-
Notifications
You must be signed in to change notification settings - Fork 44
/
Prisma.ts
93 lines (77 loc) · 2.17 KB
/
Prisma.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
import { Binding } from 'graphql-binding'
import { Exists, PrismaOptions } from './types'
import { sign } from 'jsonwebtoken'
import { makePrismaLink } from './link'
import { buildExistsInfo } from './info'
import { SharedLink } from './SharedLink'
import { getTypesAndWhere } from './utils'
import { getCachedTypeDefs, getCachedRemoteSchema } from './cache'
const sharedLink = new SharedLink()
export class Prisma extends Binding {
exists: Exists
constructor({
typeDefs,
endpoint,
secret,
fragmentReplacements,
debug,
disableCache,
}: PrismaOptions) {
if (!typeDefs) {
throw new Error('No `typeDefs` provided when calling `new Prisma()`')
}
if (typeDefs.endsWith('.graphql')) {
typeDefs = getCachedTypeDefs(typeDefs, disableCache)
}
if (endpoint === undefined) {
throw new Error(
`No Prisma endpoint found. Please provide the \`endpoint\` constructor option.`,
)
}
if (!endpoint!.startsWith('http')) {
throw new Error(`Invalid Prisma endpoint provided: ${endpoint}`)
}
fragmentReplacements = fragmentReplacements || []
debug = debug || false
const token = secret ? sign({}, secret!) : undefined
const link = makePrismaLink({ endpoint: endpoint!, token, debug })
const remoteSchema = getCachedRemoteSchema(
endpoint,
typeDefs,
sharedLink,
disableCache,
)
const before = () => {
sharedLink.setInnerLink(link)
}
super({
schema: remoteSchema,
fragmentReplacements,
before,
disableCache,
})
this.exists = this.buildExists()
}
private buildExists(): Exists {
const queryType = this.schema.getQueryType()
if (!queryType) {
return {}
}
if (queryType) {
const types = getTypesAndWhere(queryType)
return types.reduce((acc, { type, pluralFieldName }) => {
return {
...acc,
[type]: args =>
this.delegate(
'query',
pluralFieldName,
{ where: args },
buildExistsInfo(pluralFieldName, this.schema),
).then(res => res.length > 0),
}
}, {})
}
return {}
}
}