Also: - Update deps. - Lock `apollo-cache-inmemory` to v1.0.0 since newer versions are buggy. - New file naming approach for stored uploads. - More intuitive mixed ESM/CJS module imports in the API.
52 lines
1.3 KiB
JavaScript
52 lines
1.3 KiB
JavaScript
import { createWriteStream } from 'fs'
|
|
import mkdirp from 'mkdirp'
|
|
import shortid from 'shortid'
|
|
import lowdb from 'lowdb'
|
|
import FileSync from 'lowdb/adapters/FileSync'
|
|
import { GraphQLUpload } from 'apollo-upload-server'
|
|
|
|
const uploadDir = './uploads'
|
|
const db = lowdb(new FileSync('db.json'))
|
|
|
|
// Seed an empty DB
|
|
db.defaults({ uploads: [] }).write()
|
|
|
|
// Ensure upload directory exists
|
|
mkdirp.sync(uploadDir)
|
|
|
|
const storeUpload = async ({ stream, filename }) => {
|
|
const id = shortid.generate()
|
|
const path = `${uploadDir}/${id}-${filename}`
|
|
|
|
return new Promise((resolve, reject) => {
|
|
stream
|
|
.pipe(createWriteStream(path))
|
|
.on('finish', () => resolve({ id, path }))
|
|
.on('error', reject)
|
|
})
|
|
}
|
|
|
|
const recordFile = file =>
|
|
db
|
|
.get('uploads')
|
|
.push(file)
|
|
.last()
|
|
.write()
|
|
|
|
const processUpload = async upload => {
|
|
const { stream, filename, mimetype, encoding } = await upload
|
|
const { id, path } = await storeUpload({ stream, filename })
|
|
return recordFile({ id, filename, mimetype, encoding, path })
|
|
}
|
|
|
|
export default {
|
|
Upload: GraphQLUpload,
|
|
Query: {
|
|
uploads: () => db.get('uploads').value()
|
|
},
|
|
Mutation: {
|
|
singleUpload: (obj, { file }) => processUpload(file),
|
|
multipleUpload: (obj, { files }) => Promise.all(files.map(processUpload))
|
|
}
|
|
}
|