import { FastiFoxPlugin, IFastiFoxPlugin } from '../../protocols/crud-generator-helper.struct'; import { FastifyReply, FastifyRequest } from 'fastify'; import fs from 'fs'; import fastifyMultipart from '@fastify/multipart'; import busboy from 'busboy'; import path from 'path'; import { IRegisterMulterPlugin } from './multer-plugin.struct'; import AWS from 'aws-sdk'; export class UploadMulter extends FastiFoxPlugin implements IFastiFoxPlugin { name: string = 'upload-module'; register({ local, awsS3 }: IRegisterMulterPlugin) { this.server.register(fastifyMultipart); if (local) { this.server.get('/local/upload/:id', async (request: FastifyRequest | any, reply: FastifyReply) => { const { id } = request.params; const file = fs.readFileSync(path.join(local.destination, id)); reply.send({ file }); }) this.server.post('/local/upload', async (request: FastifyRequest, reply: FastifyReply) => { const bb = busboy({ headers: request.headers }); bb.on('file', (_, file, filename) => { const saveTo = path.join(local.destination, filename.filename); file.pipe(fs.createWriteStream(saveTo)); }); bb.on('finish', () => { reply.send({ status: 'uploaded' }); }); request.raw.pipe(bb); }); } if(awsS3){ this.server.post('/s3/upload', async (request: FastifyRequest, reply: FastifyReply) => { const bb = busboy({ headers: request.headers }); bb.on('file', (_, file, filename) => { const s3 = new AWS.S3({ accessKeyId: awsS3.accessKeyId, secretAccessKey: awsS3.secretAccessKey, region: awsS3.region }) const params = { Bucket: awsS3.bucket, Key: filename.filename, Body: file } s3.upload(params, (err: any, data: any) => { if (err) { reply.send({ status: 'error' }); } reply.send({ status: 'uploaded', data }); }); }); }); } } }