graphql-kit / graphql-lodash

🛠 Data manipulation for GraphQL queries with lodash syntax
https://apis.guru/graphql-lodash/
MIT License
1.23k stars 50 forks source link

Check for null FieldNode directives and add Apollo Link usage example #13

Closed csboling closed 6 years ago

csboling commented 6 years ago

One of these changes relies on the other one to work so I thought it'd be easiest to roll them into the same PR.

The first commit just checks if node.directives is falsy before iterating over it, because it looks from the type definitions like the directives prop is optional.

The second commit adds an example of how you could use an Apollo Link, a sort of query fetching middleware, to apply the graphql-lodash transformation, which I believe is the recommended Apollo way of manipulating queries and responses like this. Since every query/mutation/subscription is run by Apollo by feeding it through the Apollo Client's chain of Links, I believe this also fixes #12.

However, using a Link like this with Apollo relies on the null directives check. This is because Apollo adds a __typename field to every object type in the outgoing query, but leaves the directives undefined instead of setting them to [] as graphql() does, so you would get:

Uncaught TypeError: Cannot read property 'length' of undefined
    at getLodashDirectiveArgs (index.js?bc07:37)
    at eval (index.js?bc07:18)
    at Object.leave (index.js?bc07:188)
    at visit (visitor.js?a6ec:229)
    at traverse (index.js?bc07:173)
    at traverseOperationFields (index.js?bc07:171)
    at Object.graphqlLodash (index.js?bc07:17)

I also added a remark to the README on how you can extend the introspection query results to add the graphql-lodash directives, which could be important for certain applications. For instance, I figured out how to do this by reading your demo/ app while trying to integrate this library with graphql-playground, which uses Apollo Links for query fetching.

IvanGoncharov commented 6 years ago

@csboling Thanks for PR and detailed explanation 🎉

IvanGoncharov commented 6 years ago

@csboling published 1.3.3 NPM 📦 🎉

csboling commented 6 years ago

Awesome, thanks for that quick turnaround.