-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathschema.ts
439 lines (400 loc) · 11.7 KB
/
schema.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
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/* eslint-disable no-unused-vars */
// We disable this rule as we want to always show all the arguments of each functions
// so that the API is easier to understand
import { GraphQLFieldConfig } from 'graphql'
import { InferAttributes, InferCreationAttributes, Model } from 'sequelize'
import {
GraphqlSchemaDeclarationType,
ModelDeclarationType,
MutationList,
} from '../types/types'
import {
generateApolloServer,
generateModelTypes,
injectAssociations,
resolver,
} from './../../src'
const {
GraphQLObjectType,
GraphQLString,
GraphQLList,
GraphQLBoolean,
GraphQLInt,
GraphQLError,
} = require('graphql')
const { PubSub } = require('graphql-subscriptions')
const { defaultListArgs } = require('graphql-sequelize')
const { EXPECTED_OPTIONS_KEY } = require('dataloader-sequelize')
const { WebSocketServer } = require('ws')
const { Op } = require('sequelize')
const models = require('./models')
// If you want to enable the dataloader everywhere, you can do this:
// From https://github.com/mickhansen/graphql-sequelize#options
resolver.contextToOptions = { [EXPECTED_OPTIONS_KEY]: EXPECTED_OPTIONS_KEY }
const graphqlSchemaDeclaration: GraphqlSchemaDeclarationType = {}
const types = generateModelTypes(models)
const pubSubInstance = new PubSub()
graphqlSchemaDeclaration.companyType = {
model: models.companyType,
actions: ['list', 'create'],
}
class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
declare id: number | null
declare name: string | null
}
class Department extends Model<
InferAttributes<Department>,
InferCreationAttributes<Department>
> {
declare name: string | null
}
class Company extends Model<
InferAttributes<Company>,
InferCreationAttributes<Company>
> {
declare name: string | null
}
graphqlSchemaDeclaration.user = {
model: models.user,
actions: ['list', 'create', 'delete', 'update', 'count'],
subscriptions: ['create', 'update'],
webhooks: ['create', 'update', 'delete'],
before: [
(args, context, info) => {
// Global before hook only have args, context and info.
// You can use many functions or just one.
// Use it if you need to do something before each enpoint
if (!context.bootDate) {
throw new GraphQLError('Boot date is missing!')
}
if (info.xxx) {
throw new GraphQLError('Xxx is provided when it should not!')
}
// Typical usage:
// * Protect an endpoint
// * Verify entity existance
// ex:
// if (!context.user.role !== 'admin') {
// throw new Error('You must be admin to use this endpoint!')
// }
// The function returns nothing
},
],
count: {
extraArg: {
departmentId: { type: GraphQLInt },
},
before: async (findOptions, source, args) => {
// example of an extra argument usage
if (args.departmentId) {
if (!findOptions.include) {
findOptions.include = []
}
// @ts-ignore
findOptions.include.push({
model: models.company,
required: true,
where: {
departmentId: args.departmentId,
},
})
}
// while keeping the list logic after
// If you want to re-use the list before,
// can can either call it or duplicate the code.
// Or do not specify the extra arg in the count,
// and declare it in the list, they will both user it.
if (typeof findOptions.where === 'undefined') {
findOptions.where = {}
}
findOptions.where = {
[Op.and]: [findOptions.where, { departmentId: [1] }],
}
return findOptions
},
},
list: {
removeUnusedAttributes: false,
enforceMaxLimit: 50,
before: (findOptions, args, context, info) => {
if (typeof findOptions.where === 'undefined') {
findOptions.where = {}
}
findOptions.where = { ...findOptions.where, id: 1 }
return findOptions
},
after: (result, args, context, info) => {
if (result && Object.hasOwnProperty.call(result, 'length')) {
for (const user of result as User[]) {
if (user.name === 'Test 5 c 2') {
user.name = `Mr ${user.name}`
}
}
}
return result
},
subscriptionFilter: (payload, args, context) => {
// Exemple of subscription check
if (context.user.role !== 'admin') {
return false
}
return true
},
},
// The followings hooks are just here to demo their signatures.
// They are not required and can be omited if you don't need them.
create: {
before: (source, args, context, info) => {
// You can restrict the creation if needed
return args.user
},
after: async (newEntity, source, args, context, info, setWebhookData) => {
// You can log what happened here
setWebhookData((defaultData: any) => {
return {
...defaultData,
gsg: 'This hook will be triggered ig gsg',
}
})
return newEntity
},
preventDuplicateOnAttributes: ['type'],
},
update: {
before: (source, args, context, info) => {
// You can restrict the creation if needed
return args.user
},
after: async (
updatedEntity,
entitySnapshot,
source,
args,
context,
info
) => {
// You can log what happened here
return updatedEntity
},
},
delete: {
extraArg: { log: { type: GraphQLBoolean } },
before: (where, source, args, context, info) => {
// You can restrict the creation if needed
return where
},
after: async (deletedEntity, source, args, context, info) => {
// You can log what happened here
if (args.log) {
const date = Date.now()
await models.log.create({
message: `The User id = ${args.id} was successfully deleted`,
createdAt: date,
updatedAt: date,
})
}
return deletedEntity
},
},
} as ModelDeclarationType<typeof models.user>
graphqlSchemaDeclaration.company = {
model: models.company,
actions: ['list', 'create'],
subscriptions: ['create', 'update'],
list: {
removeUnusedAttributes: false,
before: (findOptions, args, context, info) => {
if (typeof findOptions.where === 'undefined') {
findOptions.where = {}
}
// This is an example of rights enforcement
findOptions.where = {
[Op.and]: [findOptions.where, { id: [1, 3, 5, 7] }],
}
return findOptions
},
},
} as ModelDeclarationType<typeof models.company>
graphqlSchemaDeclaration.department = {
model: models.department,
actions: ['list', 'create'],
excludeFields: ['company', 'updatedAt'],
list: {
resolver: async (source, args, context, info) => {
// Making custom resolvers on the list query can be useful
// but keep in mind that it will be used at any level in the graph.
// Here, defining our own resolver without taking into account the args
// and the source would make that "departments" would never be returned
// when queried outside a simple query like {department{id}}
// Be sure to look at the source!
if (source && source.departmentId) {
// This call Will not be taken in account by the dataloader
const entity = await models.department.findByPk(source.departmentId)
return entity
}
if (source && source.dataValues && source.dataValues.id) {
// Example of dataloader used for a query
// This call will be taken in account by the dataloader
return source.getDepartments({
[EXPECTED_OPTIONS_KEY]: context[EXPECTED_OPTIONS_KEY],
})
}
// Do not do that in production!
// The dataloader will not be used for this query!
return models.department.findAll({
where: {
id: [1, 2, 3, 4, 5, 6, 7, 8],
},
})
},
},
} as ModelDeclarationType<typeof models.department>
graphqlSchemaDeclaration.location = {
model: models.location,
actions: ['list', 'count'],
list: {
enforceMaxLimit: 2,
},
count: {
resolver: async () => {
// You can specify you own count if needed
const result = await models.sequelize.query(
`SELECT count(*) as "count" FROM location`,
{ type: models.sequelize.QueryTypes.SELECT }
)
return result && result[0] ? result[0].count : 0
},
},
}
graphqlSchemaDeclaration.serverStatistics = {
type: new GraphQLObjectType({
name: 'serverStatistics',
description: 'Statistics about the server',
fields: {
serverBootDate: { type: GraphQLString },
},
}),
resolve: async (source, args, context, info) => {
return {
serverBootDate: context.bootDate,
}
},
} as GraphQLFieldConfig<any, any, any>
const OddUser = new GraphQLObjectType({
name: 'OddUser',
description: 'Like an user, but only with odd ids.',
fields: {
handleAdditionalFields: { type: GraphQLString },
},
})
graphqlSchemaDeclaration.log = {
model: models.log,
actions: ['list', 'create'],
}
// Testing the many to many relationships
graphqlSchemaDeclaration.tag = {
model: models.tag,
actions: ['list'],
}
graphqlSchemaDeclaration.oddUser = {
type: new GraphQLList(
injectAssociations(
OddUser,
graphqlSchemaDeclaration,
types.outputTypes,
models,
() => null,
'user'
)
),
args: {
...defaultListArgs(),
},
resolve: resolver(models.user, {
before: async (findOptions, args, context, info) => {
findOptions.where = {
[Op.and]: [
findOptions.where,
{ id: models.sequelize.literal('id % 2') },
],
}
return findOptions
},
}),
} as GraphQLFieldConfig<any, any, any>
// Sometimes you want to add an action that do not match an existing model
// ex: Trigger a process
const customMutations: MutationList = {}
customMutations.logThat = {
type: new GraphQLObjectType({
name: 'logThat',
fields: {
message: { type: GraphQLString },
},
}),
args: {
message: {
type: GraphQLString,
},
},
description: 'Refresh the status of the call for projects.',
resolve: async (source, args, context, info) => {
// Your mutation can do something here...
console.log(args.message)
return {
message: args.message,
}
},
}
graphqlSchemaDeclaration.companySetting = {
model: models.companySetting,
excludeFromRoot: true,
actions: ['list'],
}
graphqlSchemaDeclaration.userLocation = {
model: models.userLocation,
actions: ['list'],
list: {
before: async (findOptions) => {
return findOptions
},
},
} as ModelDeclarationType<typeof models.userLocation>
module.exports = (globalPreCallback: any, httpServer: any) => {
// Creating the WebSocket server
const wsServer = new WebSocketServer({
// This is the `httpServer` we created in a previous step.
server: httpServer,
// Pass a different path here if app.use
// serves expressMiddleware at a different path
path: '/graphql',
})
return {
server: generateApolloServer<{ user: any }>({
graphqlSchemaDeclaration,
customMutations,
types,
models,
globalPreCallback,
wsServer,
apolloServerOptions: {
// Required for the tests.
csrfPrevention: false,
playground: true,
},
callWebhook: (data: any) => {
return data
},
pubSubInstance,
useServerOptions: {
context: async (ctx, msg, args) => {
// Returning an object will add that information to
// contextValue, which all of our resolvers have access to.
const user = { id: 1, name: 'John', companyId: 1, role: 'admin' }
ctx.extra.user = user
return { ctx, msg, args }
},
},
}),
}
}