From 3bc18a95816a4c352d399483040562e32fda3f4d Mon Sep 17 00:00:00 2001 From: hanoak20 Date: Mon, 29 Jan 2024 13:38:49 +0530 Subject: [PATCH 1/4] chore: updated the getLogMessage method in utils/index.ts --- src/utils/index.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/utils/index.ts b/src/utils/index.ts index a83fae24..18bd6adc 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -14,11 +14,17 @@ export const safePromise = (promise: Promise): Promise => promise.then((res) => [null, res]).catch((err) => [err]); //Generic method to get log message object -export const getLogMessage = (methodName: string, message = {}, user = {}) => { +export const getLogMessage = ( + message: string, + methodName: string, + user = {}, + error?: any +) => { return { - methodName: methodName, - message: message, - user: user, + message, + methodName, + ...(user && { user }), + ...(error && { error }), }; }; From c40bedc26880a07f8c636ae51d0a5265fd15ebb5 Mon Sep 17 00:00:00 2001 From: hanoak20 Date: Mon, 29 Jan 2024 13:43:39 +0530 Subject: [PATCH 2/4] chore: removed types for constants in constants/index.ts --- src/constants/index.ts | 59 +----------------------------------------- 1 file changed, 1 insertion(+), 58 deletions(-) diff --git a/src/constants/index.ts b/src/constants/index.ts index fcedfb43..2239fb21 100644 --- a/src/constants/index.ts +++ b/src/constants/index.ts @@ -1,61 +1,4 @@ -export type HttpErrorCodes = { - OK: number; - FORBIDDEN: number; - BAD_REQUEST: number; - NOT_FOUND: number; - UNAUTHORIZED: number; - TOO_MANY_REQS: number; - SOMETHING_WRONG: number; - MOVED_PERMANENTLY: number; - SUPPORT_DOC: number; - SERVER_ERROR: number; - UNPROCESSABLE_CONTENT: number; -}; - -export type ValidationErrors = { - INVALID_EMAIL: string; - EMAIL_LIMIT: string; - LENGTH_LIMIT: string; - STRING_REQUIRED: string; - INVALID_REGION: string; -}; - -export type ConstantType = { - CS_REGIONS: Array; - AXIOS_TIMEOUT: number; - HTTP_CODES: HttpErrorCodes; - HTTP_TEXTS: HttpErrorTexts; - HTTP_RESPONSE_HEADERS: HttpResponseHeaders; - METHODS_TO_INCLUDE_DATA_IN_AXIOS: Array; - VALIDATION_ERRORS: ValidationErrors; -}; - -export type HttpErrorTexts = { - UNAUTHORIZED: string; - INTERNAL_ERROR: string; - SOMETHING_WENT_WRONG: string; - NO_CS_USER: string; - SUCCESS_LOGIN: string; - TOKEN_ERROR: string; - LOGIN_ERROR: string; - ROUTE_ERROR: string; - NO_PROJECT: string; - MIGRATION_CREATED: string; - MIGRATION_UPDATED: string; - CMS_UPDATED: string; - FILE_FORMAT_UPDATED: string; - MIGRATION_DELETED: string; - INVALID_ID: string; - MIGRATION_EXISTS: string; -}; - -export type HttpResponseHeaders = { - "Access-Control-Allow-Origin": string; - "Content-Type": string; - Connection: string; -}; - -export const constants: ConstantType = { +export const constants = { CS_REGIONS: ["US", "EU", "AZURE_NA", "AZURE_EU"], AXIOS_TIMEOUT: 60 * 1000, HTTP_CODES: { From d2f28159ede88d6c479d8bb9e31febe7dfc8a326 Mon Sep 17 00:00:00 2001 From: hanoak20 Date: Mon, 29 Jan 2024 14:09:07 +0530 Subject: [PATCH 3/4] chore: added srcFun name to all the custom Error classes. --- src/middlewares/error.middleware.ts | 1 + src/services/auth.service.ts | 7 +++-- src/services/projects.migrations.service.ts | 23 +++++++++----- src/services/user.service.ts | 10 +++++-- src/utils/custom-errors.utils.ts | 33 +++++++++++++-------- src/validators/index.ts | 2 +- 6 files changed, 52 insertions(+), 24 deletions(-) diff --git a/src/middlewares/error.middleware.ts b/src/middlewares/error.middleware.ts index a401b46f..f2a4b7b2 100644 --- a/src/middlewares/error.middleware.ts +++ b/src/middlewares/error.middleware.ts @@ -13,6 +13,7 @@ export const errorMiddleware = ( logger.error(err.stack); if (err instanceof AppError) { + logger.error(`Error in method: ${err.srcFunc}`); res .status(err.statusCode) .json({ error: { code: err.statusCode, message: err.message } }); diff --git a/src/services/auth.service.ts b/src/services/auth.service.ts index ed250e6c..6a961661 100644 --- a/src/services/auth.service.ts +++ b/src/services/auth.service.ts @@ -46,7 +46,7 @@ const login = async (req: Request): Promise => { }; if (!res?.data?.user) - throw new BadRequestError(constants.HTTP_TEXTS.NO_CS_USER); + throw new BadRequestError(constants.HTTP_TEXTS.NO_CS_USER, "login"); const appTokenPayload: AppTokenPayload = { region: userData?.region, @@ -106,7 +106,10 @@ const requestSms = async (req: Request): Promise => { status: res.status, }; } catch (error) { - throw new InternalServerError(); + throw new InternalServerError( + constants.HTTP_TEXTS.INTERNAL_ERROR, + "requestSms" + ); } }; diff --git a/src/services/projects.migrations.service.ts b/src/services/projects.migrations.service.ts index a42b4ddc..d1c3c105 100644 --- a/src/services/projects.migrations.service.ts +++ b/src/services/projects.migrations.service.ts @@ -9,12 +9,14 @@ import { MigrationQueryType } from "../models/types"; const _getProject = async (projectId: string, query: MigrationQueryType) => { if (!isValidObjectId(projectId)) throw new BadRequestError( - constants.HTTP_TEXTS.INVALID_ID.replace("$", "project") + constants.HTTP_TEXTS.INVALID_ID.replace("$", "project"), + "_getProject" ); const project = await ProjectModel.findOne(query); - if (!project) throw new NotFoundError(constants.HTTP_TEXTS.NO_PROJECT); + if (!project) + throw new NotFoundError(constants.HTTP_TEXTS.NO_PROJECT, "_getProject"); return project; }; @@ -68,7 +70,10 @@ const createMigration = async (req: Request) => { }); if (project.migration?.length) - throw new BadRequestError(constants.HTTP_TEXTS.MIGRATION_EXISTS); + throw new BadRequestError( + constants.HTTP_TEXTS.MIGRATION_EXISTS, + "createMigration" + ); project.migration.push({ _id: getMongooseID(), @@ -109,7 +114,8 @@ const updateMigration = async (req: Request) => { if (!isValidObjectId(migrationId)) throw new BadRequestError( - constants.HTTP_TEXTS.INVALID_ID.replace("$", "migration") + constants.HTTP_TEXTS.INVALID_ID.replace("$", "migration"), + "updateMigration" ); const project = await _getProject(projectId, { @@ -143,7 +149,8 @@ const updateMigrationLegacyCMS = async (req: Request) => { if (!isValidObjectId(migrationId)) throw new BadRequestError( - constants.HTTP_TEXTS.INVALID_ID.replace("$", "migration") + constants.HTTP_TEXTS.INVALID_ID.replace("$", "migration"), + "updateMigrationLegacyCMS" ); const project = await _getProject(projectId, { @@ -172,7 +179,8 @@ const updateMigrationFileFormat = async (req: Request) => { if (!isValidObjectId(migrationId)) throw new BadRequestError( - constants.HTTP_TEXTS.INVALID_ID.replace("$", "migration") + constants.HTTP_TEXTS.INVALID_ID.replace("$", "migration"), + "updateMigrationFileFormat" ); const project = await _getProject(projectId, { @@ -203,7 +211,8 @@ const deleteMigration = async (req: Request) => { if (!isValidObjectId(migrationId)) throw new BadRequestError( - constants.HTTP_TEXTS.INVALID_ID.replace("$", "migration") + constants.HTTP_TEXTS.INVALID_ID.replace("$", "migration"), + "deleteMigration" ); const filter = { diff --git a/src/services/user.service.ts b/src/services/user.service.ts index 89110f20..e5f9190f 100644 --- a/src/services/user.service.ts +++ b/src/services/user.service.ts @@ -15,7 +15,10 @@ const getUserProfile = async (req: Request): Promise => { }).lean(); if (!user?.authtoken) - throw new BadRequestError(constants.HTTP_TEXTS.NO_CS_USER); + throw new BadRequestError( + constants.HTTP_TEXTS.NO_CS_USER, + "getUserProfile" + ); const res = await https({ method: "GET", @@ -29,7 +32,10 @@ const getUserProfile = async (req: Request): Promise => { }); if (!res?.data?.user) - throw new BadRequestError(constants.HTTP_TEXTS.NO_CS_USER); + throw new BadRequestError( + constants.HTTP_TEXTS.NO_CS_USER, + "getUserProfile" + ); const orgs = (res?.data?.user?.organizations || []) ?.filter((org: any) => org?.org_roles?.some((item: any) => item.admin)) diff --git a/src/utils/custom-errors.utils.ts b/src/utils/custom-errors.utils.ts index 5853e9e6..eb70db8c 100644 --- a/src/utils/custom-errors.utils.ts +++ b/src/utils/custom-errors.utils.ts @@ -1,45 +1,54 @@ import { constants } from "../constants"; export class AppError extends Error { - constructor(public statusCode: number, message: string) { + srcFunc: string; + constructor( + public statusCode: number, + message: string, + srcFunc: string = "" + ) { super(message); + this.srcFunc = srcFunc; Object.setPrototypeOf(this, AppError.prototype); } } export class NotFoundError extends AppError { - constructor(message: string = "Not Found") { - super(constants.HTTP_CODES.NOT_FOUND, message); + constructor(message: string = "Not Found", srcFunc: string = "") { + super(constants.HTTP_CODES.NOT_FOUND, message, srcFunc); } } export class BadRequestError extends AppError { - constructor(message: string = "Bad Request") { - super(constants.HTTP_CODES.BAD_REQUEST, message); + constructor(message: string = "Bad Request", srcFunc: string = "") { + super(constants.HTTP_CODES.BAD_REQUEST, message, srcFunc); } } export class DatabaseError extends AppError { - constructor(message: string = "DB error") { - super(constants.HTTP_CODES.SERVER_ERROR, message); + constructor(message: string = "DB error", srcFunc: string = "") { + super(constants.HTTP_CODES.SERVER_ERROR, message, srcFunc); } } export class ValidationError extends AppError { - constructor(message: string = "User validation error") { - super(constants.HTTP_CODES.UNPROCESSABLE_CONTENT, message); + constructor(message: string = "User validation error", srcFunc: string = "") { + super(constants.HTTP_CODES.UNPROCESSABLE_CONTENT, message, srcFunc); } } export class InternalServerError extends AppError { - constructor(message: string = constants.HTTP_TEXTS.INTERNAL_ERROR) { - super(constants.HTTP_CODES.SERVER_ERROR, message); + constructor( + message: string = constants.HTTP_TEXTS.INTERNAL_ERROR, + srcFunc: string = "" + ) { + super(constants.HTTP_CODES.SERVER_ERROR, message, srcFunc); } } export class UnauthorizedError extends AppError { constructor(message: string = constants.HTTP_TEXTS.UNAUTHORIZED) { - super(constants.HTTP_CODES.UNAUTHORIZED, message); + super(constants.HTTP_CODES.UNAUTHORIZED, message, "Auth utils"); } } diff --git a/src/validators/index.ts b/src/validators/index.ts index 4d1012f8..6f86cc6d 100644 --- a/src/validators/index.ts +++ b/src/validators/index.ts @@ -21,7 +21,7 @@ export default (route: string = "") => .map((field) => field.array()) .reduce((acc, val) => [...acc, ...val], []); - if (result.length) throw new ValidationError(result[0].msg); + if (result.length) throw new ValidationError(result[0].msg, "validation"); return next(); }); From 914e04bdf1e37c3cf497c21f0fe77348aa9ac744 Mon Sep 17 00:00:00 2001 From: hanoak20 Date: Mon, 29 Jan 2024 19:16:37 +0530 Subject: [PATCH 4/4] chore: Removed migrationId and project schema. --- src/models/project.ts | 36 +++++----- src/models/types.ts | 1 - src/routes/projects.migrations.routes.ts | 11 ++- src/services/projects.migrations.service.ts | 78 ++++++--------------- 4 files changed, 41 insertions(+), 85 deletions(-) diff --git a/src/models/project.ts b/src/models/project.ts index 96a67516..4cc0045a 100644 --- a/src/models/project.ts +++ b/src/models/project.ts @@ -18,7 +18,6 @@ interface Modules { } interface Migration { - _id: Schema.Types.ObjectId; name: string; description: string; created_at: Date; @@ -38,7 +37,7 @@ interface ProjectDocument extends Document { name: string; description: string; status: boolean; - migration: [Migration]; + migration: Migration; execution_log: ExecutionLog; } @@ -51,26 +50,23 @@ const projectSchema = new Schema( name: { type: String, required: true }, description: { type: String, required: true }, status: { type: Boolean, default: true }, - migration: [ - { - _id: Schema.Types.ObjectId, - name: { type: String }, - description: { type: String }, - created_at: { type: Date }, - updated_at: { type: Date }, - modules: { - legacy_cms: { - cms: { type: String }, - file_format: { type: String }, - import_data: { type: String }, - }, - destination_cms: { - stack_id: { type: String }, - org_id: { type: String }, - }, + migration: { + name: { type: String }, + description: { type: String }, + created_at: { type: Date }, + updated_at: { type: Date }, + modules: { + legacy_cms: { + cms: { type: String }, + file_format: { type: String }, + import_data: { type: String }, + }, + destination_cms: { + stack_id: { type: String }, + org_id: { type: String }, }, }, - ], + }, execution_log: { log_url: { type: String }, }, diff --git a/src/models/types.ts b/src/models/types.ts index 2dae0ab6..e5270b81 100644 --- a/src/models/types.ts +++ b/src/models/types.ts @@ -24,7 +24,6 @@ export interface LoginServiceType { export interface MigrationQueryType { _id: string; - "migration._id"?: string; org_id: string; region: string; owner: string; diff --git a/src/routes/projects.migrations.routes.ts b/src/routes/projects.migrations.routes.ts index dedb2840..825e3ac4 100644 --- a/src/routes/projects.migrations.routes.ts +++ b/src/routes/projects.migrations.routes.ts @@ -17,29 +17,26 @@ router.post( // Update project's migration route router.put( - "/:migrationId", + "/", validator("project"), asyncRouter(migrationController.updateMigration) ); // Update project's legacy-cms router.put( - "/:migrationId/legacy-cms", + "/legacy-cms", validator("cms"), asyncRouter(migrationController.updateMigrationLegacyCMS) ); // Update project's file format router.put( - "/:migrationId/file-format", + "/file-format", validator("file_format"), asyncRouter(migrationController.updateMigrationFileFormat) ); // Delete project's migration route -router.delete( - "/:migrationId", - asyncRouter(migrationController.deleteMigration) -); +router.delete("/", asyncRouter(migrationController.deleteMigration)); export default router; diff --git a/src/services/projects.migrations.service.ts b/src/services/projects.migrations.service.ts index d1c3c105..7150831c 100644 --- a/src/services/projects.migrations.service.ts +++ b/src/services/projects.migrations.service.ts @@ -2,7 +2,7 @@ import { Request } from "express"; import { constants } from "../constants"; import ProjectModel from "../models/project"; -import { isValidObjectId, getMongooseID } from "../utils"; +import { isValidObjectId } from "../utils"; import { NotFoundError, BadRequestError } from "../utils/custom-errors.utils"; import { MigrationQueryType } from "../models/types"; @@ -23,7 +23,6 @@ const _getProject = async (projectId: string, query: MigrationQueryType) => { const _getCondensedMigration = (projectId: string, data: any) => { return { - id: data._id, name: data.name, description: data.description, created_at: data.created_at, @@ -48,11 +47,9 @@ const getMigration = async (req: Request) => { return { status: constants.HTTP_CODES.OK, data: { - migration: [ - project.migration?.[0]?._id - ? _getCondensedMigration(projectId, project.migration[0]) - : {}, - ], + migration: project?.migration?.name + ? _getCondensedMigration(projectId, project.migration) + : {}, }, }; }; @@ -69,14 +66,13 @@ const createMigration = async (req: Request) => { owner: token_payload?.user_id, }); - if (project.migration?.length) + if (project.migration?.name) throw new BadRequestError( constants.HTTP_TEXTS.MIGRATION_EXISTS, "createMigration" ); - project.migration.push({ - _id: getMongooseID(), + project.migration = { created_at: new Date(), updated_at: new Date(), ...req?.body, @@ -91,7 +87,7 @@ const createMigration = async (req: Request) => { org_id: "", }, }, - }); + }; const updatedProject = await project.save(); @@ -99,9 +95,7 @@ const createMigration = async (req: Request) => { status: constants.HTTP_CODES.OK, data: { message: constants.HTTP_TEXTS.MIGRATION_CREATED, - migration: [ - _getCondensedMigration(projectId, updatedProject.migration[0]), - ], + migration: _getCondensedMigration(projectId, updatedProject.migration), }, }; }; @@ -109,26 +103,18 @@ const createMigration = async (req: Request) => { const updateMigration = async (req: Request) => { const orgId = req?.params?.orgId; const projectId = req?.params?.projectId; - const migrationId = req?.params?.migrationId; const { token_payload, name, description } = req.body; - if (!isValidObjectId(migrationId)) - throw new BadRequestError( - constants.HTTP_TEXTS.INVALID_ID.replace("$", "migration"), - "updateMigration" - ); - const project = await _getProject(projectId, { _id: projectId, - "migration._id": migrationId, org_id: orgId, region: token_payload?.region, owner: token_payload?.user_id, }); - project.migration[0].name = name; - project.migration[0].description = description; - project.migration[0].updated_at = new Date(); + project.migration.name = name; + project.migration.description = description; + project.migration.updated_at = new Date(); const updatedProject = await project.save(); @@ -136,32 +122,23 @@ const updateMigration = async (req: Request) => { status: constants.HTTP_CODES.OK, data: { message: constants.HTTP_TEXTS.MIGRATION_UPDATED, - migration: [ - _getCondensedMigration(projectId, updatedProject.migration[0]), - ], + migration: _getCondensedMigration(projectId, updatedProject.migration), }, }; }; const updateMigrationLegacyCMS = async (req: Request) => { - const { orgId, projectId, migrationId } = req.params; + const { orgId, projectId } = req.params; const { token_payload, legacy_cms } = req.body; - if (!isValidObjectId(migrationId)) - throw new BadRequestError( - constants.HTTP_TEXTS.INVALID_ID.replace("$", "migration"), - "updateMigrationLegacyCMS" - ); - const project = await _getProject(projectId, { _id: projectId, - "migration._id": migrationId, org_id: orgId, region: token_payload?.region, owner: token_payload?.user_id, }); - project.migration[0].modules.legacy_cms.cms = legacy_cms; + project.migration.modules.legacy_cms.cms = legacy_cms; await project.save(); @@ -174,24 +151,17 @@ const updateMigrationLegacyCMS = async (req: Request) => { }; const updateMigrationFileFormat = async (req: Request) => { - const { orgId, projectId, migrationId } = req.params; + const { orgId, projectId } = req.params; const { token_payload, file_format } = req.body; - if (!isValidObjectId(migrationId)) - throw new BadRequestError( - constants.HTTP_TEXTS.INVALID_ID.replace("$", "migration"), - "updateMigrationFileFormat" - ); - const project = await _getProject(projectId, { _id: projectId, - "migration._id": migrationId, org_id: orgId, region: token_payload?.region, owner: token_payload?.user_id, }); - project.migration[0].modules.legacy_cms.file_format = file_format; + project.migration.modules.legacy_cms.file_format = file_format; await project.save(); @@ -206,27 +176,21 @@ const updateMigrationFileFormat = async (req: Request) => { const deleteMigration = async (req: Request) => { const orgId = req?.params?.orgId; const projectId = req?.params?.projectId; - const migrationId = req?.params?.migrationId; const { token_payload } = req.body; - if (!isValidObjectId(migrationId)) - throw new BadRequestError( - constants.HTTP_TEXTS.INVALID_ID.replace("$", "migration"), - "deleteMigration" - ); - const filter = { _id: projectId, - "migration._id": migrationId, org_id: orgId, region: token_payload?.region, owner: token_payload?.user_id, }; - const project = await _getProject(projectId, filter); + await _getProject(projectId, filter); - project.migration.shift(); - await project.save(); + await ProjectModel.updateOne( + { _id: projectId }, + { $set: { migration: null } } + ); return { status: constants.HTTP_CODES.OK,