UNPKG

2.76 kBJavaScriptView Raw
1import { resolve } from 'path';
2import { DetailedError } from './errors';
3import { buildSchema } from './merge-schemas';
4import { validateGraphQlDocuments, checkValidationErrors } from 'graphql-toolkit';
5export async function getPluginByName(name, pluginLoader) {
6 const possibleNames = [
7 `graphql-codegen-${name}`,
8 `graphql-codegen-${name}-template`,
9 `codegen-${name}`,
10 `codegen-${name}-template`,
11 name
12 ];
13 const possibleModules = possibleNames.concat(resolve(process.cwd(), name));
14 for (const moduleName of possibleModules) {
15 try {
16 return pluginLoader(moduleName);
17 }
18 catch (err) {
19 if (err.message.indexOf(`Cannot find module '${moduleName}'`) === -1) {
20 throw new DetailedError(`Unable to load template plugin matching ${name}`, `
21 Unable to load template plugin matching '${name}'.
22 Reason:
23 ${err.message}
24 `);
25 }
26 }
27 }
28 const possibleNamesMsg = possibleNames
29 .map(name => `
30 - ${name}
31 `.trimRight())
32 .join('');
33 throw new DetailedError(`Unable to find template plugin matching ${name}`, `
34 Unable to find template plugin matching '${name}'
35 Install one of the following packages:
36
37 ${possibleNamesMsg}
38 `);
39}
40export async function executePlugin(options, pluginPackage) {
41 if (!pluginPackage || !pluginPackage.plugin || typeof pluginPackage.plugin !== 'function') {
42 throw new DetailedError(`Invalid Custom Plugin "${options.name}"`, `
43 Plugin ${options.name} does not export a valid JS object with "plugin" function.
44
45 Make sure your custom plugin is written in the following form:
46
47 module.exports = {
48 plugin: (schema, documents, config) => {
49 return 'my-custom-plugin-content';
50 },
51 };
52 `);
53 }
54 const outputSchema = buildSchema(options.schema);
55 if (outputSchema && options.documents.length > 0) {
56 const errors = validateGraphQlDocuments(outputSchema, options.documents);
57 checkValidationErrors(errors);
58 }
59 if (pluginPackage.validate && typeof pluginPackage.validate === 'function') {
60 try {
61 await pluginPackage.validate(outputSchema, options.documents, options.config, options.outputFilename, options.allPlugins);
62 }
63 catch (e) {
64 throw new DetailedError(`Plugin "${options.name}" validation failed:`, `
65 ${e.message}
66 `);
67 }
68 }
69 return pluginPackage.plugin(outputSchema, options.documents, options.config, {
70 outputFile: options.outputFilename
71 });
72}
73//# sourceMappingURL=execute-plugin.js.map
\No newline at end of file