82 lines
2.1 KiB
JavaScript
82 lines
2.1 KiB
JavaScript
|
import path from 'path'
|
||
|
import formidable from './formidable/index.js'
|
||
|
import fs from 'fs/promises'
|
||
|
import { HttpError } from 'flaska'
|
||
|
|
||
|
export default class IngestRoutes {
|
||
|
constructor(opts = {}) {
|
||
|
Object.assign(this, {
|
||
|
})
|
||
|
}
|
||
|
|
||
|
uploadPart(org, ctx) {
|
||
|
let form = formidable.IncomingForm()
|
||
|
form.uploadDir = org.uploadDir
|
||
|
form.maxFileSize = org.maxFileSize || 8 * 1024 * 1024
|
||
|
form.maxFieldsSize = org.maxFieldsSize || 10 * 1024
|
||
|
form.maxFields = org.maxFields || 50
|
||
|
|
||
|
let filename = ctx.params.path.split('/').slice(-1)[0]
|
||
|
let target = path.join(org.uploadDir, filename)
|
||
|
|
||
|
return new Promise(function(res, rej) {
|
||
|
form.parse(ctx.req, function(err, fields, files) {
|
||
|
if (err) return rej(new HttpError(400, err.message))
|
||
|
|
||
|
ctx.req.body = fields
|
||
|
ctx.req.files = files
|
||
|
ctx.req.file = null
|
||
|
|
||
|
if (!ctx.req.files) {
|
||
|
return res()
|
||
|
}
|
||
|
|
||
|
let keys = Object.keys(files).filter(key => Boolean(ctx.req.files[key]))
|
||
|
|
||
|
Promise.all(
|
||
|
keys.map(key => {
|
||
|
return fs.rm(target, { force: true })
|
||
|
.then(() => {
|
||
|
return fs.rename(ctx.req.files[key].path, target)
|
||
|
})
|
||
|
.then(function() {
|
||
|
ctx.req.files[key].path = target
|
||
|
ctx.req.files[key].filename = filename
|
||
|
})
|
||
|
})
|
||
|
)
|
||
|
.then(() => {
|
||
|
if (keys.length === 1 && keys[0] === 'file') {
|
||
|
ctx.req.file = ctx.req.files.file
|
||
|
}
|
||
|
res()
|
||
|
}, rej)
|
||
|
})
|
||
|
})
|
||
|
}
|
||
|
|
||
|
register(server) {
|
||
|
server.flaska.put('/ingest/::path', [
|
||
|
this.uploadPart.bind(this, {
|
||
|
maxFileSize: 100 * 1024 * 1024,
|
||
|
uploadDir: './upload',
|
||
|
}),
|
||
|
], this.ingest.bind(this))
|
||
|
server.flaska.post('/ingest/::path', [
|
||
|
this.uploadPart.bind(this, {
|
||
|
maxFileSize: 100 * 1024 * 1024,
|
||
|
uploadDir: './upload',
|
||
|
}),
|
||
|
], this.ingest.bind(this))
|
||
|
}
|
||
|
|
||
|
/** POST: /api/ingest */
|
||
|
async ingest(ctx) {
|
||
|
ctx.log.info(`Got part ${ctx.req.file.filename} size ${ctx.req.file.size}`)
|
||
|
|
||
|
ctx.body = {
|
||
|
success: true,
|
||
|
}
|
||
|
}
|
||
|
}
|