UNPKG

3.43 kBJavaScriptView Raw
1import { isEnumType } from 'graphql';
2import { parseMapper } from './mappers.js';
3function escapeString(str) {
4 return str.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/'/g, "\\'");
5}
6export function parseEnumValues({ schema, mapOrStr = {}, ignoreEnumValuesFromSchema, }) {
7 const allTypes = schema.getTypeMap();
8 const allEnums = Object.keys(allTypes).filter(t => isEnumType(allTypes[t]));
9 if (typeof mapOrStr === 'object') {
10 if (!ignoreEnumValuesFromSchema) {
11 for (const enumTypeName of allEnums) {
12 const enumType = schema.getType(enumTypeName);
13 for (const { name, value } of enumType.getValues()) {
14 if (value !== name) {
15 mapOrStr[enumTypeName] = mapOrStr[enumTypeName] || {};
16 if (typeof mapOrStr[enumTypeName] !== 'string' && !mapOrStr[enumTypeName][name]) {
17 mapOrStr[enumTypeName][name] = typeof value === 'string' ? escapeString(value) : value;
18 }
19 }
20 }
21 }
22 }
23 const invalidMappings = Object.keys(mapOrStr).filter(gqlName => !allEnums.includes(gqlName));
24 if (invalidMappings.length > 0) {
25 throw new Error(`Invalid 'enumValues' mapping! \n
26 The following types does not exist in your GraphQL schema: ${invalidMappings.join(', ')}`);
27 }
28 return Object.keys(mapOrStr).reduce((prev, gqlIdentifier) => {
29 const pointer = mapOrStr[gqlIdentifier];
30 if (typeof pointer === 'string') {
31 const mapper = parseMapper(pointer, gqlIdentifier);
32 return {
33 ...prev,
34 [gqlIdentifier]: {
35 isDefault: mapper.isExternal && mapper.default,
36 typeIdentifier: gqlIdentifier,
37 sourceFile: mapper.isExternal ? mapper.source : null,
38 sourceIdentifier: mapper.type,
39 importIdentifier: mapper.isExternal ? mapper.import : null,
40 mappedValues: null,
41 },
42 };
43 }
44 if (typeof pointer === 'object') {
45 return {
46 ...prev,
47 [gqlIdentifier]: {
48 isDefault: false,
49 typeIdentifier: gqlIdentifier,
50 sourceFile: null,
51 sourceIdentifier: null,
52 importIdentifier: null,
53 mappedValues: pointer,
54 },
55 };
56 }
57 throw new Error(`Invalid "enumValues" configuration \n
58 Enum "${gqlIdentifier}": expected string or object (with enum values mapping)`);
59 }, {});
60 }
61 if (typeof mapOrStr === 'string') {
62 return allEnums
63 .filter(enumName => !enumName.startsWith('__'))
64 .reduce((prev, enumName) => {
65 return {
66 ...prev,
67 [enumName]: {
68 isDefault: false,
69 typeIdentifier: enumName,
70 sourceFile: mapOrStr,
71 sourceIdentifier: enumName,
72 importIdentifier: enumName,
73 mappedValues: null,
74 },
75 };
76 }, {});
77 }
78 return {};
79}