@graphql-codegen/named-operations-object
Version:
GraphQL Code Generator plugin for generating an enum with all loaded operations, for simpler and type-safe access
53 lines (52 loc) • 1.98 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.plugin = void 0;
const change_case_all_1 = require("change-case-all");
const graphql_1 = require("graphql");
const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers");
const plugin = (schema, documents, config) => {
const identifierName = config.identifierName || 'namedOperations';
const allAst = (0, graphql_1.concatAST)(documents.map(v => v.document));
const allOperationsNames = {
query: new Set(),
mutation: new Set(),
subscription: new Set(),
fragment: new Set(),
};
(0, plugin_helpers_1.oldVisit)(allAst, {
enter: {
OperationDefinition: node => {
var _a;
if ((_a = node.name) === null || _a === void 0 ? void 0 : _a.value) {
allOperationsNames[node.operation].add(node.name.value);
}
},
FragmentDefinition: node => {
allOperationsNames.fragment.add(node.name.value);
},
},
});
const objectItems = Object.keys(allOperationsNames)
.map(operationType => {
const relevantOperations = allOperationsNames[operationType];
if (relevantOperations && relevantOperations.size > 0) {
const rootFieldName = (0, change_case_all_1.capitalCase)(operationType);
return ` ${rootFieldName}: {
${Array.from(relevantOperations)
.map(t => ` ${t}: '${t}'${config.useConsts ? ' as const' : ''}`)
.join(',\n')}
}`;
}
return null;
})
.filter(Boolean);
if (objectItems.length === 0) {
// eslint-disable-next-line no-console
console.warn(`Plugin "named-operations-object" has an empty output, since there are no valid operations!`);
return '';
}
return `export const ${identifierName} = {
${objectItems.join(',\n')}
}`;
};
exports.plugin = plugin;
;