Created
January 10, 2024 07:40
-
-
Save LunaticMuch/b21c7ad523c648e5d320b4d3508c80a6 to your computer and use it in GitHub Desktop.
find parents in a graphql query
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
import _ from "lodash"; | |
export function addParent(schema) { | |
function extractFields(type) { | |
// no need to inspect circular types any further | |
if (type.type === "[Circular]") return [type]; | |
// same with scalars and enums | |
if (_.includes(["SCALAR", "ENUM"], type.kind && type.kind)) return []; | |
if ( | |
type.type && | |
type.type.kind && | |
_.includes(["SCALAR", "ENUM"], type.type.kind) | |
) | |
return []; | |
return _.flatMap(_.values(type.fields), (currentType) => { | |
// if it's a composite object, use recursion to introspect the inner object | |
const innerTypes = currentType.type.fields | |
? _.flatMap(currentType.type.fields, (subType) => | |
extractFields(subType) | |
) | |
: [currentType]; | |
// dedupe types by their id | |
return _.uniqBy(_.concat(innerTypes, currentType), (x) => x.name); | |
}); | |
} | |
const allFields = _.flatMap(schema, (type) => | |
extractFields(type) | |
); | |
/* | |
* Group fields by their corresponding type id | |
*/ | |
const groupedFieldsByType = _.groupBy(allFields, function (field) { | |
return field.type.name; | |
}); | |
/* | |
* Extract id and prepare the mapping | |
*/ | |
const mappings = _.mapValues(groupedFieldsByType, function (t) { | |
return _.map(t, (field) => field.name); | |
}); | |
// console.log(mappings) | |
/* | |
* Assign the mapping | |
*/ | |
// _.each(schema, (type) => { | |
// if (mappings[type]) { | |
// (schema.types[type]).parents = mappings[type]; | |
// } | |
// }) | |
const schmeaAdded = schema.map((type) => { | |
const { name } = type | |
return mappings[name] ? Object.assign(type, {parents: mappings[name]}) : type | |
}) | |
console.log(schmeaAdded) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment