Skip to content

Commit

Permalink
feat : createdby amd updated by from query
Browse files Browse the repository at this point in the history
  • Loading branch information
Xitija committed Nov 6, 2024
1 parent e2970ea commit d050263
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 34 deletions.
15 changes: 11 additions & 4 deletions src/common/filters/exception.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ 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';
Expand Down Expand Up @@ -38,9 +38,10 @@ export class AllExceptionsFilter implements ExceptionFilter {
statusCode.toString(),
);
LoggerWinston.error(
`Error occurred on API: ${request.url}`,
ERROR_MESSAGES.API_REQ_FAILURE(request.url),
errorMessage,
request.method,
typeof request.query === 'string' ? request.query : '',
);

return response.status(statusCode).json(errorResponse);
Expand All @@ -53,10 +54,10 @@ export class AllExceptionsFilter implements ExceptionFilter {
statusCode.toString(),
);
LoggerWinston.error(
`Database Query Failed on API: ${request.url}`,
ERROR_MESSAGES.DB_QUERY_FAILURE(request.url),
(exception as QueryFailedError).message,
request.method,
// user
typeof request.query === 'string' ? request.query : '',
);
return response.status(statusCode).json(errorResponse);
}
Expand All @@ -69,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);
}
}
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
21 changes: 18 additions & 3 deletions src/modules/event/event.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
Param,
UsePipes,
Res,
Req,
ValidationPipe,
BadRequestException,
UseFilters,
Expand All @@ -21,8 +22,9 @@ import {
ApiOkResponse,
ApiResponse,
ApiTags,
ApiQuery,
} from '@nestjs/swagger';
import { Response } from 'express';
import { Request, Response } from 'express';
import { SearchFilterDto } from './dto/search-event.dto';
import {
DateValidationPipe,
Expand All @@ -38,6 +40,7 @@ import {
ERROR_MESSAGES,
SUCCESS_MESSAGES,
} from 'src/common/utils/constants.util';
import { checkValidUserId } from 'src/common/utils/functions.util';

@Controller('event/v1')
@ApiTags('Create Event')
Expand All @@ -50,6 +53,7 @@ export class EventController {
@UseFilters(new AllExceptionsFilter(API_ID.CREATE_EVENT))
@Post('/create')
@ApiBody({ type: CreateEventDto })
@ApiQuery({ name: 'userid', required: true })
@UsePipes(
new ValidationPipe({ transform: true }),
new DateValidationPipe(),
Expand All @@ -67,13 +71,18 @@ export class EventController {
async create(
@Body() createEventDto: CreateEventDto,
@Res() response: Response,
@Req() request: Request,
) {
const userId: string = checkValidUserId(request.query.userid);
createEventDto.createdBy = userId;
createEventDto.updatedBy = userId;
return this.eventService.createEvent(createEventDto, response);
}

@UseFilters(new AllExceptionsFilter(API_ID.GET_EVENTS))
@Post('/list')
@ApiBody({ type: SearchFilterDto })
@ApiQuery({ name: 'userid', required: true })
@ApiInternalServerErrorResponse({
description: ERROR_MESSAGES.INTERNAL_SERVER_ERROR,
})
Expand All @@ -86,15 +95,18 @@ export class EventController {
status: 200,
})
async findAll(
@Res() response: Response,
@Body() requestBody: SearchFilterDto,
@Res() response: Response,
@Req() request: Request,
) {
return this.eventService.getEvents(response, requestBody);
const userId: string = checkValidUserId(request.query.userid);
return this.eventService.getEvents(response, requestBody, userId);
}

@UseFilters(new AllExceptionsFilter(API_ID.UPDATE_EVENT))
@Patch('/:id')
@ApiBody({ type: UpdateEventDto })
@ApiQuery({ name: 'userid', required: true })
@ApiResponse({ status: 200, description: SUCCESS_MESSAGES.EVENT_UPDATED })
@ApiInternalServerErrorResponse({
description: ERROR_MESSAGES.INTERNAL_SERVER_ERROR,
Expand All @@ -104,10 +116,13 @@ export class EventController {
@Body(new ValidationPipe({ transform: true }))
updateEventDto: UpdateEventDto,
@Res() response: Response,
@Req() request: Request,
) {
if (!updateEventDto || Object.keys(updateEventDto).length === 0) {
throw new BadRequestException(ERROR_MESSAGES.INVALID_REQUEST_BODY);
}
const userId: string = checkValidUserId(request.query.userid);
updateEventDto.updatedBy = userId;
return this.eventService.updateEvent(id, updateEventDto, response);
}
}
20 changes: 14 additions & 6 deletions src/modules/event/event.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ import { Response } from 'express';
import APIResponse from 'src/common/utils/response';
import { AttendeesService } from '../attendees/attendees.service';
import { EventDetail } from './entities/eventDetail.entity';
import { API_ID, ERROR_MESSAGES } from 'src/common/utils/constants.util';
import {
API_ID,
ERROR_MESSAGES,
SUCCESS_MESSAGES,
} from 'src/common/utils/constants.util';
import { EventRepetition } from './entities/eventRepetition.entity';
import {
DaysOfWeek,
Expand Down Expand Up @@ -107,17 +111,17 @@ export class EventService {
}

LoggerWinston.log(
`Event created with ID: ${createdEvent.res.eventId}`,
SUCCESS_MESSAGES.EVENT_CREATED_LOG(createdEvent.res?.eventId),
apiId,
'user',
createEventDto.createdBy,
);

return response
.status(HttpStatus.CREATED)
.json(APIResponse.success(apiId, createdEvent.res, 'Created'));
}

async getEvents(response, requestBody) {
async getEvents(response, requestBody, userId: string) {
const apiId = API_ID.GET_EVENTS;
this.validateTimezone();

Expand Down Expand Up @@ -172,7 +176,7 @@ export class EventService {
if (finalResult.length === 0) {
throw new NotFoundException(ERROR_MESSAGES.EVENT_NOT_FOUND);
}
LoggerWinston.log(`Successfully fetched events`, apiId, 'info');
LoggerWinston.log(SUCCESS_MESSAGES.EVENTS_FETCHED_LOG, apiId, userId);
return response
.status(HttpStatus.OK)
.json(
Expand Down Expand Up @@ -320,7 +324,11 @@ export class EventService {
);
}

LoggerWinston.log(`Successfully updated events`, apiId, 'user');
LoggerWinston.log(
SUCCESS_MESSAGES.EVENT_UPDATED_LOG,
apiId,
updateBody.updatedBy,
);
return response
.status(HttpStatus.OK)
.json(APIResponse.success(apiId, result, 'OK'));
Expand Down

0 comments on commit d050263

Please sign in to comment.