Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if (graphqlFiles && graphqlFiles.length > 0) {
for (const graphqlFile of graphqlFiles) {
const content = (await fs.readFile(graphqlFile)).toString();
const document = parse(content);
documents.push({
content: document,
filePath: graphqlFile,
});
}
config.documents = documents;
await fs.ensureDir(path.dirname(gqlGenOutput));
// Make all properties optional to retain backwards compatibility
const typesContent = (await codegen(config)).replace(/ ([a-zA-Z_\-0-9]+): Maybe/g, ` $1?: Maybe`);
// Write the new types.ts content back out
await fs.writeFile(gqlGenOutput, `/* tslint:disable */\n\n${typesContent}`, "utf8");
}
process.exit(0);
} catch (e) {
console.error(`Generating GraphQL types failed: ${e.message}`);
process.exit(1);
}
throw new Error("Should never get here, process.exit() called above");
}
// used by a plugin internally, although the 'typescript' plugin currently returns the string output, rather than writing to a file
filename: outputFile,
schema: parse(printSchema(schema)),
plugins: [{ typescript: { skipTypename: true, avoidOptionals: true } }, { typescriptOperations: {} }],
documents: [], //needed, for now
pluginMap: {
typescript: {
plugin: typescriptPlugin
},
typescriptOperations: {
plugin: typescriptOperationsPlugin
}
}
};
const output = await codegen(config);
fs.writeFileSync(outputFile, additionalTypes + "\n\n" + output);
console.log("TypeScript Types Generated!");
}
export const loadSchema = async (schemaPointers: UnnormalizedTypeDefPointer, config: Types.Config, out?: 'GraphQLSchema' | 'DocumentNode'): Promise => {
try {
const loaders = [new CodeFileLoader(), new GitLoader(), new GithubLoader(), new GraphQLFileLoader(), new JsonFileLoader(), new UrlLoader(), new ApolloEngineLoader(), new PrismaLoader()];
if (out === 'DocumentNode') {
const documents = await loadTypedefsUsingLoaders(loaders, schemaPointers, config);
return mergeTypeDefs(documents.map(doc => doc.document));
} else {
const schema = await loadSchemaUsingLoaders(loaders, schemaPointers, config);
return schema;
}
} catch (e) {
throw new DetailedError(
'Failed to load schema',
`
Failed to load schema from ${Object.keys(schemaPointers).join(',')}:
${e.message || e}
${e.stack || ''}
GraphQL Code Generator supports:
- ES Modules and CommonJS exports (export as default or named export "schema")
- Introspection JSON File
- URL of GraphQL endpoint
- Multiple files with type definitions (glob expression)
- String in config file
Try to use one of above options and run codegen again.
Please make sure the --config points to a correct file.
`
);
}
throw new DetailedError(
`Unable to find Codegen config file!`,
`
Please make sure that you have a configuration file under the current directory!
`
);
}
if (result.isEmpty) {
throw new DetailedError(
`Found Codegen config file but it was empty!`,
`
Please make sure that you have a valid configuration file under the current directory!
`
);
}
return new CodegenContext({
filepath: result.filepath,
config: result.config as Types.Config,
});
}
${err.message}
`
);
}
}
}
const possibleNamesMsg = possibleNames
.map(name =>
`
- ${name}
`.trimRight()
)
.join('');
throw new DetailedError(
`Unable to find template plugin matching ${name}`,
`
Unable to find template plugin matching '${name}'
Install one of the following packages:
${possibleNamesMsg}
`
);
}
It should looks like that:
schema:
- my-schema.graphql
generates:
my-file.ts:
- plugin1
- plugin2
- plugin3
`
);
}
}
if (rootSchemas.length === 0 && Object.keys(generates).some(filename => !generates[filename].schema || generates[filename].schema.length === 0)) {
throw new DetailedError(
'Invalid Codegen Configuration!',
`
Please make sure that your codegen config file contains either the "schema" field
or every generated file has its own "schema" field.
It should looks like that:
schema:
- my-schema.graphql
or:
generates:
path/to/output:
schema: my-schema.graphql
`
);
}
for (const enumTypeName of allEnums) {
const enumType = schema.getType(enumTypeName) as GraphQLEnumType;
for (const { name, value } of enumType.getValues()) {
if (value && value !== name) {
mapOrStr[enumTypeName] = mapOrStr[enumTypeName] || {};
if (typeof mapOrStr[enumTypeName] !== 'string' && !mapOrStr[enumTypeName][name]) {
mapOrStr[enumTypeName][name] = value;
}
}
}
}
const invalidMappings = Object.keys(mapOrStr).filter(gqlName => !allEnums.includes(gqlName));
if (invalidMappings.length > 0) {
throw new DetailedError(`Invalid 'enumValues' mapping!`, `The following types does not exist in your GraphQL schema: ${invalidMappings.join(', ')}`);
}
return Object.keys(mapOrStr).reduce((prev, gqlIdentifier) => {
const pointer = mapOrStr[gqlIdentifier];
if (typeof pointer === 'string') {
const mapper = parseMapper(pointer, gqlIdentifier);
return {
...prev,
[gqlIdentifier]: {
typeIdentifier: gqlIdentifier,
sourceFile: mapper.isExternal ? mapper.source : undefined,
sourceIdentifier: mapper.type,
mappedValues: null,
},
return async (schema) => {
const config = await createConfigFromSchema(schema)
const output = await codegen(config)
return fs.writeFile(config.filename, output)
}
}
const process = async (outputArgs: Types.GenerateOptions) => {
const output = await codegen(outputArgs);
result.push({
filename: outputArgs.filename,
content: output,
hooks: outputConfig.hooks || {},
});
};
return async (schema) => {
const config = await createConfigFromSchema(schema)
const output = await codegen(config)
return fs.writeFile(config.filename, output)
}
}