UNPKG

@apollo/gateway

Version:
106 lines 3.44 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isObjectOfType = exports.applyRewrites = void 0; const federation_internals_1 = require("@apollo/federation-internals"); const graphql_1 = require("graphql"); const FRAGMENT_PREFIX = '... on '; function applyRewrites(schema, rewrites, value) { if (!rewrites) { return; } for (const rewrite of rewrites) { applyRewrite(schema, rewrite, value); } } exports.applyRewrites = applyRewrites; function applyRewrite(schema, rewrite, value) { const splitted = splitPathLastElement(rewrite.path); if (!splitted) { return; } const [parent, last] = splitted; const { kind, value: fieldName } = parsePathElement(last); (0, federation_internals_1.assert)(kind === 'fieldName', () => `Unexpected fragment as last element of ${rewrite.path}`); applyAtPath(schema, parent, value, rewriteAtPathFunction(rewrite, fieldName)); } function rewriteAtPathFunction(rewrite, fieldAtPath) { switch (rewrite.kind) { case 'ValueSetter': return (obj) => { obj[fieldAtPath] = rewrite.setValueTo; }; case 'KeyRenamer': return (obj) => { const objAtPath = obj[fieldAtPath]; if (objAtPath) { obj[rewrite.renameKeyTo] = obj[fieldAtPath]; obj[fieldAtPath] = undefined; } }; } } function splitPathLastElement(path) { if (path.length === 0) { return undefined; } const lastIdx = path.length - 1; return [path.slice(0, lastIdx), path[lastIdx]]; } function applyAtPath(schema, path, value, fct) { if (Array.isArray(value)) { for (const arrayValue of value) { applyAtPath(schema, path, arrayValue, fct); } return; } if (typeof value !== 'object' || value === null) { return; } if (path.length === 0) { fct(value); return; } const [first, ...rest] = path; const { kind, value: eltValue } = parsePathElement(first); switch (kind) { case 'fieldName': applyAtPath(schema, rest, value[eltValue], fct); break; case 'typeName': if (isObjectOfType(schema, value, eltValue, true)) { applyAtPath(schema, rest, value, fct); } break; } } function parsePathElement(elt) { if (elt.startsWith(FRAGMENT_PREFIX)) { return { kind: 'typeName', value: elt.slice(FRAGMENT_PREFIX.length) }; } else { return { kind: 'fieldName', value: elt }; } } function isObjectOfType(schema, obj, typeCondition, defaultOnUnknownObjectType = false) { const objTypename = obj['__typename']; if (!objTypename) { return defaultOnUnknownObjectType; } if (typeCondition === objTypename) { return true; } const type = schema.getType(objTypename); if (!type) { return false; } const conditionalType = schema.getType(typeCondition); if (!conditionalType) { return false; } if ((0, graphql_1.isAbstractType)(conditionalType)) { return ((0, graphql_1.isObjectType)(type) || (0, graphql_1.isInterfaceType)(type)) && schema.isSubType(conditionalType, type); } return false; } exports.isObjectOfType = isObjectOfType; //# sourceMappingURL=dataRewrites.js.map