/
execute-plugin.ts
80 lines (73 loc) · 2.42 KB
/
execute-plugin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { Types, CodegenPlugin, Profiler, createNoopProfiler } from '@graphql-codegen/plugin-helpers';
import { DocumentNode, GraphQLSchema, buildASTSchema } from 'graphql';
export interface ExecutePluginOptions {
name: string;
config: Types.PluginConfig;
parentConfig: Types.PluginConfig;
schema: DocumentNode;
schemaAst?: GraphQLSchema;
documents: Types.DocumentFile[];
outputFilename: string;
allPlugins: Types.ConfiguredPlugin[];
skipDocumentsValidation?: Types.SkipDocumentsValidationOptions;
pluginContext?: { [key: string]: any };
profiler?: Profiler;
}
export async function executePlugin(options: ExecutePluginOptions, plugin: CodegenPlugin): Promise<Types.PluginOutput> {
if (!plugin || !plugin.plugin || typeof plugin.plugin !== 'function') {
throw new Error(
`Invalid Custom Plugin "${options.name}" \n
Plugin ${options.name} does not export a valid JS object with "plugin" function.
Make sure your custom plugin is written in the following form:
module.exports = {
plugin: (schema, documents, config) => {
return 'my-custom-plugin-content';
},
};
`
);
}
const outputSchema: GraphQLSchema = options.schemaAst || buildASTSchema(options.schema, options.config as any);
const documents = options.documents || [];
const pluginContext = options.pluginContext || {};
const profiler = options.profiler ?? createNoopProfiler();
if (plugin.validate && typeof plugin.validate === 'function') {
try {
// FIXME: Sync validate signature with plugin signature
await profiler.run(
async () =>
plugin.validate(
outputSchema,
documents,
options.config,
options.outputFilename,
options.allPlugins,
pluginContext
),
`Plugin ${options.name} validate`
);
} catch (e) {
throw new Error(
`Plugin "${options.name}" validation failed: \n
${e.message}
`
);
}
}
return profiler.run(
() =>
Promise.resolve(
plugin.plugin(
outputSchema,
documents,
typeof options.config === 'object' ? { ...options.config } : options.config,
{
outputFile: options.outputFilename,
allPlugins: options.allPlugins,
pluginContext,
}
)
),
`Plugin ${options.name} execution`
);
}