Last active
November 18, 2017 09:03
-
-
Save sbrichardson/460db0fca1ebdc08932e99423229cd55 to your computer and use it in GitHub Desktop.
Will build a mongodb fields list filter from a graphql query resolver
This file contains 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
/////////////////// | |
// 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