-
Notifications
You must be signed in to change notification settings - Fork 558
/
file-uploads.spec.ts
116 lines (103 loc) 路 2.95 KB
/
file-uploads.spec.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
import * as crypto from 'node:crypto'
import * as fs from 'node:fs'
import { createServer } from 'node:http'
import { AddressInfo } from 'node:net'
import * as os from 'node:os'
import * as path from 'node:path'
import { fetch, File, FormData } from '@whatwg-node/fetch'
import { createSchema, createYoga } from '../src'
function md5File(path: string) {
return new Promise((resolve, reject) => {
const output = crypto.createHash('md5')
const input = fs.createReadStream(path)
input.on('error', (err) => {
reject(err)
})
output.once('readable', () => {
resolve(output.read().toString('hex'))
})
input.pipe(output)
})
}
describe('file uploads', () => {
it('uploading and streaming a binary file succeeds', async () => {
const sourceFilePath = path.join(
__dirname,
'..',
'..',
'..',
'website',
'public',
'logo.png',
)
const sourceMd5 = await md5File(sourceFilePath)
const id = crypto.randomBytes(20).toString('hex')
const targetFilePath = path.join(os.tmpdir(), `${id}.png`)
const yoga = createYoga({
schema: createSchema({
resolvers: {
Mutation: {
uploadFile: async (root, args) => {
await fs.promises.writeFile(
targetFilePath,
Buffer.from(await args.file.arrayBuffer()),
)
return true
},
},
},
typeDefs: /* GraphQL */ `
scalar File
type Query {
_: Boolean
}
type Mutation {
uploadFile(file: File!): Boolean
}
`,
}),
logging: false,
})
const server = createServer(yoga)
try {
await new Promise<void>((resolve) => server.listen(0, resolve))
const port = (server.address() as AddressInfo).port
const formData = new FormData()
formData.set(
'operations',
JSON.stringify({
query: /* GraphQL */ `
mutation uploadFile($file: File!) {
uploadFile(file: $file)
}
`,
}),
)
formData.set('map', JSON.stringify({ 0: ['variables.file'] }))
formData.set(
'0',
new File(
[await fs.promises.readFile(sourceFilePath)],
path.basename(sourceFilePath),
{ type: 'image/png' },
),
)
const response = await fetch(`http://localhost:${port}/graphql`, {
method: 'POST',
body: formData,
})
const body = await response.json()
expect(body.errors).toBeUndefined()
expect(body.data).toEqual({
uploadFile: true,
})
await fs.promises.stat(targetFilePath)
const targetMd5 = await md5File(targetFilePath)
expect(targetMd5).toEqual(sourceMd5)
fs.promises.unlink(targetFilePath)
expect(targetMd5).toBe(sourceMd5)
} finally {
await new Promise((resolve) => server.close(resolve))
}
})
})