UNPKG

2.11 kBJavaScriptView Raw
1import { parse, buildClientSchema, isSchema } from 'graphql';
2import { isSchemaAst, isSchemaJson, isSchemaText, isWrappedSchemaJson, pick } from './helpers.js';
3const identifiersToLookFor = ['default', 'schema', 'typeDefs', 'data'];
4// Pick exports
5/**
6 * @internal
7 */
8export function pickExportFromModule({ module, filepath }) {
9 ensureModule({ module, filepath });
10 return resolveModule(ensureExports({ module, filepath }));
11}
12/**
13 * @internal
14 */
15export function pickExportFromModuleSync({ module, filepath }) {
16 ensureModule({ module, filepath });
17 return resolveModuleSync(ensureExports({ module, filepath }));
18}
19// module
20async function resolveModule(identifiers) {
21 const exportValue = await pick(await identifiers, identifiersToLookFor);
22 return resolveExport(exportValue);
23}
24function resolveModuleSync(identifiers) {
25 const exportValue = pick(identifiers, identifiersToLookFor);
26 return resolveExport(exportValue);
27}
28// validate
29function ensureModule({ module, filepath }) {
30 if (!module) {
31 throw new Error(`Invalid export from export file ${filepath}: empty export!`);
32 }
33}
34function 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// Decide what to do with an exported value
42function 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}