UNPKG

2.11 kBPlain TextView Raw
1import {
2 GraphQLBoolean,
3 GraphQLFloat,
4 GraphQLInt,
5 GraphQLID,
6 GraphQLList,
7 GraphQLNonNull,
8 GraphQLScalarType,
9 GraphQLString,
10 GraphQLType,
11} from 'graphql'
12
13import * as t from '@babel/types';
14
15import { CompilerOptions } from 'apollo-codegen-core/lib/compiler';
16
17const builtInScalarMap = {
18 [GraphQLString.name]: t.TSStringKeyword(),
19 [GraphQLInt.name]: t.TSNumberKeyword(),
20 [GraphQLFloat.name]: t.TSNumberKeyword(),
21 [GraphQLBoolean.name]: t.TSBooleanKeyword(),
22 [GraphQLID.name]: t.TSStringKeyword(),
23}
24
25export function createTypeFromGraphQLTypeFunction(
26 compilerOptions: CompilerOptions
27): (graphQLType: GraphQLType, typeName?: string) => t.TSType {
28 function nonNullableTypeFromGraphQLType(graphQLType: GraphQLType, typeName?: string): t.TSType {
29 if (graphQLType instanceof GraphQLList) {
30 const elementType = typeFromGraphQLType(graphQLType.ofType, typeName);
31 return t.TSArrayType(
32 t.isTSUnionType(elementType) ? t.TSParenthesizedType(elementType) : elementType
33 );
34 } else if (graphQLType instanceof GraphQLScalarType) {
35 const builtIn = builtInScalarMap[typeName || graphQLType.name]
36 if (builtIn != null) {
37 return builtIn;
38 } else if (compilerOptions.passthroughCustomScalars) {
39 return t.TSTypeReference(t.identifier((compilerOptions.customScalarsPrefix || '') + graphQLType.name));
40 } else {
41 return t.TSAnyKeyword();
42 }
43 } else if (graphQLType instanceof GraphQLNonNull) {
44 // This won't happen; but for TypeScript completeness:
45 return typeFromGraphQLType(graphQLType.ofType, typeName);
46 } else {
47 return t.TSTypeReference(t.identifier(typeName || graphQLType.name));
48 }
49 }
50
51 function typeFromGraphQLType(graphQLType: GraphQLType, typeName?: string): t.TSType {
52 if (graphQLType instanceof GraphQLNonNull) {
53 return nonNullableTypeFromGraphQLType(graphQLType.ofType, typeName);
54 } else {
55 const type = nonNullableTypeFromGraphQLType(graphQLType, typeName);
56 return t.TSUnionType([type, t.TSNullKeyword()]);
57 }
58 }
59
60 return typeFromGraphQLType;
61}