Picsur/backend/src/decorators/multipart/postfile.pipe.ts

46 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-05-01 21:29:56 +00:00
import { Multipart } from '@fastify/multipart';
2022-09-06 14:32:16 +00:00
import { Injectable, Logger, PipeTransform, Scope } from '@nestjs/common';
2022-03-06 11:27:11 +00:00
import { FastifyRequest } from 'fastify';
2022-07-19 12:54:02 +00:00
import { Fail, FT } from 'picsur-shared/dist/types';
2022-04-18 12:34:53 +00:00
import { MultipartConfigService } from '../../config/early/multipart.config.service';
2022-03-06 11:27:11 +00:00
@Injectable({ scope: Scope.REQUEST })
export class PostFilePipe implements PipeTransform {
2022-09-02 15:18:22 +00:00
private readonly logger = new Logger(PostFilePipe.name);
2022-03-06 11:27:11 +00:00
2022-06-27 15:37:37 +00:00
constructor(
private readonly multipartConfigService: MultipartConfigService,
) {}
2022-03-06 11:27:11 +00:00
async transform({ req }: { req: FastifyRequest }) {
2022-07-19 12:54:02 +00:00
if (!req.isMultipart()) throw Fail(FT.UsrValidation, 'Invalid file');
2022-03-06 11:27:11 +00:00
2022-03-28 10:44:00 +00:00
// Only one file is allowed
2022-03-06 11:27:11 +00:00
const file = await req.file({
limits: {
...this.multipartConfigService.getLimits(),
files: 1,
},
});
2022-07-19 12:54:02 +00:00
if (file === undefined) throw Fail(FT.UsrValidation, 'Invalid file');
2022-03-06 11:27:11 +00:00
2022-03-28 10:44:00 +00:00
// Remove empty fields
2022-03-06 11:27:11 +00:00
const allFields: Multipart[] = Object.values(file.fields).filter(
(entry) => entry,
) as any;
2022-03-28 10:44:00 +00:00
// Remove non-file fields
2022-03-06 11:27:11 +00:00
const files = allFields.filter((entry) => entry.file !== undefined);
2022-07-19 12:54:02 +00:00
if (files.length !== 1) throw Fail(FT.UsrValidation, 'Invalid file');
2022-03-06 11:27:11 +00:00
2022-03-28 10:44:00 +00:00
// Return a buffer of the file
2022-03-06 11:27:11 +00:00
try {
return await files[0].toBuffer();
} catch (e) {
this.logger.warn(e);
2022-07-19 12:54:02 +00:00
throw Fail(FT.Internal, 'Invalid file');
2022-03-06 11:27:11 +00:00
}
}
}