Skip to content

Commit

Permalink
Merge pull request #13 from poojakarma/template_api_changes_for_push_…
Browse files Browse the repository at this point in the history
…notification

PS - 2393 Template api changes for push notification
  • Loading branch information
snehal0904 authored Nov 7, 2024
2 parents 9b46160 + d399eab commit 3a23a37
Show file tree
Hide file tree
Showing 22 changed files with 512 additions and 515 deletions.
71 changes: 58 additions & 13 deletions src/common/filters/exception.filter.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,72 @@
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { QueryFailedError } from 'typeorm';
import { Response, Request } from 'express';
import APIResponse from '../utils/response';
import { ERROR_MESSAGES } from '../utils/constant.util';
import { LoggerUtil } from '../logger/LoggerUtil';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
constructor(private readonly apiId?: string) { }

catch(exception: unknown, host: ArgumentsHost) {
catch(
exception: Error | HttpException | QueryFailedError,
host: ArgumentsHost,
) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception instanceof HttpException ? exception.getStatus() : 500;
const exceptionResponse = exception instanceof HttpException ? exception.getResponse() : null;
const errorMessage =
exception instanceof HttpException
? (exceptionResponse as any).message || exception.message
: 'Internal server error';
const request = ctx.getRequest<Request>();
const userId = request?.query?.userid;
const status =
exception instanceof HttpException ? exception.getStatus() : 500;

let errorMessage =
exception?.message || ERROR_MESSAGES.INTERNAL_SERVER_ERROR;

LoggerUtil.error(`Error occurred on API: ${request.url} Method : ${request.method}`,
errorMessage, 'Notification Service', `requested by userId: ${userId}`,
)

if (exception instanceof HttpException) {
const statusCode = exception.getStatus();
const errorResponse = APIResponse.error(
this.apiId,
(exception.getResponse() as any)?.message,
ERROR_MESSAGES.BAD_REQUEST,
statusCode.toString(),
);
return response.status(statusCode).json(errorResponse);
} else if (exception instanceof QueryFailedError) {
const statusCode = HttpStatus.UNPROCESSABLE_ENTITY;
const errorResponse = APIResponse.error(
this.apiId,
(exception as QueryFailedError).message,
ERROR_MESSAGES.INTERNAL_SERVER_ERROR,
statusCode.toString(),
);
LoggerUtil.error(`Database Query Failed on API: ${request.url} requested by userId: ${userId}`,
request.method,
(exception as QueryFailedError).message,
'QueryFailedError')

return response.status(statusCode).json(errorResponse);
}
const detailedErrorMessage = `${errorMessage}`;
APIResponse.error(
response,

const errorResponse = APIResponse.error(
this.apiId,
detailedErrorMessage,
exception instanceof HttpException ? exception.name : 'InternalServerError', // error
status
exception instanceof HttpException
? exception.name
: ERROR_MESSAGES.INTERNAL_SERVER_ERROR,
status.toString(),
);
return response.status(status).json(errorResponse);
}
}
}
78 changes: 78 additions & 0 deletions src/common/logger/LoggerUtil.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import * as winston from 'winston';

export class LoggerUtil {
private static logger: winston.Logger;

static getLogger() {
if (!this.logger) {
const customFormat = winston.format.printf(
({ timestamp, level, message, context, user, error }) => {
return JSON.stringify({
timestamp: timestamp,
context: context,
user: user,
level: level,
message: message,
error: error,
});
},
);

this.logger = winston.createLogger({
level: 'info',
format: winston.format.combine(winston.format.timestamp(), customFormat),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' }),
],
});
}
return this.logger;
}
static log(
message: string,
context?: string,
user?: string,
level: string = 'info',
) {
this.getLogger().log({
level: level,
message: message,
context: context,
user: user,
timestamp: new Date().toISOString(),
});
}

static error(
message: string,
error?: string,
context?: string,
user?: string,
) {
this.getLogger().error({
message: message,
error: error,
context: context,
user: user,
timestamp: new Date().toISOString(),
});
}

static warn(message: string, context?: string) {
this.getLogger().warn({
message: message,
context: context,
timestamp: new Date().toISOString(),
});
}

static debug(message: string, context?: string) {
this.getLogger().debug({
message: message,
context: context,
timestamp: new Date().toISOString(),
});
}
}
64 changes: 0 additions & 64 deletions src/common/logger/logger.service.ts

This file was deleted.

41 changes: 36 additions & 5 deletions src/common/utils/constant.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,23 @@ export const SUCCESS_MESSAGES = {
NOTIFICATION_QUEUE_SAVE_SUCCESSFULLY: 'Notification saved in queue successfully',
NOTIFICATION_SENT_SUCCESSFULLY: 'Notification sent successfully',
PUSH_NOTIFICATION_SEND_SUCCESSFULLY: 'Push notification sent successfully',



TEMPLATE_CREATE: 'Template created successfully',
TEMPLATE_UPDATE: 'Template updated successfully',
TEMPLATE_DELETE: 'Template delete successfully',
TEMPLATE_GET: 'Template get successfully',
CREATE_TEMPLATE_API: '/create Template for Notification',
UPDATE_TEMPLATE_API: '/Update Template for Notification',
TEMPLATE_DELETE_ID: (actionId) => `Template id: ${actionId} deleted successfully.`,
TEMPLATE_LIST: 'Get template list',
CREATED: 'Created',
QUEUE_UPDATED: 'Updated Sucessfully',
QUEUE_LIST: 'Get Records from queue',
SAVE_NOTIFICATION_LOG: '/save Notification Log',
EMAIL_NOTIFICATION_SEND_SUCCESSFULLY: 'Email notification sent successfully',
SMS_NOTIFICATION_SEND_SUCCESSFULLY: 'SMS notification sent successfully',
TEMPLATE_CREATED_SUCESSFULLY: (userId) => `Template created successfully by userId: ${userId}`,
GET_TEMPLATE: (userId) => `Get Template successfully by userId: ${userId}`,
DELETE_TEMPLATE: (userId) => `Delete Template successfully by userId: ${userId}`
};
export const ERROR_MESSAGES = {
INVALID_REQUEST: "Invalid request",
Expand All @@ -22,6 +36,23 @@ export const ERROR_MESSAGES = {
NOTIFICATION_QUEUE_SAVE_FAILED: 'Failed to save notifications in queue',
NOTIFICATION_LOG_SAVE_FAILED: 'Failed to save Log of notification',
TOPIC_NOTIFICATION_FAILED: 'Failed to send topic notification',
PUSH_NOTIFICATION_FAILED: 'Failed to send push notification'

PUSH_NOTIFICATION_FAILED: 'Failed to send push notification',
TEMPLATE_ALREADY_EXIST: 'Template already exist',
TEMPLATE_NOT_EXIST: 'Template not exist',
TEMPLATE_NOT_DELETED: 'Template not deleted',
TEMPLATE_ID_NOTFOUND: (template_id) => `No template id found: ${template_id}`,
QUEUE_NOTFOUND: 'No data found in queue',
QUEUE_UPDATE: (id) => `No notification queue found for:${id}`,
EVENT_UPDATE_FAILED: 'Event update failed',
USERID_REQUIRED: 'User ID is required',
USERID_UUID: 'The userId should not be empty and must be valid UUID',
NOTIFICATION_SAVE_ERROR_IN_RABBITMQ: '/error to save in notification in rabbitMq',
NOTIFICATION_SEND_FAILED: (topic_name) => `Failed to Send Notification for this: ${topic_name} topic`,
INVALID_EMAIL: 'Invalid Email ID or Request Format',
EMAIL_NOTIFICATION_FAILED: 'Failed to Send Email Notification for',
INVALID_MOBILE_NUMBER: 'invalid Mobile Number',
SMS_NOTIFICATION_FAILED: 'Failed to Send SMS Notification',
ALREADY_EXIST_KEY_FOR_CONTEXT: 'Already Exist key with this context',
ALREADY_EXIST_KEY_FOR_CONTEXT_ENTER_ANOTHER: 'Key already exist for this context. Please enter another key',
NOT_EMPTY_SUBJECT_OR_BODY: 'Subject and body cannot be empty.'
}
9 changes: 2 additions & 7 deletions src/common/utils/response-interface.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { IsOptional } from "class-validator";

// structure for server responses
export interface ServerResponse {
// api id
Expand All @@ -21,14 +19,11 @@ export interface ServerResponse {
ver: string;

headers?: any;

response: any;
}

export interface Params {
resmsgid: string;
err?: any;
error?: string;
status: string;
errmsg?: any;
successmessage?: string;
errmsg?: string;
}
27 changes: 11 additions & 16 deletions src/common/utils/response.ts
Original file line number Diff line number Diff line change
@@ -1,62 +1,57 @@
import { v4 } from 'uuid';
import { Params } from './response-interface';
import { Response } from 'express';
import { ServerResponse, Params } from './response-interface';

export default class APIResponse {
public static success<Type>(
response: Response,
id: string,
result: Type,
statusCode: number,
successmessage: string
) {
statusCode: string,
): ServerResponse {
try {
const params: Params = {
resmsgid: v4(),
status: 'successful',
err: null,
error: null,
errmsg: null,
successmessage: successmessage
};

const resObj = {
const resObj: ServerResponse = {
id,
ver: '1.0',
ts: new Date().toISOString(),
params,
responseCode: statusCode,
result,
};
return response.status(Number(statusCode)).json(resObj);
return resObj;
} catch (e) {
return e;
}
}

public static error(
response: Response,
id: string,
errmsg: string,
error: string,
statusCode: number,
) {
statusCode: string,
): ServerResponse {
try {
const params: Params = {
resmsgid: v4(),
status: 'failed',
err: error,
errmsg: errmsg,
error,
};

const resObj = {
const resObj: ServerResponse = {
id,
ver: '1.0',
ts: new Date().toISOString(),
params,
responseCode: statusCode,
result: {},
};
return response.status(Number(statusCode)).json(resObj);
return resObj;
} catch (e) {
return e;
}
Expand Down
Loading

0 comments on commit 3a23a37

Please sign in to comment.