Code Monkey home page Code Monkey logo

Comments (14)

jakepusateri avatar jakepusateri commented on March 29, 2024 2

@Sandreu I made a library that expands on the example above and includes handling for skip and include directives: graphql-list-fields

from graphql-js.

leebyron avatar leebyron commented on March 29, 2024

I suppose the short answer is that you cannot directly get to a fragment from a field AST. There must also be a mapping of fragment name to the fragment AST.

Could you help me understand how you're using the fields and in what context you need access to the fragment definitions? Is this from within a field resolve function?

from graphql-js.

gyzerok avatar gyzerok commented on March 29, 2024

@leebyron thank you for the quick answer!

Yes, but I'm using this from query resolve function, not field resolve. Currently I'm working on mapping fieldASTs to MongoDB projections. I've done with the Field and InlineFragment, now I want to get FragmentSpread working to complete common cases of GraphQL queries.

from graphql-js.

leebyron avatar leebyron commented on March 29, 2024

Could you link me to the point in your code where this is being used? I'm afraid I don't know what you mean by "query resolve function"

from graphql-js.

gyzerok avatar gyzerok commented on March 29, 2024

@leebyron consider this

const todoQueries = {
  todo: {
    type: todoType,
    args: {
      _id: {
        name: '_id',
        type: new GraphQLNonNull(GraphQLString),
      },
    },
    resolve: (root, { _id }, source, fieldASTs) => {
      const projs = getProjection(fieldASTs);
      return Todo.findById(_id, projs);
    },
  }
};

Queries here are part of GraphQL schema. And I'm working on getProjection function. Currently it is as follows:

function getProjection(fieldASTs) {
  const { selections } = fieldASTs.selectionSet;
  return selections.reduce((projs, selection) => {
    switch (selection.kind) {
      case 'Field':
        return {
          ...projs,
          [selection.name.value]: 1
        };
      case 'InlineFragment':
        return {
          ...projs,
          ...getProjection(selection),
        };
      default:
        throw 'Unsupported query';
    }
  }, {});
}

from graphql-js.

hekike avatar hekike commented on March 29, 2024

@leebyron hi! The use case is that in graffiti-mongoose we are doing some kind of field selection (projection) with Mongoose to optimise our queries to get only the necessary data from the database.

Our issue is that currently we cannot get the required fields from graphql-js's fieldASTs if the selection.kind is FragmentSpread. (we can if it's Field or InlineFragment)

Details:
The projection in mongoose looks like this:

Model.find({ age: 26 }, {  name: 1, createdAt: 1  })

so the second parameter is the field selection.

For example from this query:

query GetUser {
  user(_id: 1) {
    ...UserFragment
    foo
  }
}
fragment UserFragment on User {
  name
}

we would like to generate the projection object below:

{
  name: 1,
  foo: 1
}

But currently we cannot read the selection fields from the selection if it's FragmentSpread.

The current workaround is that if the query contains fragment we don't do any projection and get all of the fields from the database:
RisingStack/graffiti-mongoose@25fc49c#diff-2169c493dbfb064f0cf8f5c05d6fffadR17

Any idea how can we read the required fields from FragmentSpread selection?
I'm happy to send pull-request to graphql-js but I'm not sure yet that it's an issue here or am I doing something wrong.

from graphql-js.

leebyron avatar leebyron commented on March 29, 2024

This is now solved by #119 which should be released on npm soon.

from graphql-js.

hekike avatar hekike commented on March 29, 2024

@leebyron thanks!

from graphql-js.

Sandreu avatar Sandreu commented on March 29, 2024

Hello,

Sorry to reopen this ticket, but it seems that nobody kept going with this... I need the same thing, and here is the update of @gyzerok 's code to deal with the current version :

export default function getFieldList(asts) {
  //for recursion...Fragments don't have many sets...
  if (!Array.isArray(asts)) asts = [asts]

  //get all selectionSets
  var selections = asts.reduce((selections, source) => {
    selections.push(...source.selectionSet.selections);
    return selections;
  }, []);

  //return fields
  return selections.reduce((list, ast) => {
    switch (ast.kind) {
      case 'Field' :
        list[ast.name.value] = true
        return list;
      case 'InlineFragment':
        return {
          ...list,
          ...getFieldList(ast)
        };
      case 'FragmentSpread':
        console.log(ast)
      default: 
        throw new Error('Unsuported query selection')
    }
  }, {})
}

It appears that Fieds are seen wherever they are declared, but selectionSets of FragmentSpread are not declared.

log output :

{
  kind: 'FragmentSpread',
  name: [Object],
  directives: [],
  loc: [Object]
}

from graphql-js.

Sandreu avatar Sandreu commented on March 29, 2024

Ok, I got it...
When parent's resolve is called, we don't know yet which children fields will be included! and directives aren't solved yet... When executor calls resolve, it's blind about what's next... the resolve would be called even if directives skip all children...!

The above getFieldList function could work like this :

export default function getFieldList(context, asts = context.fieldASTs) {
  //for recursion...Fragments doesn't have many sets...
  if (!Array.isArray(asts)) asts = [asts]

  //get all selectionSets
  var selections = asts.reduce((selections, source) => {
    selections.push(...source.selectionSet.selections);
    return selections;
  }, []);

  //return fields
  return selections.reduce((list, ast) => {
    switch (ast.kind) {
      case 'Field' :
        list[ast.name.value] = true
        return list;
      case 'InlineFragment':
        return {
          ...list,
          ...getFieldList(context, ast)
        };
      case 'FragmentSpread':
        return {
          ...list,
          ...getFieldList(context, context.fragments[ast.name.value])
        };
      default: 
        throw new Error('Unsuported query selection')
    }
  }, {})
}

But in fact, it doesn't really get the child list because directives are ignored... They are solved later by GQL...

I don't really know what to say about this...

What do you think ? @leebyron @dschafer @schrockn

from graphql-js.

parkan avatar parkan commented on March 29, 2024

@Sandreu can you explain the above a bit more? I'm seeing this with 0.4.4 for the first example query in this thread:

{ kind: 'FragmentDefinition',
  name:
   { kind: 'Name',
     value: 'TextFragment',
     loc: { start: 115, end: 127, source: [Object] } },
  typeCondition:
   { kind: 'NamedType',
     name: { kind: 'Name', value: 'Todo', loc: [Object] },
     loc: { start: 131, end: 135, source: [Object] } },
  directives: [],
  selectionSet:
   { kind: 'SelectionSet',
     selections: [ [Object] ],
     loc: { start: 136, end: 150, source: [Object] } },
  loc:
   { start: 106,
     end: 150,
     source:
      Source {
        body: <Buffer 20 71 75 65 72 79 20 51 75 65 72 79 57 69 74 68 46 72 61 67 6d 65 6e 74 20 7b 0a 20 20 20 20 74 6f 64 6f 28 5f 69 64 3a 20 22 35 35 61 36 32 34 62 61 ... >,
        name: 'GraphQL' } } }

and the selectionSet.selections from above:

[ { kind: 'Field',
    alias: null,
    name: { kind: 'Name', value: 'text', loc: [Object] },
    arguments: [],
    directives: [],
    selectionSet: null,
    loc: { start: 142, end: 146, source: [Object] } } ]

This looks like we have everything we need?

from graphql-js.

Sandreu avatar Sandreu commented on March 29, 2024

Hello @parkan ,

I'm not quite sure that I'm getting your question right,
But I think that is because you're looking into the text resolver... The aim here is to get the list of children fields from the parent resolver. Not a list of locations where the resolving field is requested.

Here is a complete example...

import gql, {
  graphql,
  GraphQLString,
  GraphQLSchema,
  GraphQLObjectType,
} from './src';



var test = new GraphQLObjectType({
  name: 'Test',
  fields: () => ({
    a : { type: GraphQLString, },
    b : { type: GraphQLString, },
    c : { type: GraphQLString, },
  })
});
var Queries = new GraphQLObjectType({
  name: 'Query',
  fields: () => ({
    req: {
      type: test,
      resolve: (_, inputs, context) => {
        console.log(getFieldList(context));
/*********************************
{ a: true, b: true, c: true }
*********************************/
        // Here is your request with fields selection !
        return { a:'a', b:'b', c:'c'}
      }
    }
  }),
});


var Schema = new GraphQLSchema({
  query: Queries,
});


function getFieldList(context, asts = context.fieldASTs) {
  //for recursion...Fragments doesn't have many sets...
  if (!Array.isArray(asts)) asts = [asts]

  //get all selectionSets
  var selections = asts.reduce((selections, source) => {
    selections.push(...source.selectionSet.selections);
    return selections;
  }, []);

  //return fields
  return selections.reduce((list, ast) => {
    switch (ast.kind) {
      case 'Field' :
        list[ast.name.value] = true
        return list;
      case 'InlineFragment':
        return {
          ...list,
          ...getFieldList(context, ast)
        };
      case 'FragmentSpread':
        console.log(ast)
/**********************
{ kind: 'FragmentSpread',
  name: [Object],
  directives: [],
  loc: [Object] }
*************************/
        return {
          ...list,
          ...getFieldList(context, context.fragments[ast.name.value])
        };
      default: 
        throw new Error('Unsuported query selection')
    }
  }, {})
}

graphql(Schema, '{ req { a, ...f } } fragment f on Test { b, c }');

As you can see here, the FragmentSpread does not includes selectionSet and then you have to go through context.fragments.

I gave up on querying my db only the requested fields so I don't really know about corner cases with this getFields function ! But I'm sure it doesn't handle directives...

graphql(Schema, '{ req { a, ...f @skip(if:true) } } fragment f on Test { b, c }')

Here getFields will return { a: true, b: true, c: true } event if the answer will include a only...

from graphql-js.

ansarizafar avatar ansarizafar commented on March 29, 2024

@Sandreu I am facing the same issue. Did you find the solution?

from graphql-js.

Sandreu avatar Sandreu commented on March 29, 2024

@ansarizafar A solution about what ? Getting the requested fields works with this getFieldList() function, I'm just preventing about corner cases like skip directives usage...

from graphql-js.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.