-
Notifications
You must be signed in to change notification settings - Fork 60
/
remoteGraphQLSchema.ts
214 lines (185 loc) · 5.99 KB
/
remoteGraphQLSchema.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import {get, camelCase, groupBy} from 'lodash'
import {
FieldDefinitionNode,
GraphQLString,
ListTypeNode,
NamedTypeNode,
NonNullTypeNode,
ObjectTypeDefinitionNode,
parse,
ScalarTypeDefinitionNode,
specifiedScalarTypes,
TypeNode,
UnionTypeDefinitionNode,
valueFromAST,
} from 'gatsby/graphql'
import {SanityClient} from '@sanity/client'
import {getTypeName} from './normalize'
import {ErrorWithCode} from './errors'
import {PluginConfig} from './validateConfig'
export type FieldDef = {
type: NamedTypeNode | ListTypeNode | NonNullTypeNode
namedType: NamedTypeNode
isList: boolean
aliasFor: string | null
isReference: boolean
}
export type ObjectTypeDef = {
name: string
kind: 'Object'
isDocument: boolean
fields: {[key: string]: FieldDef}
}
export type UnionTypeDef = {
name: string
types: string[]
}
export type TypeMap = {
scalars: string[]
objects: {[key: string]: ObjectTypeDef}
unions: {[key: string]: UnionTypeDef}
}
export const defaultTypeMap: TypeMap = {
scalars: [],
objects: {},
unions: {},
}
export async function getRemoteGraphQLSchema(client: SanityClient, config: PluginConfig) {
const {graphqlTag} = config
const {dataset} = client.config()
try {
const api = await client.request({
url: `/apis/graphql/${dataset}/${graphqlTag}?tag=sanity.gatsby.get-schema`,
headers: {Accept: 'application/graphql'},
})
return api
} catch (err: any) {
const statusCode = get(err, 'response.statusCode')
const errorCode = get(err, 'response.body.errorCode')
const message =
get(err, 'response.body.message') || get(err, 'response.statusMessage') || err.message
const is404 = statusCode === 404 || /schema not found/i.test(message)
const error = new ErrorWithCode(
is404
? `GraphQL API not deployed - see https://github.com/sanity-io/gatsby-source-sanity#graphql-api for more info\n\n`
: `${message}`,
errorCode || statusCode,
)
throw error
}
}
export function getTypeMapFromGraphQLSchema(sdl: string): TypeMap {
const typeMap: TypeMap = {objects: {}, scalars: [], unions: {}}
const remoteSchema = parse(sdl)
const groups = {
ObjectTypeDefinition: [],
ScalarTypeDefinition: [],
UnionTypeDefinition: [],
...groupBy(remoteSchema.definitions, 'kind'),
}
typeMap.scalars = specifiedScalarTypes
.map((scalar) => scalar.name)
.concat(
groups.ScalarTypeDefinition.map((typeDef: ScalarTypeDefinitionNode) => typeDef.name.value),
)
const objects: {[key: string]: ObjectTypeDef} = {}
typeMap.objects = groups.ObjectTypeDefinition.reduce((acc, typeDef: ObjectTypeDefinitionNode) => {
if (typeDef.name.value === 'RootQuery') {
return acc
}
const name = getTypeName(typeDef.name.value)
acc[name] = {
name,
kind: 'Object',
isDocument: Boolean(
(typeDef.interfaces || []).find((iface) => iface.name.value === 'Document'),
),
fields: (typeDef.fields || []).reduce((fields, fieldDef) => {
if (isAlias(fieldDef)) {
const aliasFor = getAliasDirective(fieldDef) || ''
fields[aliasFor] = {
type: fieldDef.type,
namedType: {kind: 'NamedType', name: {kind: 'Name', value: 'JSON'}},
isList: false,
aliasFor: null,
isReference: false,
}
const aliasName = '_' + camelCase(`raw ${aliasFor}`)
fields[aliasName] = {
type: {kind: 'NamedType', name: {kind: 'Name', value: 'JSON'}},
namedType: {kind: 'NamedType', name: {kind: 'Name', value: 'JSON'}},
aliasFor,
isList: false,
isReference: false,
}
return fields
}
const namedType = unwrapType(fieldDef.type)
fields[fieldDef.name.value] = {
type: fieldDef.type,
namedType,
isList: isListType(fieldDef.type),
aliasFor: null,
isReference: Boolean(getReferenceDirective(fieldDef)),
}
// Add raw alias if not scalar
if (!typeMap.scalars.includes(namedType.name.value)) {
const aliasName = '_' + camelCase(`raw ${fieldDef.name.value}`)
fields[aliasName] = {
type: {kind: 'NamedType', name: {kind: 'Name', value: 'JSON'}},
namedType: {kind: 'NamedType', name: {kind: 'Name', value: 'JSON'}},
aliasFor: fieldDef.name.value,
isList: false,
isReference: false,
}
}
return fields
}, {} as {[key: string]: FieldDef}),
}
return acc
}, objects)
const unions: {[key: string]: UnionTypeDef} = {}
typeMap.unions = groups.UnionTypeDefinition.reduce((acc, typeDef: UnionTypeDefinitionNode) => {
const name = getTypeName(typeDef.name.value)
acc[name] = {
name,
types: (typeDef.types || []).map((type) => getTypeName(type.name.value)),
}
return acc
}, unions)
return typeMap
}
function isAlias(field: FieldDefinitionNode): boolean {
return getAliasDirective(field) !== null
}
function unwrapType(typeNode: TypeNode): NamedTypeNode {
if (['NonNullType', 'ListType'].includes(typeNode.kind)) {
const wrappedType = typeNode as NonNullTypeNode
return unwrapType(wrappedType.type)
}
return typeNode as NamedTypeNode
}
function isListType(typeNode: TypeNode): boolean {
if (typeNode.kind === 'ListType') {
return true
}
if (typeNode.kind === 'NonNullType') {
const node = typeNode as NonNullTypeNode
return isListType(node.type)
}
return false
}
function getAliasDirective(field: FieldDefinitionNode): string | null {
const alias = (field.directives || []).find((dir) => dir.name.value === 'jsonAlias')
if (!alias) {
return null
}
const forArg = (alias.arguments || []).find((arg) => arg.name.value === 'for')
if (!forArg) {
return null
}
return valueFromAST(forArg.value, GraphQLString, {})
}
function getReferenceDirective(field: FieldDefinitionNode) {
return (field.directives || []).find((dir) => dir.name.value === 'reference')
}