Skip to content

Commit

Permalink
Merge pull request #50 from Xitija/main2
Browse files Browse the repository at this point in the history
PS -2403 UserId from Query Params and logging
  • Loading branch information
snehal0904 authored Nov 8, 2024
2 parents b1bc654 + d050263 commit 99c4d02
Show file tree
Hide file tree
Showing 10 changed files with 237 additions and 101 deletions.
143 changes: 71 additions & 72 deletions .github/workflows/eks-pratham-deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ on:
push:
branches:
- main

env:
ECR_REPOSITORY: ${{ secrets.ECR_REPOSITORY }}
EKS_CLUSTER_NAME: ${{ secrets.EKS_CLUSTER_NAME }}
Expand All @@ -13,77 +12,77 @@ jobs:
name: Deployment
runs-on: ubuntu-latest
steps:
- name: Set short git commit SHA
id: commit
uses: prompt/actions-commit-hash@v2
- name: Check out code
uses: actions/checkout@v2
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{env.AWS_REGION}}
- name: Setup Node Env
uses: actions/setup-node@v3
with:
node-version: 21.1.0
- name: Copy .env file
env:
ENV_FILE_CONTENT: '${{ secrets.ENV_FILE_CONTENT }}"'
run: echo "$ENV_FILE_CONTENT" > manifest/configmap.yaml
- name: Show PWD and list content
run: |
echo "Current Working Directory: pwd"
pwd
ls -ltra
- name: Creating Dockerfile
env:
DOCKERFILE_FILE_CONTENT: ${{ secrets.DOCKERFILE_FILE_CONTENT }}
run: echo "$DOCKERFILE_FILE_CONTENT" > Dockerfile
- name: Show PWD and list content
run: |
- name: Set short git commit SHA
id: commit
uses: prompt/actions-commit-hash@v2
- name: Check out code
uses: actions/checkout@v2
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{env.AWS_REGION}}
- name: Setup Node Env
uses: actions/setup-node@v3
with:
node-version: 21.1.0
- name: Copy .env file
env:
ENV_FILE_CONTENT: '${{ secrets.ENV_FILE_CONTENT }}"'
run: echo "$ENV_FILE_CONTENT" > manifest/configmap.yaml
- name: Show PWD and list content
run: |
echo "Current Working Directory: pwd"
pwd
ls -ltra
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ env.AWS_REGION }}
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v1
- name: Build, tag, and push image to Amazon ECR
env:
ECR_REGISTRY: ${{ secrets.ECR_REPOSITORY }}
IMAGE_TAG: ${{ secrets.ECR_IMAGE }}
run: |
docker build -t ${{ secrets.ECR_REPOSITORY }}:${{ secrets.IMAGE_TAG }} .
docker push ${{ secrets.ECR_REPOSITORY }}:${{ secrets.IMAGE_TAG }}
- name: Update kube config
run: aws eks update-kubeconfig --name ${{ secrets.EKS_CLUSTER_NAME }} --region ${{ secrets.AWS_REGION_NAME }}
- name: Deploy to EKS
env:
ECR_REGISTRY: ${{ secrets.ECR_REPOSITORY }}
IMAGE_TAG: ${{ secrets.IMAGE_TAG }}
ECR_REPOSITORY: ${{ secrets.ECR_REPOSITORY }}
ECR_IMAGE: ${{ secrets.ECR_IMAGE }}
run: |
export ECR_REPOSITORY=${{ secrets.ECR_REPOSITORY }}
export IMAGE_TAG=${{ secrets.IMAGE_TAG }}
export ECR_IMAGE=${{ secrets.ECR_IMAGE }}
envsubst < manifest/event-service.yaml > manifest/event-service-updated.yaml
cat manifest/event-service-updated.yaml
rm -rf manifest/event-service.yaml
kubectl delete deployment eventmanagement
kubectl delete svc eventmanagement
kubectl delete cm event-service-config
kubectl apply -f manifest/event-service-updated.yaml
kubectl apply -f manifest/configmap.yaml
sleep 10
kubectl get pods
kubectl get services
kubectl get deployment
kubectl apply -f manifest/
- name: Creating Dockerfile
env:
DOCKERFILE_FILE_CONTENT: ${{ secrets.DOCKERFILE_FILE_CONTENT }}
run: echo "$DOCKERFILE_FILE_CONTENT" > Dockerfile
- name: Show PWD and list content
run: |
echo "Current Working Directory: pwd"
pwd
ls -ltra
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ env.AWS_REGION }}
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@v1
- name: Build, tag, and push image to Amazon ECR
env:
ECR_REGISTRY: ${{ secrets.ECR_REPOSITORY }}
IMAGE_TAG: ${{ secrets.ECR_IMAGE }}
run: |
docker build -t ${{ secrets.ECR_REPOSITORY }}:${{ secrets.IMAGE_TAG }} .
docker push ${{ secrets.ECR_REPOSITORY }}:${{ secrets.IMAGE_TAG }}
- name: Update kube config
run: aws eks update-kubeconfig --name ${{ secrets.EKS_CLUSTER_NAME }} --region ${{ secrets.AWS_REGION_NAME }}
- name: Deploy to EKS
env:
ECR_REGISTRY: ${{ secrets.ECR_REPOSITORY }}
IMAGE_TAG: ${{ secrets.IMAGE_TAG }}
ECR_REPOSITORY: ${{ secrets.ECR_REPOSITORY }}
ECR_IMAGE: ${{ secrets.ECR_IMAGE }}
run: |
export ECR_REPOSITORY=${{ secrets.ECR_REPOSITORY }}
export IMAGE_TAG=${{ secrets.IMAGE_TAG }}
export ECR_IMAGE=${{ secrets.ECR_IMAGE }}
envsubst < manifest/event-service.yaml > manifest/event-service-updated.yaml
cat manifest/event-service-updated.yaml
rm -rf manifest/event-service.yaml
kubectl delete deployment eventmanagement
kubectl delete svc eventmanagement
kubectl delete cm event-service-config
kubectl apply -f manifest/event-service-updated.yaml
kubectl apply -f manifest/configmap.yaml
sleep 10
kubectl get pods
kubectl get services
kubectl get deployment
kubectl apply -f manifest/
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"moment-timezone": "^0.5.45",
"nest-winston": "^1.9.7",
"pg": "^8.13.0",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1"
"rxjs": "^7.8.1",
"winston": "^3.16.0"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
Expand Down
25 changes: 23 additions & 2 deletions src/common/filters/exception.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import {
HttpStatus,
} from '@nestjs/common';
import { QueryFailedError } from 'typeorm';
import { Response } from 'express';
import { Request, Response } from 'express';
import APIResponse from '../utils/response';
import { ERROR_MESSAGES } from '../utils/constants.util';
import { LoggerWinston } from '../logger/logger.util';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
Expand All @@ -20,6 +21,8 @@ export class AllExceptionsFilter implements ExceptionFilter {
) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();

const status =
exception instanceof HttpException ? exception.getStatus() : 500;

Expand All @@ -34,6 +37,13 @@ export class AllExceptionsFilter implements ExceptionFilter {
ERROR_MESSAGES.BAD_REQUEST,
statusCode.toString(),
);
LoggerWinston.error(
ERROR_MESSAGES.API_REQ_FAILURE(request.url),
errorMessage,
request.method,
typeof request.query === 'string' ? request.query : '',
);

return response.status(statusCode).json(errorResponse);
} else if (exception instanceof QueryFailedError) {
const statusCode = HttpStatus.UNPROCESSABLE_ENTITY;
Expand All @@ -43,10 +53,15 @@ export class AllExceptionsFilter implements ExceptionFilter {
ERROR_MESSAGES.INTERNAL_SERVER_ERROR,
statusCode.toString(),
);
LoggerWinston.error(
ERROR_MESSAGES.DB_QUERY_FAILURE(request.url),
(exception as QueryFailedError).message,
request.method,
typeof request.query === 'string' ? request.query : '',
);
return response.status(statusCode).json(errorResponse);
}
const detailedErrorMessage = `${errorMessage}`;
console.log('detailedErrorMessage', detailedErrorMessage);
const errorResponse = APIResponse.error(
this.apiId,
detailedErrorMessage,
Expand All @@ -55,6 +70,12 @@ export class AllExceptionsFilter implements ExceptionFilter {
: ERROR_MESSAGES.INTERNAL_SERVER_ERROR,
status.toString(),
);
LoggerWinston.error(
ERROR_MESSAGES.API_FAILURE(request.url),
errorResponse.result,
request.method,
typeof request.query === 'string' ? request.query : '',
);
return response.status(status).json(errorResponse);
}
}
79 changes: 79 additions & 0 deletions src/common/logger/logger.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import * as winston from 'winston';

export class LoggerWinston {
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.File({
filename: 'error.log',
level: 'error',
}),
new winston.transports.File({ filename: 'combined.log' }),
],
});
}
return this.logger;
}
static log(message: string, context?: string, user?: string) {
this.getLogger().log({
level: 'info',
message: message,
context: context,
user: user,
timestamp: new Date().toISOString(),
});
}

static error(
message: string,
error?: string,
context?: string,
user?: string,
) {
this.getLogger().error({
level: '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(),
});
}
}
8 changes: 8 additions & 0 deletions src/common/utils/constants.util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@ export const ERROR_MESSAGES = {
END_CONDITION_BY_OCCURENCES:
'End condition by occurrences is not implemented yet',
EVENT_TYPE_CHANGE_NOT_SUPPORTED: 'Event type change not supported',
USERID_INVALID: 'Invalid UserId',
PROVIDE_ONE_USERID_IN_QUERY: 'Please provide only one userid in query',
API_REQ_FAILURE: (url: string) => `Error occurred on API Request: ${url}`,
DB_QUERY_FAILURE: (url: string) => `Database Query Failed on API: ${url}`,
API_FAILURE: (url: string) => `API Failure: ${url}`,
};

export const SUCCESS_MESSAGES = {
Expand All @@ -102,6 +107,9 @@ export const SUCCESS_MESSAGES = {
'Event attendee history item updated successfully',
EVENT_ATTENDEE_HISTORY_ITEM_DELETED:
'Event attendee history item deleted successfully',
EVENT_CREATED_LOG: (url: string) => `Event created with ID: ${url}`,
EVENTS_FETCHED_LOG: 'Successfully fetched events',
EVENT_UPDATED_LOG: 'Successfully updated events',
};

export const API_ID = {
Expand Down
14 changes: 14 additions & 0 deletions src/common/utils/functions.util.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { BadRequestException } from '@nestjs/common';
import { isUUID } from 'class-validator';
import { ERROR_MESSAGES } from './constants.util';

export const compareArrays = (a: number[], b: number[]): boolean => {
if (a.length !== b.length) {
return false;
Expand All @@ -22,3 +26,13 @@ export const getNextDay = (currentDate: Date): Date => {

return nextDay;
};

export const checkValidUserId = (userId: any): string => {
if (typeof userId !== 'string') {
throw new BadRequestException(ERROR_MESSAGES.PROVIDE_ONE_USERID_IN_QUERY);
}
if (!userId || !isUUID(userId)) {
throw new BadRequestException(ERROR_MESSAGES.USERID_INVALID);
}
return userId;
};
10 changes: 0 additions & 10 deletions src/modules/event/dto/create-event.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,18 +347,8 @@ export class CreateEventDto {
@IsNotEmpty()
status: string;

@ApiProperty({
type: String,
description: 'createdBy',
example: 'eff008a8-2573-466d-b877-fddf6a4fc13e',
})
createdBy: string;

@ApiProperty({
type: String,
description: 'updatedBy',
example: 'eff008a8-2573-466d-b877-fddf6a4fc13e',
})
updatedBy: string;

@ApiProperty({
Expand Down
11 changes: 0 additions & 11 deletions src/modules/event/dto/update-event.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,17 +187,6 @@ export class UpdateEventDto {
@IsIn(['Zoom', 'GoogleMeet'])
onlineProvider: string;

// @IsString()
// @IsOptional()
// createdBy: string;

@ApiProperty({
type: String,
description: 'updatedBy',
example: 'eff008a8-2573-466d-b877-fddf6a4fc13e',
})
@IsString()
// @IsOptional()
updatedBy: string;

@IsOptional()
Expand Down
Loading

0 comments on commit 99c4d02

Please sign in to comment.