-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathcore.ts
480 lines (444 loc) · 18.4 KB
/
core.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable no-restricted-globals */
/* eslint-disable n/prefer-global/process */
import type {
AfterHookParams,
InjectedConfig,
Options,
PrismaAppSyncOptionsType,
ResolveParams,
Shield,
ShieldAuthorization,
} from './types'
import {
Prisma,
PrismaClient,
} from './types'
import {
BatchActionsList,
DebugTestingKey,
} from './consts'
import { CustomError, log, parseError } from './inspector'
import {
clarify,
getDepth,
getShieldAuthorization,
preventDOS,
runHooks,
} from './guard'
import { parseEvent } from './adapter'
import { isEmpty, omit } from './utils'
import { prismaQueryJoin } from './resolver'
import * as queries from './resolver'
/**
* ## Auto-injected at generation time
*/
// eslint-disable-next-line spaced-comment
const injectedConfig: InjectedConfig = {} //! inject:config
/**
* ## Prisma-AppSync Client ʲˢ
*
* Type-safe Prisma AppSync client for TypeScript & Node.js
* @example
* ```
* const prismaAppSync = new PrismaAppSync()
*
* // lambda handler (AppSync Direct Lambda Resolver)
* export const resolver = async (event: any, context: any) => {
* return await prismaAppSync.resolve({ event })
* }
* ```
*
*
* Read more in our [docs](https://prisma-appsync.vercel.app).
*/
export class PrismaAppSync {
public options: Options
public prismaClient: PrismaClient<Prisma.PrismaClientOptions, 'query' | 'info' | 'warn' | 'error'>
/**
* ### Client Constructor
*
* Instantiate Prisma-AppSync Client.
* @example
* ```
* const prismaAppSync = new PrismaAppSync()
* ```
*
* @param {PrismaAppSyncOptionsType} options
* @param {string} options.connectionString? - Prisma connection string (database connection URL).
* @param {boolean} options.sanitize? - Enable sanitize inputs (parse xss + encode html).
* @param {'INFO' | 'WARN' | 'ERROR'} options.logLevel? - Server logs level (visible in CloudWatch).
* @param {number|false} options.defaultPagination? - Default pagination for list Query (items per page).
* @param {number} options.maxDepth? - Maximum allowed GraphQL query depth.
* @param {number} options.maxReqPerUserMinute? - Maximum allowed requests per user, per minute.
*
* @default
* ```
* {
* connectionString: process.env.DATABASE_URL,
* sanitize: true,
* logLevel: 'INFO',
* defaultPagination: 50,
* maxDepth: 4,
* maxReqPerUserMinute: 200
* }
* ```
*
*
* Read more in our [docs](https://prisma-appsync.vercel.app).
*/
constructor(options?: PrismaAppSyncOptionsType) {
// Set ENV variable DATABASE_URL if connectionString option is set
if (typeof options?.connectionString !== 'undefined')
process.env.DATABASE_URL = options.connectionString
// Set client options using constructor options
this.options = {
modelsMapping: {},
fieldsMapping: {},
connectionString: String(process.env.DATABASE_URL),
sanitize:
typeof options?.sanitize !== 'undefined'
? options.sanitize
: true,
logLevel:
typeof options?.logLevel !== 'undefined'
? options.logLevel
: 'INFO',
defaultPagination:
typeof options?.defaultPagination !== 'undefined'
? options.defaultPagination
: 50,
maxDepth:
typeof options?.maxDepth !== 'undefined'
? options.maxDepth
: 4,
maxReqPerUserMinute:
typeof options?.maxReqPerUserMinute !== 'undefined'
? options.maxReqPerUserMinute
: 200,
}
this.options.modelsMapping = {}
// Read injected config
if (injectedConfig?.modelsMapping) {
this.options.modelsMapping = injectedConfig.modelsMapping
}
else if (process?.env?.PRISMA_APPSYNC_INJECTED_CONFIG) {
try {
this.options.modelsMapping = JSON.parse(
process.env.PRISMA_APPSYNC_INJECTED_CONFIG,
).modelsMapping
}
catch {}
}
if (injectedConfig?.fieldsMapping) {
this.options.fieldsMapping = injectedConfig.fieldsMapping
}
else if (process?.env?.PRISMA_APPSYNC_INJECTED_CONFIG) {
try {
this.options.fieldsMapping = JSON.parse(
process.env.PRISMA_APPSYNC_INJECTED_CONFIG,
).fieldsMapping
}
catch {}
}
// Make sure injected config isn't empty
if (Object.keys(this.options.modelsMapping).length === 0) {
throw new CustomError('Issue with auto-injected models mapping config.', {
type: 'INTERNAL_SERVER_ERROR',
})
}
// Set ENV variable for log level
process.env.PRISMA_APPSYNC_LOG_LEVEL = this.options.logLevel
// Debug logs
// eslint-disable-next-line unused-imports/no-unused-vars
const { fieldsMapping, ...newInstanceLogs } = this.options
log('New Prisma-AppSync instance created:', newInstanceLogs)
// Prisma client options
const prismaLogDef: Prisma.LogDefinition[] = [
{ emit: 'event', level: 'query' },
{ emit: 'event', level: 'error' },
{ emit: 'event', level: 'info' },
{ emit: 'event', level: 'warn' },
]
// Create new Prisma Client
if (process?.env?.PRISMA_APPSYNC_TESTING === 'true') {
if (!global.prisma)
global.prisma = new PrismaClient({ log: prismaLogDef })
this.prismaClient = global.prisma
}
else {
this.prismaClient = new PrismaClient({ log: prismaLogDef })
}
// Prisma logs
if (!(process?.env?.PRISMA_APPSYNC_TESTING === 'true')) {
this.prismaClient.$on('query', (e: any) => log('Prisma Client query:', e, 'INFO'))
this.prismaClient.$on('info', (e: any) => log('Prisma Client info:', e, 'INFO'))
this.prismaClient.$on('warn', (e: any) => log('Prisma Client warn:', e, 'WARN'))
this.prismaClient.$on('error', (e: any) => log('Prisma Client error:', e, 'ERROR'))
}
}
/**
* ### Resolver
*
* Resolve the API request, based on the AppSync `event` received by the Direct Lambda Resolver.
* @example
* ```
* await prismaAppSync.resolve({ event })
*
* // custom resolvers
* await prismaAppSync.resolve<'notify'|'listPosts'>(
* event,
* resolvers: {
* // extend CRUD API with a custom `notify` query
* notify: async ({ args }) => { return { message: args.message } },
*
* // disable one of the generated CRUD API query
* listPosts: false,
* }
* })
* ```
*
* @param {ResolveParams} resolveParams
* @param {any} resolveParams.event - AppSync event received by the Direct Lambda Resolver.
* @param {any} resolveParams.resolvers? - Custom resolvers (to extend the CRUD API).
* @param {function} resolveParams.shield? - Shield configuration (to protect your API).
* @param {function} resolveParams.hooks? - Hooks (to trigger functions based on events).
* @returns Promise<result>
*
*
* Read more in our [docs](https://prisma-appsync.vercel.app).
*/
public async resolve<CustomResolvers = void>(
resolveParams: ResolveParams<'//! inject:type:operations', Extract<CustomResolvers, string>>,
): Promise<any> {
let result: any = null
try {
log('Resolving API request w/ event (truncated):', {
arguments: resolveParams.event.arguments,
identity: resolveParams.event.identity,
info: omit(resolveParams.event.info, 'selectionSetGraphQL'),
})
// Adapter :: parse appsync event
let QueryParams = await parseEvent(
resolveParams.event,
this.options,
resolveParams.resolvers,
)
log('Parsed event:', QueryParams)
// Guard :: rate limiting
const callerUuid
= (QueryParams.identity as any)?.sourceIp?.[0]
|| (QueryParams.identity as any)?.sourceIp
|| (QueryParams.identity as any)?.sub
|| JSON.stringify(QueryParams.identity)
if (this.options.maxReqPerUserMinute && callerUuid) {
const { limitExceeded, count } = await preventDOS({
callerUuid,
maxReqPerMinute: this.options.maxReqPerUserMinute,
})
if (limitExceeded) {
throw new CustomError(
`Rate limit (maxReqPerUserMinute=${this.options.maxReqPerUserMinute}) exceeded for caller "${callerUuid}".`,
{
type: 'TOO_MANY_REQUESTS',
},
)
}
else {
log(`Rate limit check for caller "${callerUuid}" returned ${count}/${this.options.maxReqPerUserMinute} (last minute).`)
}
}
// Guard :: block queries with a depth > maxDepth
const depth = getDepth({
paths: QueryParams.paths,
context: QueryParams.context,
fieldsMapping: this.options.fieldsMapping,
})
if (depth > this.options.maxDepth) {
throw new CustomError(
`Query has depth of ${depth}, which exceeds max depth of ${this.options.maxDepth}.`,
{
type: 'FORBIDDEN',
},
)
}
else {
log(`Query has depth of ${depth} (max allowed is ${this.options.maxDepth}).`)
}
// Guard :: create shield from config
const shield: Shield = resolveParams?.shield
? await resolveParams.shield(QueryParams)
: {}
// Guard :: get shield authorization config
const shieldAuth: ShieldAuthorization = await getShieldAuthorization({
shield,
paths: QueryParams.paths,
context: QueryParams.context,
})
if (Object.keys(shield).length === 0)
log('Query shield authorization: No Shield setup detected.', null, 'WARN')
else
log('Query shield authorization:', shieldAuth)
// Guard :: if `canAccess` if equal to `false`, we reject the API call
if (!shieldAuth.canAccess) {
const reason = typeof shieldAuth.reason === 'string'
? shieldAuth.reason
: shieldAuth.reason({
action: QueryParams.context.action,
model: QueryParams.context.model?.singular || QueryParams.context.action,
})
throw new CustomError(reason, { type: 'FORBIDDEN' })
}
// Guard :: if `prismaFilter` is set, combine with current Prisma query
if (!isEmpty(shieldAuth.prismaFilter)) {
log('QueryParams before adding Shield filters:', QueryParams)
QueryParams.prismaArgs = prismaQueryJoin(
[QueryParams.prismaArgs, { where: shieldAuth.prismaFilter }],
[
'where',
'data',
'orderBy',
'skip',
'take',
'skipDuplicates',
'select',
],
)
log('QueryParams after adding Shield filters:', QueryParams)
}
// Guard: get and run all before hooks functions matching query
if (!isEmpty(resolveParams?.hooks)) {
QueryParams = await runHooks({
when: 'before',
hooks: resolveParams.hooks,
prismaClient: this.prismaClient,
QueryParams,
})
}
// Resolver :: resolve query for UNIT TESTS
if (process?.env?.PRISMA_APPSYNC_TESTING === 'true') {
log('Resolving query for UNIT TESTS.')
const isBatchAction = BatchActionsList.includes(
QueryParams?.context?.action,
)
const getTestResult = () => {
return {
...QueryParams.fields.reduce((a, v) => {
const value = !isEmpty(QueryParams?.prismaArgs?.data?.[v])
? QueryParams.prismaArgs.data[v]
: (Math.random() + 1).toString(36).substring(7)
return { ...a, [v]: String(value) }
}, {}),
[DebugTestingKey]: {
QueryParams,
},
}
}
if (isBatchAction)
result = [getTestResult(), getTestResult()]
else
result = getTestResult()
}
// Resolver :: query is disabled
else if (
resolveParams?.resolvers
&& typeof resolveParams.resolvers[QueryParams.operation] === 'boolean'
&& resolveParams.resolvers[QueryParams.operation] === false
) {
throw new CustomError(
`Query resolver for ${QueryParams.operation} is disabled.`,
{ type: 'FORBIDDEN' },
)
}
// Resolver :: resolve query with Custom Resolver
else if (
typeof resolveParams?.resolvers?.[QueryParams.operation] === 'function'
) {
log(`Resolving query for Custom Resolver "${QueryParams.operation}".`)
const customResolverFn = resolveParams.resolvers[
QueryParams.operation
] as Function
result = await customResolverFn({
...QueryParams,
prismaClient: this.prismaClient,
})
}
// Resolver :: resolve query with built-in CRUD
else if (!isEmpty(QueryParams?.context?.model)) {
log(`Resolving query for built-in CRUD operation "${QueryParams.operation}".`)
try {
result = await queries[`${QueryParams.context.action}Query`](
this.prismaClient,
QueryParams,
)
}
catch (err: any) {
if (err instanceof Prisma.PrismaClientKnownRequestError) {
throw new CustomError(
`Prisma Client known request error${err?.code ? ` (code ${err.code})` : ''}. https://www.prisma.io/docs/reference/api-reference/error-reference#prismaclientknownrequesterror`,
{ type: 'INTERNAL_SERVER_ERROR', cause: err },
)
}
else if (err instanceof Prisma.PrismaClientUnknownRequestError) {
throw new CustomError(
'Prisma Client unknown request error. https://www.prisma.io/docs/reference/api-reference/error-reference#prismaclientunknownrequesterror',
{ type: 'INTERNAL_SERVER_ERROR', cause: err },
)
}
else if (err instanceof Prisma.PrismaClientRustPanicError) {
throw new CustomError(
'Prisma Client Rust panic error. https://www.prisma.io/docs/reference/api-reference/error-reference#prismaclientrustpanicerror',
{ type: 'INTERNAL_SERVER_ERROR', cause: err },
)
}
else if (err instanceof Prisma.PrismaClientInitializationError) {
throw new CustomError(
`Prisma Client initialization error${err?.errorCode ? ` (errorCode ${err.errorCode})` : ''}. https://www.prisma.io/docs/reference/api-reference/error-reference#prismaclientinitializationerror`,
{ type: 'INTERNAL_SERVER_ERROR', cause: err },
)
}
else if (err instanceof Prisma.PrismaClientValidationError) {
throw new CustomError(
'Prisma Client validation error. https://www.prisma.io/docs/reference/api-reference/error-reference#prismaclientvalidationerror',
{ type: 'INTERNAL_SERVER_ERROR', cause: err },
)
}
else {
throw new CustomError(
err?.message?.split('\n')?.pop() || 'Unknown error during query.',
{ type: 'INTERNAL_SERVER_ERROR', cause: err },
)
}
}
}
// Resolver :: query resolver not found
else {
throw new CustomError(
`Query resolver for ${QueryParams.operation} could not be found.`,
{
type: 'INTERNAL_SERVER_ERROR',
},
)
}
// Guard: get and run all after hooks functions matching query
if (!isEmpty(resolveParams?.hooks)) {
const q: AfterHookParams = await runHooks({
when: 'after',
hooks: resolveParams.hooks,
prismaClient: this.prismaClient,
QueryParams,
result,
})
result = q.result
}
}
catch (error) {
// Return error
return Promise.reject(parseError(error as Error))
}
// Guard :: clarify result (decode html)
const resultClarified = this.options.sanitize ? await clarify(result) : result
log('Returning response to API request w/ result:', resultClarified)
return resultClarified
}
}