@graphql-codegen/near-operation-file-preset
Version:
GraphQL Code Generator preset for generating operation code near the operation file
70 lines (69 loc) • 3.48 kB
JavaScript
import { Kind, } from 'graphql';
import { isUsingTypes } from '@graphql-codegen/plugin-helpers';
import { generateImportStatement, resolveImportSource, } from '@graphql-codegen/visitor-plugin-common';
import buildFragmentResolver from './fragment-resolver.js';
/**
* Transform the preset's provided documents into single-file generator sources, while resolving fragment and user-defined imports
*
* Resolves user provided imports and fragment imports using the `DocumentImportResolverOptions`.
* Does not define specific plugins, but rather returns a string[] of `importStatements` for the calling plugin to make use of
*/
export function resolveDocumentImports(presetOptions, schemaObject, importResolverOptions, // Original type is `schemaTypesSource: string | ImportSource`. We manually override `schemaTypesSource` type because we only use the `ImportSource` use case
dedupeFragments = false) {
const resolveFragments = buildFragmentResolver(importResolverOptions, presetOptions, schemaObject, dedupeFragments);
const { baseOutputDir, documents } = presetOptions;
const { generateFilePath, schemaTypesSource, baseDir, typesImport } = importResolverOptions;
return documents
.filter(documentFile => documentFile.type !== 'external')
.map(documentFile => {
try {
const meta = {
operations: [],
fragments: [],
};
for (const definition of documentFile.document.definitions) {
if (definition.kind === Kind.OPERATION_DEFINITION) {
meta.operations.push(definition);
}
else if (definition.kind === Kind.FRAGMENT_DEFINITION) {
meta.fragments.push(definition);
}
}
const generatedFilePath = generateFilePath({ location: documentFile.location, meta });
const importStatements = [];
const { externalFragments, fragmentImports } = resolveFragments(generatedFilePath, documentFile.document);
const externalFragmentsInjectedDocument = {
...documentFile.document,
definitions: [
...documentFile.document.definitions,
...externalFragments.map(fragment => fragment.node),
],
};
if (isUsingTypes(externalFragmentsInjectedDocument, [], schemaObject) &&
schemaTypesSource.namespace) {
const schemaTypesImportStatement = generateImportStatement({
baseDir,
emitLegacyCommonJSImports: presetOptions.config.emitLegacyCommonJSImports,
importExtension: presetOptions.config.importExtension,
importSource: resolveImportSource(schemaTypesSource),
baseOutputDir,
outputPath: generatedFilePath,
typesImport,
});
importStatements.unshift(schemaTypesImportStatement);
}
return {
filename: generatedFilePath,
documents: [documentFile],
importStatements,
fragmentImports,
externalFragments,
};
}
catch (e) {
throw new Error(`Unable to validate GraphQL document! \n
File ${documentFile.location} caused error:
${e.message || e.toString()}`);
}
});
}