import { Body, Controller, Post, Res, Route, Security, SuccessResponse, TsoaResponse, } from 'tsoa'; import { getCustomRepository } from 'typeorm'; import { RawRetailerDataV1 } from '@/entities/RawRetailerProduct/types'; import logger from '@/logger'; import { RawRetailerProductRepository } from '@/repositories'; import { HttpStatusCodes } from '@/routes/types'; import { UserRole } from '@/types'; import { RawRetailerInput, RawRetailerPayload } from './types'; @Route('raw-retailers') @Security('basic', [UserRole.ADMIN]) export class RawRetailerController extends Controller { @Post() @SuccessResponse('201', 'Created') async rawRetailers( @Body() requestBody: RawRetailerInput, @Res() failed: TsoaResponse, @Res() invalidInput: TsoaResponse< HttpStatusCodes.UNPROCESSABLE_ENTITY, { reason: string } > ): Promise { try { const errors: RawRetailerDataV1[] = []; const { ingestionID, data, productIds } = requestBody; // @TODO: add bulk upsert await Promise.all( data.map(async (value) => { try { await getCustomRepository( RawRetailerProductRepository ).createFromData({ data: value, ingestionID, productIds, }); } catch (error) { logger.error(error); errors.push(value); } }) ); if (errors.length > 0) { return invalidInput(HttpStatusCodes.UNPROCESSABLE_ENTITY, { reason: `${ errors.length } errors creating raw retailers: ${JSON.stringify(errors)}`, }); } return { status: 'success' }; } catch (e: any) { return failed(HttpStatusCodes.SERVER_ERROR, { reason: e.message || 'Failed to create raw retailer', }); } } }