/
index.ts
138 lines (121 loc) · 2.81 KB
/
index.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
import Fastify, { FastifyReply, FastifyRequest } from 'fastify'
import { buildSchema } from 'graphql'
import mercurius, { IResolvers, MercuriusLoaders } from 'mercurius'
import {
codegenMercurius,
CodegenMercuriusOptions,
loadSchemaFiles,
} from 'mercurius-codegen'
export const app = Fastify({
logger: true,
})
const codegenMercuriusOptions: CodegenMercuriusOptions = {
targetPath: './src/graphql/generated.ts',
operationsGlob: './src/graphql/operations/*.gql',
watchOptions: {
enabled: process.env.NODE_ENV === 'development',
},
}
const { schema } = loadSchemaFiles('src/graphql/schema/**/*.gql', {
watchOptions: {
enabled: process.env.NODE_ENV === 'development',
onChange(schema) {
app.graphql.replaceSchema(buildSchema(schema.join('\n')))
app.graphql.defineResolvers(resolvers)
codegenMercurius(app, codegenMercuriusOptions).catch(console.error)
},
},
})
const buildContext = async (req: FastifyRequest, _reply: FastifyReply) => {
return {
authorization: req.headers.authorization,
}
}
type PromiseType<T> = T extends PromiseLike<infer U> ? U : T
declare module 'mercurius' {
interface MercuriusContext
extends PromiseType<ReturnType<typeof buildContext>> {}
}
const dogs = [
{ name: 'Max' },
{ name: 'Charlie' },
{ name: 'Buddy' },
{ name: 'Max' },
]
const owners: Record<string, { name: string }> = {
Max: {
name: 'Jennifer',
},
Charlie: {
name: 'Sarah',
},
Buddy: {
name: 'Tracy',
},
}
const NOTIFICATION = 'notification'
const resolvers: IResolvers = {
Query: {
Hello(root, args, ctx, info) {
// root ~ {}
root
// args ~ {}
args
// ctx.authorization ~ string | undefined
ctx.authorization
// info ~ GraphQLResolveInfo
info
return 'world'
},
dogs() {
return dogs
},
},
Mutation: {
add(root, { x, y }, ctx, info) {
// root ~ {}
root
// x ~ string
x
// x ~ string
y
// ctx.authorization ~ string | undefined
ctx.authorization
// info ~ GraphQLResolveInfo
info
return x + y
},
createNotification(_root, { message }, { pubsub }) {
pubsub.publish({
topic: NOTIFICATION,
payload: {
newNotification: message,
},
})
return true
},
},
Subscription: {
newNotification: {
subscribe: (_root, _args, { pubsub }) => {
return pubsub.subscribe(NOTIFICATION)
},
},
},
}
const loaders: MercuriusLoaders = {
Dog: {
async owner(queries, _ctx) {
return queries.map(({ obj }) => owners[obj.name])
},
},
}
app.register(mercurius, {
schema,
resolvers,
loaders,
context: buildContext,
subscription: true,
})
codegenMercurius(app, codegenMercuriusOptions).catch(console.error)
// app.listen(8000)