-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresolvers.mjs
executable file
·70 lines (61 loc) · 1.76 KB
/
resolvers.mjs
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
import fs from 'fs'
import apolloServerKoa from 'apollo-server-koa'
import lowdb from 'lowdb'
import FileSync from 'lowdb/adapters/FileSync'
import mkdirp from 'mkdirp'
import promisesAll from 'promises-all'
import shortid from 'shortid'
const UPLOAD_DIR = './uploads'
const db = lowdb(new FileSync('db.json'))
// Seed an empty DB.
db.defaults({ uploads: [] }).write()
// Ensure upload directory exists.
mkdirp.sync(UPLOAD_DIR)
const storeFS = ({ stream, filename }) => {
const id = shortid.generate()
const path = `${UPLOAD_DIR}/${id}-${filename}`
return new Promise((resolve, reject) =>
stream
.on('error', error => {
if (stream.truncated)
// Delete the truncated file.
fs.unlinkSync(path)
reject(error)
})
.pipe(fs.createWriteStream(path))
.on('error', error => reject(error))
.on('finish', () => resolve({ id, path }))
)
}
const storeDB = file =>
db
.get('uploads')
.push(file)
.last()
.write()
const processUpload = async upload => {
const { createReadStream, filename, mimetype } = await upload
const stream = createReadStream()
const { id, path } = await storeFS({ stream, filename })
return storeDB({ id, filename, mimetype, path })
}
export default {
Upload: apolloServerKoa.GraphQLUpload,
Query: {
uploads: () => db.get('uploads').value()
},
Mutation: {
singleUpload: (obj, { file }) => processUpload(file),
async multipleUpload(obj, { files }) {
const { resolve, reject } = await promisesAll.all(
files.map(processUpload)
)
if (reject.length)
reject.forEach(({ name, message }) =>
// eslint-disable-next-line no-console
console.error(`${name}: ${message}`)
)
return resolve
}
}
}