| 3 | const Busboy = require('@fastify/busboy') |
| 4 | |
| 5 | function parseFormDataString ( |
| 6 | body, |
| 7 | contentType |
| 8 | ) { |
| 9 | const cache = { |
| 10 | fileMap: new Map(), |
| 11 | fields: [] |
| 12 | } |
| 13 | |
| 14 | const bb = new Busboy({ |
| 15 | headers: { |
| 16 | 'content-type': contentType |
| 17 | } |
| 18 | }) |
| 19 | |
| 20 | return new Promise((resolve, reject) => { |
| 21 | bb.on('file', (name, file, filename, encoding, mimeType) => { |
| 22 | cache.fileMap.set(name, { data: [], info: { filename, encoding, mimeType } }) |
| 23 | |
| 24 | file.on('data', (data) => { |
| 25 | const old = cache.fileMap.get(name) |
| 26 | |
| 27 | cache.fileMap.set(name, { |
| 28 | data: [...old.data, data], |
| 29 | info: old.info |
| 30 | }) |
| 31 | }).on('end', () => { |
| 32 | const old = cache.fileMap.get(name) |
| 33 | |
| 34 | cache.fileMap.set(name, { |
| 35 | data: Buffer.concat(old.data), |
| 36 | info: old.info |
| 37 | }) |
| 38 | }) |
| 39 | }) |
| 40 | |
| 41 | bb.on('field', (key, value) => cache.fields.push({ key, value })) |
| 42 | bb.on('finish', () => resolve(cache)) |
| 43 | bb.on('error', (e) => reject(e)) |
| 44 | |
| 45 | bb.end(body) |
| 46 | }) |
| 47 | } |
| 48 | |
| 49 | module.exports = { |
| 50 | parseFormDataString |