Skip to content

Commit

Permalink
[TM-1531] add lint and reduce queries
Browse files Browse the repository at this point in the history
  • Loading branch information
egrojMonroy committed Dec 12, 2024
1 parent 50f7ede commit a9ed70a
Showing 1 changed file with 60 additions and 62 deletions.
122 changes: 60 additions & 62 deletions apps/job-service/src/jobs/delayed-jobs.controller.ts
Original file line number Diff line number Diff line change
@@ -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<JsonApiDocument> {
async getRunningJobs(@Request() { authenticatedUserId }): Promise<JsonApiDocument> {
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<JsonApiDocument> {
async findOne(@Param("uuid") pathUUID: string): Promise<JsonApiDocument> {
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<JsonApiDocument> {
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();

}
}
}

0 comments on commit a9ed70a

Please sign in to comment.