UNPKG

@graphql-mesh/transform-encapsulate

Version:
75 lines (74 loc) 3.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const graphql_1 = require("graphql"); const utils_1 = require("@graphql-mesh/utils"); const utils_2 = require("@graphql-tools/utils"); const wrap_1 = require("@graphql-tools/wrap"); const OPERATION_TYPE_SUFFIX_MAP = { query: 'Query', mutation: 'Mutation', subscription: 'Subscription', }; const DEFAULT_APPLY_TO = { query: true, mutation: true, subscription: true, }; class EncapsulateTransform { constructor(options) { this.transformMap = {}; this.transforms = []; this.config = options.config; this.name = this.config?.name || options.apiName; if (!this.name) { throw new Error(`Unable to execute encapsulate transform without a name. Please make sure to use it over a specific schema, or specify a name in your configuration!`); } } *generateSchemaTransforms(originalWrappingSchema) { const applyTo = { ...DEFAULT_APPLY_TO, ...(this.config?.applyTo || {}) }; const outerTypeNames = (0, utils_2.getRootTypeMap)(originalWrappingSchema); for (const operationType in applyTo) { if (applyTo[operationType] === true) { const outerTypeName = outerTypeNames.get(operationType)?.name; if (outerTypeName) { this.transformMap[outerTypeName] = new wrap_1.WrapType(outerTypeName, `${this.name}${OPERATION_TYPE_SUFFIX_MAP[operationType]}`, this.name); } } } for (const typeName of Object.keys(this.transformMap)) { const fieldConfigMap = (0, utils_2.selectObjectFields)(originalWrappingSchema, typeName, () => true); if (Object.keys(fieldConfigMap).length) { yield this.transformMap[typeName]; } } } transformSchema(originalWrappingSchema, subschemaConfig, transformedSchema) { this.transforms = [...this.generateSchemaTransforms(originalWrappingSchema)]; return (0, utils_1.applySchemaTransforms)(originalWrappingSchema, subschemaConfig, transformedSchema, this.transforms); } transformRequest(originalRequest, delegationContext, transformationContext) { const transformedRequest = (0, utils_1.applyRequestTransforms)(originalRequest, delegationContext, transformationContext, this.transforms); if (delegationContext.operation === 'subscription') { transformedRequest.document = { ...transformedRequest.document, definitions: transformedRequest.document.definitions.map(def => { if (def.kind === graphql_1.Kind.OPERATION_DEFINITION) { return { ...def, selectionSet: { ...def.selectionSet, selections: def.selectionSet.selections.filter(selection => selection.kind === graphql_1.Kind.FIELD && selection.name.value !== '__typename'), }, }; } return def; }), }; } return transformedRequest; } transformResult(originalResult, delegationContext, transformationContext) { return (0, utils_1.applyResultTransforms)(originalResult, delegationContext, transformationContext, this.transforms); } } exports.default = EncapsulateTransform;