From a9ed70a3661d028a36e55f3036244b115ea1a8f2 Mon Sep 17 00:00:00 2001 From: JORGE Date: Thu, 12 Dec 2024 10:53:24 -0400 Subject: [PATCH] [TM-1531] add lint and reduce queries --- .../src/jobs/delayed-jobs.controller.ts | 122 +++++++++--------- 1 file changed, 60 insertions(+), 62 deletions(-) diff --git a/apps/job-service/src/jobs/delayed-jobs.controller.ts b/apps/job-service/src/jobs/delayed-jobs.controller.ts index 7ae56d9..63c3556 100644 --- a/apps/job-service/src/jobs/delayed-jobs.controller.ts +++ b/apps/job-service/src/jobs/delayed-jobs.controller.ts @@ -1,116 +1,114 @@ -import { Controller, Get, NotFoundException, Param, UnauthorizedException, Request, Patch, BadRequestException, Body, Logger } from '@nestjs/common'; -import { ApiException } from '@nanogiants/nestjs-swagger-api-exception-decorator'; -import { ApiOperation } from '@nestjs/swagger'; -import { Op } from 'sequelize'; -import { JsonApiResponse } from '@terramatch-microservices/common/decorators'; import { - buildJsonApi, - JsonApiDocument, -} from '@terramatch-microservices/common/util'; -import { DelayedJobDto } from './dto/delayed-job.dto'; -import { DelayedJob } from '@terramatch-microservices/database/entities'; -import { DelayedJobBulkUpdateBodyDto } from './dto/delayed-job-update.dto'; + Controller, + Get, + NotFoundException, + Param, + UnauthorizedException, + Request, + Patch, + BadRequestException, + Body, + Logger +} from "@nestjs/common"; +import { ApiException } from "@nanogiants/nestjs-swagger-api-exception-decorator"; +import { ApiOperation } from "@nestjs/swagger"; +import { Op } from "sequelize"; +import { JsonApiResponse } from "@terramatch-microservices/common/decorators"; +import { buildJsonApi, JsonApiDocument } from "@terramatch-microservices/common/util"; +import { DelayedJobDto } from "./dto/delayed-job.dto"; +import { DelayedJob } from "@terramatch-microservices/database/entities"; +import { DelayedJobBulkUpdateBodyDto } from "./dto/delayed-job-update.dto"; -@Controller('jobs/v3/delayedJobs') +@Controller("jobs/v3/delayedJobs") export class DelayedJobsController { @Get() @ApiOperation({ - operationId: 'listDelayedJobs', - description: 'Retrieve a list of all delayed jobs.', + operationId: "listDelayedJobs", + description: "Retrieve a list of all delayed jobs." }) @JsonApiResponse({ data: { type: DelayedJobDto } }) @ApiException(() => UnauthorizedException, { - description: 'Authentication failed.', + description: "Authentication failed." }) - async getRunningJobs( - @Request() { authenticatedUserId } - ): Promise { + async getRunningJobs(@Request() { authenticatedUserId }): Promise { const runningJobs = await DelayedJob.findAll({ where: { isAcknowledged: false, createdBy: authenticatedUserId }, - order: [['createdAt', 'DESC']], + order: [["createdAt", "DESC"]] }); const document = buildJsonApi(); - runningJobs.forEach((job) => { + runningJobs.forEach(job => { document.addData(job.uuid, new DelayedJobDto(job)); }); return document.serialize(); } - @Get(':uuid') + @Get(":uuid") @ApiOperation({ - operationId: 'delayedJobsFind', - description: - 'Get the current status and potentially payload or error from a delayed job.', + operationId: "delayedJobsFind", + description: "Get the current status and potentially payload or error from a delayed job." }) @JsonApiResponse({ data: { type: DelayedJobDto } }) @ApiException(() => UnauthorizedException, { - description: 'Authentication failed.', + description: "Authentication failed." }) @ApiException(() => NotFoundException, { - description: 'Job with that UUID not found.', + description: "Job with that UUID not found." }) // Note: Since jobs are very generic and we don't track which resources are related to a given // job, there is no effective way to make a policy for jobs until we expand the service to // include an owner ID on the job table. - async findOne(@Param('uuid') pathUUID: string): Promise { + async findOne(@Param("uuid") pathUUID: string): Promise { const job = await DelayedJob.findOne({ where: { uuid: pathUUID } }); if (job == null) throw new NotFoundException(); - return buildJsonApi() - .addData(pathUUID, new DelayedJobDto(job)) - .document.serialize(); + return buildJsonApi().addData(pathUUID, new DelayedJobDto(job)).document.serialize(); } - @Patch('bulk-update') + @Patch("bulk-update") @ApiOperation({ - operationId: 'bulkUpdateJobs', - summary: 'Bulk update jobs to modify isAcknowledged for specified job IDs', - description: `Accepts a JSON:API-compliant payload to bulk update jobs, allowing each job's isAcknowledged attribute to be set to true or false.`, + operationId: "bulkUpdateJobs", + summary: "Bulk update jobs to modify isAcknowledged for specified job IDs", + description: `Accepts a JSON:API-compliant payload to bulk update jobs, allowing each job's isAcknowledged attribute to be set to true or false.` }) @JsonApiResponse({ data: { type: DelayedJobDto } }) - @ApiException(() => UnauthorizedException, { description: 'Authentication failed.' }) - @ApiException(() => BadRequestException, { description: 'Invalid payload or IDs provided.' }) - @ApiException(() => NotFoundException, { description: 'One or more jobs specified in the payload could not be found.' }) + @ApiException(() => UnauthorizedException, { description: "Authentication failed." }) + @ApiException(() => BadRequestException, { description: "Invalid payload or IDs provided." }) + @ApiException(() => NotFoundException, { + description: "One or more jobs specified in the payload could not be found." + }) async bulkUpdateJobs( @Body() bulkUpdateJobsDto: DelayedJobBulkUpdateBodyDto, @Request() { authenticatedUserId } ): Promise { const jobUpdates = bulkUpdateJobsDto.data; - const updatePromises = jobUpdates.map(async (job) => { - const [updatedCount] = await DelayedJob.update( - { isAcknowledged: job.attributes.isAcknowledged }, - { - where: { - uuid: job.uuid, - createdBy: authenticatedUserId, - status: { [Op.ne]: 'pending' }, - }, - }); - - if (updatedCount === 0) { - throw new NotFoundException(`Job with UUID ${job.uuid} could not be updated.`); + const jobs = await DelayedJob.findAll({ + where: { + uuid: { [Op.in]: jobUpdates.map(({ uuid }) => uuid) }, + createdBy: authenticatedUserId, + status: { [Op.ne]: "pending" } } - - const updatedJob = await DelayedJob.findOne({ - where: { uuid: job.uuid }, - }); + }); + if (jobs.length !== jobUpdates.length) { + throw new NotFoundException("Some jobs in the request could not be updated"); + } - return updatedJob; + const updatePromises = jobUpdates.map(async ({ uuid, attributes }) => { + const job = jobs.find(job => job.uuid === uuid); + job.isAcknowledged = attributes.isAcknowledged; + await job.save(); + return job; }); - + const updatedJobs = await Promise.all(updatePromises); - - + const jsonApiBuilder = buildJsonApi(); - updatedJobs.forEach((job) => { + updatedJobs.forEach(job => { jsonApiBuilder.addData(job.uuid, new DelayedJobDto(job)); }); - return jsonApiBuilder.serialize(); - } -} \ No newline at end of file +}