Last active
March 20, 2020 05:06
-
-
Save the-vampiire/3d4875ef51c18c20fa3a53fd9307aa63 to your computer and use it in GitHub Desktop.
5 line Apollo Server GraphQL Type resolver efficiency proof of concept
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const mapAttributes = (model, { fieldNodes }) => { | |
| // get the fields of the Model (columns of the table) | |
| const columns = new Set(Object.keys(model.rawAttributes)); | |
| const requested_attributes = fieldNodes[0].selectionSet.selections | |
| .map(({ name: { value } }) => value); | |
| // filter the attributes against the columns | |
| return requested_attributes.filter(attribute => columns.has(attribute)); | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ... | |
| User: async ( | |
| _, // instance (not used in Type resolver) | |
| { username, ... }, // arguments | |
| { models: { User }, ... }, // context | |
| info, | |
| ) => { | |
| if (username) { | |
| // before (entire row queried) | |
| // return User.findOne({ where: { username } }); ... | |
| // after (only requested columns queried) | |
| return User.findOne({ | |
| where: { username }, | |
| attributes: mapAttributes(User, info), | |
| }); | |
| } ... | |
| } | |
| ... |
Author
nice man. thanks for the update. do you have a medium account? i can update the article and credit you
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey there, I ran into some issues when running this with a nested selection set i.e.
To help resolve this, I came up with the following edits:
Hope this helps!