Skip to content

Commit

Permalink
feat: add feature to update request before approval or rejection
Browse files Browse the repository at this point in the history
  • Loading branch information
pankajjs committed Jan 2, 2025
1 parent b7170b8 commit 88e354f
Show file tree
Hide file tree
Showing 5 changed files with 111 additions and 2 deletions.
1 change: 1 addition & 0 deletions constants/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export const REQUEST_LOG_TYPE = {
REQUEST_REJECTED: "REQUEST_REJECTED",
REQUEST_BLOCKED: "REQUEST_BLOCKED",
REQUEST_CANCELLED: "REQUEST_CANCELLED",
REQUEST_UPDATED: "REQUEST_UPDATED",
};

export const REQUEST_CREATED_SUCCESSFULLY = "Request created successfully";
Expand Down
64 changes: 63 additions & 1 deletion controllers/requests.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import firestore from "../utils/firestore";
import {
ERROR_WHILE_FETCHING_REQUEST,
ERROR_WHILE_UPDATING_REQUEST,
LOG_ACTION,
REQUEST_DOES_NOT_EXIST,
REQUEST_FETCHED_SUCCESSFULLY,
REQUEST_LOG_TYPE,
REQUEST_STATE,
REQUEST_TYPE,
} from "../constants/requests";
import { getRequests } from "../models/requests";
Expand All @@ -10,9 +16,11 @@ import { OooRequestCreateRequest, OooRequestResponse } from "../types/oooRequest
import { CustomResponse } from "../typeDefinitions/global";
import { ExtensionRequestRequest, ExtensionRequestResponse } from "../types/extensionRequests";
import { createTaskExtensionRequest, updateTaskExtensionRequest } from "./extensionRequestsv2";
import { UpdateRequest } from "../types/requests";
import { UpdateRequest, UpdateRequestBeforeApproval } from "../types/requests";
import { TaskRequestRequest } from "../types/taskRequests";
import { createTaskRequestController } from "./taskRequestsv2";
import { addLog } from "../models/logs";
const requestModel = firestore.collection("requests");

export const createRequestController = async (
req: OooRequestCreateRequest | ExtensionRequestRequest | TaskRequestRequest,
Expand Down Expand Up @@ -97,3 +105,57 @@ export const getRequestsController = async (req: any, res: any) => {
return res.boom.badImplementation(ERROR_WHILE_FETCHING_REQUEST);
}
};

export const updateRequestBeforeApprovalController = async (req: UpdateRequestBeforeApproval, res: CustomResponse) => {
const body = req.body;
const id = req.params.id;
const lastModifiedBy = req?.userData?.id;

try{
const extensionRequest = await requestModel.doc(id).get() as unknown as {id: string, oldEndsOn: number, state: string};

if(!extensionRequest){
return res.boom.notFound(REQUEST_DOES_NOT_EXIST);
}

if(extensionRequest.oldEndsOn > body.newEndsOn) {
return res.boom.badRequest("Request new deadline must be greater than old deadline.");
}

if(extensionRequest.state != REQUEST_STATE.PENDING){
return res.boom.badRequest("Request state is not pending");
}

const requestBody = {
...body,
lastModifiedBy,
updatedAt: Date.now(),
}

await requestModel.doc(id).update(requestBody);

const requestLog = {
type: REQUEST_LOG_TYPE.REQUEST_UPDATED,
meta: {
requestId: extensionRequest.id,
action: LOG_ACTION.UPDATE,
createdBy: lastModifiedBy,
createdAt: Date.now(),
},
body: requestBody,
};

await addLog(requestLog.type, requestLog.meta, requestLog.body);

return res.status(200).json({
message: "Request updated successfully",
data: {
id: extensionRequest.id,
...requestBody
}
})
}catch(error){
logger.error(ERROR_WHILE_UPDATING_REQUEST, error);
return res.boom.badImplementation(ERROR_WHILE_UPDATING_REQUEST);
}
}
31 changes: 31 additions & 0 deletions middlewares/validators/updateRequestValidator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { NextFunction, Request } from "express";
import joi from "joi";
import { CustomResponse } from "../../types/global";

export const updateRequestValidator = async (
req: Request,
res: CustomResponse,
next: NextFunction
) => {

const schema = joi
.object()
.strict()
.keys({
reason: joi.string().optional(),
newEndsOn: joi.number().positive().min(Date.now()).required().messages({
'number.any': 'newEndsOn is required',
'number.base': 'newEndsOn must be a number',
'number.positive': 'newEndsOn must be positive',
'number.greater': 'newEndsOn must be greater than current date',
})})

try {
await schema.validateAsync(req.body, { abortEarly: false });
next();
} catch (error) {
const errorMessages = error.details.map((detail:{message: string}) => detail.message);
logger.error(`Error while validating request payload : ${errorMessages}`);
return res.boom.badRequest(errorMessages);
}
};
5 changes: 4 additions & 1 deletion routes/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ const { SUPERUSER } = require("../constants/roles");

import authenticate from "../middlewares/authenticate";
import { createRequestsMiddleware,updateRequestsMiddleware,getRequestsMiddleware } from "../middlewares/validators/requests";
import { createRequestController , updateRequestController, getRequestsController} from "../controllers/requests";
import { createRequestController , updateRequestController, getRequestsController, updateRequestBeforeApprovalController, } from "../controllers/requests";
import { updateRequestValidator } from "../middlewares/validators/updateRequestValidator";

router.get("/", getRequestsMiddleware, getRequestsController);
router.post("/",authenticate, createRequestsMiddleware, createRequestController);
router.put("/:id",authenticate, authorizeRoles([SUPERUSER]), updateRequestsMiddleware, updateRequestController);
router.patch("/:id", authenticate, updateRequestValidator, updateRequestBeforeApprovalController);

Check failure

Code scanning / CodeQL

Missing rate limiting High

This route handler performs
authorization
, but is not rate-limited.
This route handler performs
authorization
, but is not rate-limited.
This route handler performs
authorization
, but is not rate-limited.
module.exports = router;

12 changes: 12 additions & 0 deletions types/requests.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,15 @@ export type UpdateRequest = Request & {
query: RequestQuery;
params: RequestParams;
};

export type UpdateRequestBeforeApprovalBody = {
reason?: string
newEndsOn: number
}

export type UpdateRequestBeforeApproval = Request & {
body: UpdateRequestBeforeApprovalBody;
userData: userData;
query: RequestQuery;
params: RequestParams;
}

0 comments on commit 88e354f

Please sign in to comment.