Skip to content

Instantly share code, notes, and snippets.

@sbrichardson
Last active November 18, 2017 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbrichardson/460db0fca1ebdc08932e99423229cd55 to your computer and use it in GitHub Desktop.
Save sbrichardson/460db0fca1ebdc08932e99423229cd55 to your computer and use it in GitHub Desktop.
Will build a mongodb fields list filter from a graphql query resolver
///////////////////
// makeFieldList //
///////////////////
const filterString = '_r'
const reg = new RegExp(`${filterString}$`)
/**
* @param {Object[]} fields The selectionSet selections array from the resolver info arg.
* @param {Object} [f={}] Fields object, used with recursive calls
* @param {String} [rootName] Current obeject path, used with recursive calls
* @return {Object} Mongodb fields object
*/
const makeFieldList = (fields, f = {}, rootName) => {
for (let i = 0; i < fields.length; i++) {
const val = fields[i].name.value
if (!reg.test(val)) {
const newRoot = rootName ? `${rootName}.${val}` : val
fields[i].selectionSet ? makeFieldList(fields[i].selectionSet.selections,
f, newRoot) : f[newRoot] = 1
}
}
return f
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment