Regarding dynamic field selection in apollo-server

Regarding dynamic field selection in apollo-server


0

I’m using apollo GraphQL for backend and frontend. I want to dynamically select fields which are requested by the client.

With the help of info argument I created a function which gives me selected fields by client and based on that I fetch selected fields from db.

Resolver

  selection.fields = .extractSelection(info?.fieldNodes[0]?.selectionSet)

function implementation

.extractSelection = (selectionSet) => {
  const subSelection = {}

  if (selectionSet) {
    selectionSet?.selections?.forEach(selection => {
      if (selection?.selectionSet) {
        if (selection.kind === 'InlineFragment') Object.assign(subSelection, .extractSelection(selection?.selectionSet))
        else subSelection[selection?.name?.value] = .extractSelection(selection?.selectionSet)
      } else {
        subSelection[selection?.name?.value] = 1
      }
    })
  }

  return subSelection
}

I have some Doubt regarding this implementation .
is it good to execute this function for field selection per request?
is another way exist to do implementation of this thing?

I just need to know if this is good or are there better solutions?


Load 4 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *