forked from bmullan91/fastify-gql-upload
-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.ts
50 lines (39 loc) · 1.12 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
import * as util from 'util'
import stream from 'stream'
import fp from 'fastify-plugin'
import { processRequest, UploadOptions } from 'graphql-upload-minimal'
const finishedStream = util.promisify(stream.finished)
import type { FastifyPluginCallback } from 'fastify'
declare module 'fastify' {
interface FastifyRequest {
mercuriusUploadMultipart?: true
}
}
const mercuriusGQLUpload: FastifyPluginCallback<UploadOptions> = (
fastify,
options,
done,
) => {
fastify.addContentTypeParser('multipart/form-data', (req, _payload, done) => {
req.mercuriusUploadMultipart = true
done(null)
})
fastify.addHook('preValidation', async function (request, reply) {
if (!request.mercuriusUploadMultipart) {
return
}
request.body = await processRequest(request.raw, reply.raw, options)
})
fastify.addHook('onSend', async function (request) {
if (!request.mercuriusUploadMultipart) {
return
}
await finishedStream(request.raw)
})
done()
}
export const mercuriusUpload = fp(mercuriusGQLUpload, {
fastify: '5.x',
name: 'mercurius-upload',
})
export default mercuriusUpload