UNPKG

graphql-add-id-document-transform

Version:

GraphQL document transform ensuring cache normalization by adding an `id` field if available

72 lines (69 loc) 2.49 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { addIdDocumentTransform: () => addIdDocumentTransform }); module.exports = __toCommonJS(index_exports); // src/addIdDocumentTransform.ts var import_graphql = require("graphql"); var addIdDocumentTransform = { transform: ({ schema: astSchema, documents }) => { const schema = (0, import_graphql.buildASTSchema)(astSchema); const typeInfo = new import_graphql.TypeInfo(schema); return documents.map((documentFile) => { if (!documentFile.document) { return documentFile; } documentFile.document = (0, import_graphql.visit)( documentFile.document, (0, import_graphql.visitWithTypeInfo)(typeInfo, { SelectionSet(node) { const parentType = typeInfo.getParentType(); if ((0, import_graphql.isObjectType)(parentType)) { const fields = parentType.getFields(); const selectionHasIdField = node.selections.some( (selection) => selection.kind === import_graphql.Kind.FIELD && selection.name.value === "id" ); if ("id" in fields && !selectionHasIdField) { node.selections = [ ...node.selections, { kind: import_graphql.Kind.FIELD, name: { kind: import_graphql.Kind.NAME, value: "id" } } ]; } } return node; } }) ); return documentFile; }); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { addIdDocumentTransform });