Repository navigation
Expand file tree
/
Copy pathexecute-plugin.ts
More file actions
90 lines (83 loc) · 2.47 KB
/
Copy pathexecute-plugin.ts
File metadata and controls
90 lines (83 loc) · 2.47 KB
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
81
82
83
84
85
86
87
88
89
90
import { buildASTSchema, DocumentNode, GraphQLSchema } from 'graphql';
import {
CodegenPlugin,
createNoopProfiler,
Profiler,
Types,
} from '@graphql-codegen/plugin-helpers';
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 || 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();
const validate = plugin.validate?.bind(plugin);
if (validate && typeof validate === 'function') {
try {
// FIXME: Sync validate signature with plugin signature
await profiler.run(
async () =>
validate(
outputSchema,
documents,
options.config,
options.outputFilename,
options.allPlugins,
pluginContext,
),
`Plugin ${options.name} validate`,
);
} catch (e: any) {
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`,
);
}