Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting selectionSet from fieldASTs with external fragment #96

Closed
gyzerok opened this issue Jul 30, 2015 · 14 comments
Closed

Getting selectionSet from fieldASTs with external fragment #96

gyzerok opened this issue Jul 30, 2015 · 14 comments

Comments

@gyzerok
Copy link

gyzerok commented Jul 30, 2015

How can I get fields requested in external fragment from fieldASTs?

Consider following query

`
  query QueryWithFragment {
    todo(_id: "55a624bad009804e552eeea8") {
      ...TextFragment
    }
  }

  fragment TextFragment on Todo {
    text
  }
`

This query results in following, so there is no way to get those fields without directly parsing query string.

{
  "kind": "Field",
  "alias": null,
  "name": {
    "kind": "Name",
    "value": "todo",
    "loc": {
      "start": 27,
      "end": 31,
      "source": {
        "body": "\n  query UseFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ...TextFragment\n    }\n  }\n\n  fragment TextFragment on Todo {\n    text\n  }\n",
        "name": "GraphQL request"
      }
    }
  },
  "arguments": [{
    "kind": "Argument",
    "name": {
      "kind": "Name",
      "value": "_id",
      "loc": {
        "start": 32,
        "end": 35,
        "source": {
          "body": "\n  query UseFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ...TextFragment\n    }\n  }\n\n  fragment TextFragment on Todo {\n    text\n  }\n",
          "name": "GraphQL request"
        }
      }
    },
    "value": {
      "kind": "StringValue",
      "value": "55a624bad009804e552eeea8",
      "loc": {
        "start": 37,
        "end": 63,
        "source": {
          "body": "\n  query UseFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ...TextFragment\n    }\n  }\n\n  fragment TextFragment on Todo {\n    text\n  }\n",
          "name": "GraphQL request"
        }
      }
    },
    "loc": {
      "start": 32,
      "end": 63,
      "source": {
        "body": "\n  query UseFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ...TextFragment\n    }\n  }\n\n  fragment TextFragment on Todo {\n    text\n  }\n",
        "name": "GraphQL request"
      }
    }
  }],
  "directives": [],
  "selectionSet": {
    "kind": "SelectionSet",
    "selections": [{
      "kind": "FragmentSpread",
      "name": {
        "kind": "Name",
        "value": "TextFragment",
        "loc": {
          "start": 76,
          "end": 88,
          "source": {
            "body": "\n  query UseFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ...TextFragment\n    }\n  }\n\n  fragment TextFragment on Todo {\n    text\n  }\n",
            "name": "GraphQL request"
          }
        }
      },
      "directives": [],
      "loc": {
        "start": 73,
        "end": 88,
        "source": {
          "body": "\n  query UseFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ...TextFragment\n    }\n  }\n\n  fragment TextFragment on Todo {\n    text\n  }\n",
          "name": "GraphQL request"
        }
      }
    }],
    "loc": {
      "start": 65,
      "end": 94,
      "source": {
        "body": "\n  query UseFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ...TextFragment\n    }\n  }\n\n  fragment TextFragment on Todo {\n    text\n  }\n",
        "name": "GraphQL request"
      }
    }
  },
  "loc": {
    "start": 27,
    "end": 94,
    "source": {
      "body": "\n  query UseFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ...TextFragment\n    }\n  }\n\n  fragment TextFragment on Todo {\n    text\n  }\n",
      "name": "GraphQL request"
    }
  }
}

Now lets take a look in InlineFragment version

`
  query QueryWithoutFragment {
    todo(_id: "55a624bad009804e552eeea8") {
      ... on Todo {
        text
      }
    }
  }
`

We can easily access requested fields for fragment in selectionSet

{
  "kind": "Field",
  "alias": null,
  "name": {
    "kind": "Name",
    "value": "todo",
    "loc": {
      "start": 36,
      "end": 40,
      "source": {
        "body": "\n  query QueryWithoutFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ... on Todo {\n        text\n      }\n    }\n  }\n",
        "name": "GraphQL request"
      }
    }
  },
  "arguments": [{
    "kind": "Argument",
    "name": {
      "kind": "Name",
      "value": "_id",
      "loc": {
        "start": 41,
        "end": 44,
        "source": {
          "body": "\n  query QueryWithoutFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ... on Todo {\n        text\n      }\n    }\n  }\n",
          "name": "GraphQL request"
        }
      }
    },
    "value": {
      "kind": "StringValue",
      "value": "55a624bad009804e552eeea8",
      "loc": {
        "start": 46,
        "end": 72,
        "source": {
          "body": "\n  query QueryWithoutFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ... on Todo {\n        text\n      }\n    }\n  }\n",
          "name": "GraphQL request"
        }
      }
    },
    "loc": {
      "start": 41,
      "end": 72,
      "source": {
        "body": "\n  query QueryWithoutFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ... on Todo {\n        text\n      }\n    }\n  }\n",
        "name": "GraphQL request"
      }
    }
  }],
  "directives": [],
  "selectionSet": {
    "kind": "SelectionSet",
    "selections": [{
      "kind": "InlineFragment",
      "typeCondition": {
        "kind": "Name",
        "value": "Todo",
        "loc": {
          "start": 89,
          "end": 93,
          "source": {
            "body": "\n  query QueryWithoutFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ... on Todo {\n        text\n      }\n    }\n  }\n",
            "name": "GraphQL request"
          }
        }
      },
      "directives": [],
      "selectionSet": {
        "kind": "SelectionSet",
        "selections": [{
          "kind": "Field",
          "alias": null,
          "name": {
            "kind": "Name",
            "value": "text",
            "loc": {
              "start": 104,
              "end": 108,
              "source": {
                "body": "\n  query QueryWithoutFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ... on Todo {\n        text\n      }\n    }\n  }\n",
                "name": "GraphQL request"
              }
            }
          },
          "arguments": [],
          "directives": [],
          "selectionSet": null,
          "loc": {
            "start": 104,
            "end": 108,
            "source": {
              "body": "\n  query QueryWithoutFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ... on Todo {\n        text\n      }\n    }\n  }\n",
              "name": "GraphQL request"
            }
          }
        }],
        "loc": {
          "start": 94,
          "end": 116,
          "source": {
            "body": "\n  query QueryWithoutFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ... on Todo {\n        text\n      }\n    }\n  }\n",
            "name": "GraphQL request"
          }
        }
      },
      "loc": {
        "start": 82,
        "end": 116,
        "source": {
          "body": "\n  query QueryWithoutFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ... on Todo {\n        text\n      }\n    }\n  }\n",
          "name": "GraphQL request"
        }
      }
    }],
    "loc": {
      "start": 74,
      "end": 122,
      "source": {
        "body": "\n  query QueryWithoutFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ... on Todo {\n        text\n      }\n    }\n  }\n",
        "name": "GraphQL request"
      }
    }
  },
  "loc": {
    "start": 36,
    "end": 122,
    "source": {
      "body": "\n  query QueryWithoutFragment {\n    todo(_id: \"55a624bad009804e552eeea8\") {\n      ... on Todo {\n        text\n      }\n    }\n  }\n",
      "name": "GraphQL request"
    }
  }
}

I'm currently working on conversion fieldASTs to MongoDB projections. I've done with InlineFragment. Any thoughts?

@leebyron
Copy link
Contributor

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?

@gyzerok
Copy link
Author

gyzerok commented Jul 31, 2015

@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.

@leebyron
Copy link
Contributor

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"

@gyzerok
Copy link
Author

gyzerok commented Jul 31, 2015

@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';
    }
  }, {});
}

@hekike
Copy link

hekike commented Aug 1, 2015

@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.

@leebyron
Copy link
Contributor

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

@hekike
Copy link

hekike commented Aug 12, 2015

@leebyron thanks!

@Sandreu
Copy link

Sandreu commented Sep 6, 2015

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]
}

@Sandreu
Copy link

Sandreu commented Sep 7, 2015

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

@parkan
Copy link

parkan commented Sep 28, 2015

@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?

@Sandreu
Copy link

Sandreu commented Sep 29, 2015

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...

@ansarizafar
Copy link

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

@Sandreu
Copy link

Sandreu commented Nov 11, 2015

@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...

@jakepusateri
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants