UNPKG

graphql-codegen-typescript-operations-tester

Version:
73 lines 2.91 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.request = exports.plugin = void 0; const change_case_all_1 = require("change-case-all"); const graphql_1 = require("graphql"); function getOperationFragments(node, allFragments, operationFragments) { const fragments = operationFragments || new Map(); graphql_1.visit(node, { FragmentSpread: { enter(node) { const fragment = allFragments.get(node.name.value); if (fragment) { fragments.set(node.name.value, fragment); getOperationFragments(fragment, allFragments, fragments); } else { throw new Error('Unknown fragment: ' + node.name.value); } }, }, }); return fragments; } const plugin = (schema, documents, config) => { const imports = [`import { request, Args } from 'graphql-codegen-typescript-operations-tester'`]; const prefix = config.prefix || 'test'; const allAst = graphql_1.concatAST(documents.reduce((acc, source) => { if (source.document) { acc.push(source.document); } return acc; }, [])); const allFragments = new Map(); graphql_1.visit(allAst, { FragmentDefinition(node) { allFragments.set(node.name.value, node); }, }); const lines = []; graphql_1.visit(allAst, { OperationDefinition(node) { if (!node.name) return; const type = node.operation === 'mutation' ? 'Mutation' : 'Query'; // Mimic the default naming convention. // See https://www.graphql-code-generator.com/docs/getting-started/naming-convention#namingconvention const name = change_case_all_1.pascalCase(`${node.name.value}${type}`); const fragments = getOperationFragments(node, allFragments); const fragmentsStr = fragments.size > 0 ? `${Array.from(fragments.values()).map(graphql_1.print)}\n` : ''; lines.push(``); lines.push(`export const ${name}Source: string = \``); lines.push(`${fragmentsStr}${graphql_1.print(node)}\`;`); lines.push(``); lines.push(`export function ${prefix}${name}(`); lines.push(` graphqlArgs: Args,`); lines.push(` variables?: ${name}Variables`); lines.push(`) {`); lines.push(` return request<${name}>({ ...graphqlArgs, source: ${name}Source, variableValues: variables })`); lines.push(`};`); }, }); const content = lines.join('\n'); return { prepend: imports, content: content, }; }; exports.plugin = plugin; async function request(graphqlArgs) { return graphql_1.graphql(graphqlArgs); } exports.request = request; //# sourceMappingURL=index.js.map