import { BadRequestException, Controller, HttpCode, Post, Request, UnauthorizedException, UploadedFile, UseInterceptors, } from '@nestjs/common'; import { Throttle } from '@nestjs/throttler'; import { FileInterceptor } from '@nestjs/platform-express'; import { memoryStorage } from 'multer'; import { FlyerImportResponse } from './dto/flyer-import.response'; import { FlyerImportService } from './flyer-import.service'; const ALLOWED_MIMES = [ 'application/pdf', 'application/octet-stream', 'text/plain', ]; @Controller('flyer-import') export class FlyerImportController { constructor(private readonly flyerImportService: FlyerImportService) {} @Post('parse') @HttpCode(200) @Throttle({ default: { ttl: 60_000, limit: 10 } }) @UseInterceptors( FileInterceptor('file', { storage: memoryStorage(), limits: { fileSize: 15 * 1024 * 1024 }, }), ) async parseFlyer( @UploadedFile() file?: Express.Multer.File, @Request() req?: any, ): Promise { if (!file?.buffer) { throw new BadRequestException('Ingen fil skickades med.'); } if (!ALLOWED_MIMES.includes(file.mimetype)) { throw new BadRequestException('Otillåten filtyp. Använd PDF eller textfil.'); } const userId = typeof req?.user?.id === 'number' ? req.user.id : typeof req?.user?.userId === 'number' ? req.user.userId : undefined; if (!userId) { throw new UnauthorizedException('Kunde inte identifiera användaren.'); } return this.flyerImportService.parseAndMatch(file, userId); } }