1 | import { parse, buildClientSchema, isSchema } from 'graphql';
|
2 | import { isSchemaAst, isSchemaJson, isSchemaText, isWrappedSchemaJson, pick } from './helpers.js';
|
3 | const identifiersToLookFor = ['default', 'schema', 'typeDefs', 'data'];
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | export function pickExportFromModule({ module, filepath }) {
|
9 | ensureModule({ module, filepath });
|
10 | return resolveModule(ensureExports({ module, filepath }));
|
11 | }
|
12 |
|
13 |
|
14 |
|
15 | export function pickExportFromModuleSync({ module, filepath }) {
|
16 | ensureModule({ module, filepath });
|
17 | return resolveModuleSync(ensureExports({ module, filepath }));
|
18 | }
|
19 |
|
20 | async function resolveModule(identifiers) {
|
21 | const exportValue = await pick(await identifiers, identifiersToLookFor);
|
22 | return resolveExport(exportValue);
|
23 | }
|
24 | function resolveModuleSync(identifiers) {
|
25 | const exportValue = pick(identifiers, identifiersToLookFor);
|
26 | return resolveExport(exportValue);
|
27 | }
|
28 |
|
29 | function ensureModule({ module, filepath }) {
|
30 | if (!module) {
|
31 | throw new Error(`Invalid export from export file ${filepath}: empty export!`);
|
32 | }
|
33 | }
|
34 | function ensureExports({ module, filepath }) {
|
35 | const identifiers = pick(module, identifiersToLookFor);
|
36 | if (!identifiers) {
|
37 | throw new Error(`Invalid export from export file ${filepath}: missing default export or 'schema' export!`);
|
38 | }
|
39 | return identifiers;
|
40 | }
|
41 |
|
42 | function resolveExport(fileExport) {
|
43 | try {
|
44 | if (isSchema(fileExport)) {
|
45 | return fileExport;
|
46 | }
|
47 | if (isSchemaText(fileExport)) {
|
48 | return parse(fileExport);
|
49 | }
|
50 | if (isWrappedSchemaJson(fileExport)) {
|
51 | return buildClientSchema(fileExport.data);
|
52 | }
|
53 | if (isSchemaJson(fileExport)) {
|
54 | return buildClientSchema(fileExport);
|
55 | }
|
56 | if (isSchemaAst(fileExport)) {
|
57 | return fileExport;
|
58 | }
|
59 | return null;
|
60 | }
|
61 | catch (e) {
|
62 | throw new Error('Exported schema must be of type GraphQLSchema, text, AST, or introspection JSON.');
|
63 | }
|
64 | }
|