-
Notifications
You must be signed in to change notification settings - Fork 222
/
Copy pathschema.js
405 lines (350 loc) · 12.4 KB
/
schema.js
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
const immutable = require('immutable')
const tsCodegen = require('./typescript')
const typesCodegen = require('./types')
const { ThrowStatement } = require('assemblyscript')
const List = immutable.List
class IdField {
static BYTES = Symbol("Bytes")
static STRING = Symbol("String")
constructor(idField) {
const typeName = idField.getIn(['type', 'type', 'name', 'value'])
this.kind = typeName === "Bytes" ? IdField.BYTES : IdField.STRING
}
typeName() {
return this.kind === IdField.BYTES ? "Bytes" : "string"
}
gqlTypeName() {
return this.kind === IdField.BYTES ? "Bytes" : "String"
}
tsNamedType() {
return tsCodegen.namedType(this.typeName())
}
tsValueFrom() {
return this.kind === IdField.BYTES ? "Value.fromBytes(id)" : "Value.fromString(id)"
}
tsValueKind() {
return this.kind === IdField.BYTES ? "ValueKind.BYTES" : "ValueKind.STRING"
}
tsValueToString() {
return this.kind == IdField.BYTES ? "id.toBytes().toHexString()" : "id.toString()"
}
tsToString() {
return this.kind == IdField.BYTES ? "id.toHexString()" : "id"
}
static fromFields(fields) {
const idField = fields.find(field => field.getIn(['name', 'value']) === 'id')
return new IdField(idField)
}
static fromTypeDef(def) {
return IdField.fromFields(def.get("fields"))
}
}
module.exports = class SchemaCodeGenerator {
constructor(schema) {
this.schema = schema
}
generateModuleImports() {
return [
tsCodegen.moduleImports(
[
// Base classes
'TypedMap',
'Entity',
'Value',
'ValueKind',
// APIs
'store',
// Basic Scalar types
'Bytes',
'BigInt',
'BigDecimal',
],
'@graphprotocol/graph-ts',
),
]
}
generateDerivedLoader() {
// retrive all the derived fields
let fields = this.schema.ast.get("definitions")
.filter(def => this._isEntityTypeDefinition(def))
.map(def => def.get('fields')
).flatten(1);
// generate loaders for derived fields
return fields
.filter((field) => this._isDerivedField(field))
.map((derivedField) => this._generateDerivedLoaders(derivedField))
.flatten(1)
}
_generateDerivedLoaders(field) {
let typeName = this._concreteValueTypeFromGraphQl(field.get('type'))
let mappingName = this._getDerviedFieldMapping(field);
let klass = tsCodegen.klass(`${typeName}Loader`, { export: true, extends: 'Entity' })
klass.addMember(tsCodegen.klassMember("_entity", "string"))
klass.addMember(tsCodegen.klassMember("_mapping", "string"))
klass.addMember(tsCodegen.klassMember("_id", "string"))
klass.addMethod(tsCodegen.method('constructor', [tsCodegen.param('id', 'string')],
undefined, `
super()
this._entity = '${typeName}';
this._mapping = '${mappingName}';
this._id = id;
`))
klass.addMethod(tsCodegen.method("load", [], `${typeName} | null`, `
return changetype<${typeName} | null>(store.get_derived_entity('${typeName}', '${mappingName}', this._id))
`))
let arrayKlass = tsCodegen.klass(`Array${typeName}Loader`, { export: true, extends: 'Entity' })
arrayKlass.addMember(tsCodegen.klassMember("_entity", "string"))
arrayKlass.addMember(tsCodegen.klassMember("_mapping", "string"))
arrayKlass.addMember(tsCodegen.klassMember("_id", "string"))
arrayKlass.addMethod(tsCodegen.method('constructor',
[tsCodegen.param('id', 'string')],
undefined, `
super()
this._entity = '${typeName}';
this._mapping = '${mappingName}';
this._id = id;
`))
arrayKlass.addMethod(tsCodegen.method("load",
[],
`${typeName} | null`, `
return changetype<${typeName} | null>(store.get_derived_entity('${typeName}', '${mappingName}', this._id))
`))
return List([klass, arrayKlass])
}
_getDerviedFieldMapping(field) {
let derivedFrom = field
.get('directives')
.find(directive => directive.getIn(['name', 'value']) === 'derivedFrom')
return derivedFrom.get('arguments').get(0).getIn(['value', 'value'])
}
_isDerivedField(field) {
field.getIn(['name', 'value'])
return field.get('directives').find(directive => directive.getIn(['name', 'value']) === 'derivedFrom') !== undefined
}
generateTypes() {
return this.schema.ast
.get('definitions')
.filter(def => this._isEntityTypeDefinition(def))
.map(def => this._generateEntityType(def))
}
_isEntityTypeDefinition(def) {
return (
def.get('kind') === 'ObjectTypeDefinition' &&
def
.get('directives')
.find(directive => directive.getIn(['name', 'value']) === 'entity') !== undefined
)
}
_isInterfaceDefinition(def) {
return def.get('kind') === 'InterfaceTypeDefinition'
}
_generateEntityType(def) {
let name = def.getIn(['name', 'value'])
let klass = tsCodegen.klass(name, { export: true, extends: 'Entity' })
const fields = def.get('fields')
const idField = IdField.fromFields(fields)
// Generate and add a constructor
klass.addMethod(this._generateConstructor(name, fields))
// Generate and add save() and getById() methods
this._generateStoreMethods(name, idField).forEach(method => klass.addMethod(method))
// Generate and add entity field getters and setters
def
.get('fields')
.reduce(
(methods, field) => methods.concat(this._generateEntityFieldMethods(def, field)),
List(),
)
.forEach(method => klass.addMethod(method))
return klass
}
_generateConstructor(entityName, fields) {
const idField = IdField.fromFields(fields)
return tsCodegen.method(
'constructor',
[tsCodegen.param('id', idField.tsNamedType())],
undefined,
`
super()
this.set('id', ${idField.tsValueFrom()})
`,
)
}
_generateStoreMethods(entityName, idField) {
return List.of(
tsCodegen.method(
'save',
[],
tsCodegen.namedType('void'),
`
let id = this.get('id')
assert(id != null,
'Cannot save ${entityName} entity without an ID')
if (id) {
assert(id.kind == ${idField.tsValueKind()},
\`Entities of type ${entityName} must have an ID of type ${idField.gqlTypeName()} but the id '\${id.displayData()}' is of type \${id.displayKind()}\`)
store.set('${entityName}', ${idField.tsValueToString()}, this)
}`,
),
tsCodegen.staticMethod(
'load',
[tsCodegen.param('id', tsCodegen.namedType(idField.typeName()))],
tsCodegen.nullableType(tsCodegen.namedType(entityName)),
`
return changetype<${entityName} | null>(store.get('${entityName}', ${idField.tsToString()}))
`,
),
)
}
_generateEntityFieldMethods(entityDef, fieldDef) {
return List([
this._generateEntityFieldGetter(entityDef, fieldDef),
this._generateEntityFieldSetter(entityDef, fieldDef),
])
}
_generateEntityFieldGetter(entityDef, fieldDef) {
if (this._isDerivedField(fieldDef)) {
return this._generateDerviedFieldGetter(fieldDef)
}
let name = fieldDef.getIn(['name', 'value'])
let gqlType = fieldDef.get('type')
let fieldValueType = this._valueTypeFromGraphQl(gqlType)
let returnType = this._typeFromGraphQl(gqlType)
let isNullable = returnType instanceof tsCodegen.NullableType
let getNonNullable = `return ${typesCodegen.valueToAsc('value!', fieldValueType)}`
let getNullable = `if (!value || value.kind == ValueKind.NULL) {
return null
} else {
return ${typesCodegen.valueToAsc('value', fieldValueType)}
}`
return tsCodegen.method(
`get ${name}`,
[],
returnType,
`
let value = this.get('${name}')
${isNullable ? getNullable : getNonNullable}
`,
)
}
_generateDerviedFieldGetter(fieldDef) {
let name = fieldDef.getIn(['name', 'value'])
let gqlType = fieldDef.get('type')
let returnType = this._returnTypeForDervied(gqlType)
return tsCodegen.method(
`get ${name}`,
[],
returnType,
`
return new ${returnType}(this.get('id')!.toString())
`,
)
}
_generateEntityFieldSetter(entityDef, fieldDef) {
let name = fieldDef.getIn(['name', 'value'])
let gqlType = fieldDef.get('type')
let fieldValueType = this._valueTypeFromGraphQl(gqlType)
let paramType = this._typeFromGraphQl(gqlType)
let isNullable = paramType instanceof tsCodegen.NullableType
let paramTypeString = isNullable ? paramType.inner.toString() : paramType.toString()
let isArray = paramType instanceof tsCodegen.ArrayType
if (
isArray &&
paramType.inner instanceof tsCodegen.NullableType
) {
let baseType = this._baseType(gqlType)
throw new Error(`
GraphQL schema can't have List's with Nullable members.
Error in '${name}' field of type '[${baseType}]'.
Suggestion: add an '!' to the member type of the List, change from '[${baseType}]' to '[${baseType}!]'`
)
}
let setNonNullable = `
this.set('${name}', ${typesCodegen.valueFromAsc(`value`, fieldValueType)})
`
let setNullable = `
if (!value) {
this.unset('${name}')
} else {
this.set('${name}', ${typesCodegen.valueFromAsc(
`<${paramTypeString}>value`,
fieldValueType,
)})
}
`
return tsCodegen.method(
`set ${name}`,
[tsCodegen.param('value', paramType)],
undefined,
isNullable ? setNullable : setNonNullable,
)
}
_resolveFieldType(gqlType) {
let typeName = gqlType.getIn(['name', 'value'])
// If this is a reference to another type, the field has the type of
// the referred type's id field
const typeDef = this.schema.ast.get("definitions").
find(def => (this._isEntityTypeDefinition(def) || this._isInterfaceDefinition(def)) && def.getIn(["name", "value"]) === typeName)
if (typeDef) {
return IdField.fromTypeDef(typeDef).typeName()
} else {
return typeName
}
}
/** Return the type that values for this field must have. For scalar
* types, that's the type from the subgraph schema. For references to
* other entity types, this is the same as the type of the id of the
* referred type, i.e., `string` or `Bytes`*/
_valueTypeFromGraphQl(gqlType) {
if (gqlType.get('kind') === 'NonNullType') {
return this._valueTypeFromGraphQl(gqlType.get('type'), false)
} else if (gqlType.get('kind') === 'ListType') {
return '[' + this._valueTypeFromGraphQl(gqlType.get('type')) + ']'
} else {
return this._resolveFieldType(gqlType)
}
}
_concreteValueTypeFromGraphQl(gqlType) {
if (gqlType.get('kind') === 'NonNullType') {
return this._concreteValueTypeFromGraphQl(gqlType.get('type'))
} else if (gqlType.get('kind') === 'ListType') {
return this._concreteValueTypeFromGraphQl(gqlType.get('type'))
} else {
return gqlType.getIn(['name', 'value'])
}
}
_returnTypeForDervied(gqlType) {
if (gqlType.get('kind') === 'NonNullType') {
return this._returnTypeForDervied(gqlType.get('type'))
} else if (gqlType.get('kind') === 'ListType') {
return 'Array' + this._returnTypeForDervied(gqlType.get('type'))
} else {
return gqlType.getIn(['name', 'value']) + 'Loader'
}
}
/** Determine the base type of `gqlType` by removing any non-null
* constraints and using the type of elements of lists */
_baseType(gqlType) {
if (gqlType.get('kind') === 'NonNullType') {
return this._baseType(gqlType.get('type'))
} else if (gqlType.get('kind') === 'ListType') {
return this._baseType(gqlType.get('type'))
} else {
return gqlType.getIn(['name', 'value'])
}
}
_typeFromGraphQl(gqlType, nullable = true) {
if (gqlType.get('kind') === 'NonNullType') {
return this._typeFromGraphQl(gqlType.get('type'), false)
} else if (gqlType.get('kind') === 'ListType') {
let type = tsCodegen.arrayType(this._typeFromGraphQl(gqlType.get('type')))
return nullable ? tsCodegen.nullableType(type) : type
} else {
// NamedType
let type = tsCodegen.namedType(
typesCodegen.ascTypeForValue(this._resolveFieldType(gqlType)),
)
// In AssemblyScript, primitives cannot be nullable.
return nullable && !type.isPrimitive() ? tsCodegen.nullableType(type) : type
}
}
}