Skip to content

Commit

Permalink
feat: adding new message event
Browse files Browse the repository at this point in the history
  • Loading branch information
libterty committed Mar 20, 2021
1 parent 7b1f701 commit c32edde
Show file tree
Hide file tree
Showing 15 changed files with 117 additions and 169 deletions.
8 changes: 7 additions & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
{
"printWidth": 1000,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "all"
"trailingComma": "all",
"bracketSpacing": true,
"arrowParens": "always"
}
18 changes: 3 additions & 15 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import {
MiddlewareConsumer,
Module,
NestModule,
RequestMethod,
} from '@nestjs/common';
import { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';
import { GatewayModule } from './gateways/gateway.module';
import { RateMiddleware } from 'middlewares/rate-limit';
import { ChatSocketGateway } from './sockets/chat.gateway';
Expand All @@ -13,17 +8,10 @@ import { ChatMessageRoutingService } from './handlers/chat.handler';

@Module({
imports: [GatewayModule],
providers: [
ChatSocketGateway,
ChatSocketService,
ChatConsumerService,
ChatMessageRoutingService,
],
providers: [ChatSocketGateway, ChatSocketService, ChatConsumerService, ChatMessageRoutingService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(RateMiddleware)
.forRoutes({ path: '*', method: RequestMethod.ALL });
consumer.apply(RateMiddleware).forRoutes({ path: '*', method: RequestMethod.ALL });
}
}
10 changes: 4 additions & 6 deletions src/consumers/chat.consumer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ export class ChatConsumerService {
},
);

constructor(
private readonly chatMessageRoutingService: ChatMessageRoutingService,
) {
constructor(private readonly chatMessageRoutingService: ChatMessageRoutingService) {
this.init();
}

Expand All @@ -34,14 +32,14 @@ export class ChatConsumerService {
this.consumer.consume(config.EVENT_STORE_SETTINGS.poolOptions.max);
}, 1000);
})
.on('data', data => {
.on('data', (data) => {
this.chatMessageRoutingService.register(data);
this.consumer.commit();
})
.on('event.error', err => {
.on('event.error', (err) => {
this.logger.error(err.message, '', 'Event_Error');
})
.on('rebalance.error', err => {
.on('rebalance.error', (err) => {
this.logger.error(err.message, '', 'Reblanace_Error');
});

Expand Down
29 changes: 5 additions & 24 deletions src/gateways/gateway.controller.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,4 @@
import {
Controller,
Request,
Get,
UsePipes,
ValidationPipe,
HttpException,
Post,
Put,
Delete,
UseInterceptors,
} from '@nestjs/common';
import { Controller, Request, Get, UsePipes, ValidationPipe, HttpException, Post, Put, Delete, UseInterceptors } from '@nestjs/common';
import { GatewayService } from './gateway.service';
import * as Express from 'express';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
Expand All @@ -21,9 +10,7 @@ export class GatewayController {

@Get()
@UsePipes(ValidationPipe)
getRequest(
@Request() req: Express.Request,
): Promise<HttpException | unknown> {
getRequest(@Request() req: Express.Request): Promise<HttpException | unknown> {
return this.gatewayService.getRequest(req);
}

Expand All @@ -34,25 +21,19 @@ export class GatewayController {
fileFilter: isImageFilter,
}),
)
postRequest(
@Request() req: Express.Request,
): Promise<HttpException | unknown> {
postRequest(@Request() req: Express.Request): Promise<HttpException | unknown> {
return this.gatewayService.postRequest(req);
}

@Put()
@UsePipes(ValidationPipe)
putRequest(
@Request() req: Express.Request,
): Promise<HttpException | unknown> {
putRequest(@Request() req: Express.Request): Promise<HttpException | unknown> {
return this.gatewayService.putRequest(req);
}

@Delete()
@UsePipes(ValidationPipe)
delRequest(
@Request() req: Express.Request,
): Promise<HttpException | unknown> {
delRequest(@Request() req: Express.Request): Promise<HttpException | unknown> {
return this.gatewayService.delRequest(req);
}
}
36 changes: 8 additions & 28 deletions src/gateways/gateway.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,7 @@ export class GatewayService {
);

// get current server
const service: IGateway.IServerConf | undefined = config.MS_SETTINGS.find(
setting => setting.name === serviceName,
);
const service: IGateway.IServerConf | undefined = config.MS_SETTINGS.find((setting) => setting.name === serviceName);

// check if service is exist or not
if (typeof service !== 'object')
Expand All @@ -87,10 +85,7 @@ export class GatewayService {
);

// replace req.url to endpoint
const endpoint: string = req.url.replace(
`/${config.PREFIX}${config.API_EXPLORER_PATH}`,
'',
);
const endpoint: string = req.url.replace(`/${config.PREFIX}${config.API_EXPLORER_PATH}`, '');

try {
return await APIRequestFactory.createRequest('standard').makeRequest({
Expand Down Expand Up @@ -133,9 +128,7 @@ export class GatewayService {
);

// get current server
const service: IGateway.IServerConf | undefined = config.MS_SETTINGS.find(
setting => setting.name === serviceName,
);
const service: IGateway.IServerConf | undefined = config.MS_SETTINGS.find((setting) => setting.name === serviceName);

// check if service is exist or not
if (typeof service !== 'object')
Expand All @@ -148,10 +141,7 @@ export class GatewayService {
);

// replace req.url to endpoint
const endpoint: string = req.url.replace(
`/${config.PREFIX}${config.API_EXPLORER_PATH}`,
'',
);
const endpoint: string = req.url.replace(`/${config.PREFIX}${config.API_EXPLORER_PATH}`, '');

try {
if (req.headers['content-type'].includes('multipart/form-data')) {
Expand Down Expand Up @@ -217,9 +207,7 @@ export class GatewayService {
);

// get current server
const service: IGateway.IServerConf | undefined = config.MS_SETTINGS.find(
setting => setting.name === serviceName,
);
const service: IGateway.IServerConf | undefined = config.MS_SETTINGS.find((setting) => setting.name === serviceName);

// check if service is exist or not
if (typeof service !== 'object')
Expand All @@ -232,10 +220,7 @@ export class GatewayService {
);

// replace req.url to endpoint
const endpoint: string = req.url.replace(
`/${config.PREFIX}${config.API_EXPLORER_PATH}`,
'',
);
const endpoint: string = req.url.replace(`/${config.PREFIX}${config.API_EXPLORER_PATH}`, '');

try {
return await APIRequestFactory.createRequest('standard').makeRequest({
Expand Down Expand Up @@ -286,9 +271,7 @@ export class GatewayService {
);

// get current server
const service: IGateway.IServerConf | undefined = config.MS_SETTINGS.find(
setting => setting.name === serviceName,
);
const service: IGateway.IServerConf | undefined = config.MS_SETTINGS.find((setting) => setting.name === serviceName);

// check if service is exist or not
if (typeof service !== 'object')
Expand All @@ -301,10 +284,7 @@ export class GatewayService {
);

// replace req.url to endpoint
const endpoint: string = req.url.replace(
`/${config.PREFIX}${config.API_EXPLORER_PATH}`,
'',
);
const endpoint: string = req.url.replace(`/${config.PREFIX}${config.API_EXPLORER_PATH}`, '');

try {
return await APIRequestFactory.createRequest('standard').makeRequest({
Expand Down
42 changes: 20 additions & 22 deletions src/handlers/chat.handler.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import {
Injectable,
InternalServerErrorException,
Logger,
} from '@nestjs/common';
import { Injectable, InternalServerErrorException, Logger } from '@nestjs/common';
import Kafka from 'node-rdkafka';
import { ChatSocketService } from '../sockets/chat.service';
import * as EChatRoom from '../sockets/enums';
Expand All @@ -14,28 +10,30 @@ export class ChatMessageRoutingService {

constructor(private readonly chatSocketService: ChatSocketService) {}

public register(kafkaMessage: Kafka.Message) {
if (!kafkaMessage)
throw new InternalServerErrorException('Non message is being proecssed');
const event: IChatRoom.IAggregateResponse<
EChatRoom.EChatRoomSocketEvent,
IChatRoom.IEventData
> = JSON.parse(kafkaMessage.value.toString());
/**
* @description Register topic event
* @public
* @param {Kafka.Message} kafkaMessage
* @returns {void}
*/
public register(kafkaMessage: Kafka.Message): void {
if (!kafkaMessage) throw new InternalServerErrorException('Non message is being proecssed');
const event: IChatRoom.IAggregateResponse<EChatRoom.EChatRoomSocketEvent, IChatRoom.IEventData> = JSON.parse(kafkaMessage.value.toString());
return this.handler(event);
}

protected handler(
event: IChatRoom.IAggregateResponse<
EChatRoom.EChatRoomSocketEvent,
IChatRoom.IEventData
>,
) {
/**
* @description Handle message delivery
* @private
* @param {IChatRoom.IAggregateResponse<EChatRoom.EChatRoomSocketEvent, IChatRoom.IEventData>} event
* @returns {void}
*/
private handler(event: IChatRoom.IAggregateResponse<EChatRoom.EChatRoomSocketEvent, IChatRoom.IEventData>) {
switch (event.type) {
case EChatRoom.EChatRoomSocketEvent.CREATECHATROOM:
return this.chatSocketService.sendNewChatRoom(
event.type,
event.data as IChatRoom.IChatRoomEntity,
);
return this.chatSocketService.sendNewChatRoom(event.type, event.data as IChatRoom.IChatRoomEntity);
case EChatRoom.EChatRoomSocketEvent.NEWCHATMESSAGE:
return this.chatSocketService.sendNewChatMessage(event.type, event.data as IChatRoom.IChatEntity);
}
}
}
4 changes: 2 additions & 2 deletions src/libs/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ export class StandardRequest {
return new Promise((resolve, reject) => {
httpRequest
.default(options)
.then(res => resolve(res))
.catch(err => reject(err));
.then((res) => resolve(res))
.catch((err) => reject(err));
});
}
}
15 changes: 3 additions & 12 deletions src/libs/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,7 @@ import * as IGateway from '../gateways/interfaces';
* @returns {void}
*/
export function memInfo(memName: string): void {
Logger.log(
`Function ${memName} used memory: ${Math.round(
(process.memoryUsage().heapUsed / 1024 / 1024) * 100,
) / 100} MB`,
'Memory-Info',
true,
);
Logger.log(`Function ${memName} used memory: ${Math.round((process.memoryUsage().heapUsed / 1024 / 1024) * 100) / 100} MB`, 'Memory-Info', true);
}

/**
Expand Down Expand Up @@ -64,8 +58,7 @@ export function isEmptyObj(obj: { [key: string]: any }): boolean {
}

export function isImageFilter(req, file, cb) {
if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/))
return cb(new Error('Not Allowed File'), false);
if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) return cb(new Error('Not Allowed File'), false);
cb(null, true);
}

Expand All @@ -79,9 +72,7 @@ export function editFileName(req, file, cb) {
cb(null, `${name}-${randomName}${fileExtName}`);
}

export function formatErrorMessage(
errorMsg: string,
): IGateway.IErrorStruct | null {
export function formatErrorMessage(errorMsg: string): IGateway.IErrorStruct | null {
const errorMsgStr: string = errorMsg.split('-')[1];
if (!errorMsgStr) return null;
errorMsgStr.replace(/\/\n/gi, '');
Expand Down
6 changes: 1 addition & 5 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,6 @@ async function bootstrap() {
});
app.startAllMicroservices();
await app.listen(config.PORT);
Logger.log(
`Server start on ${config.HOST}:${config.PORT}`,
'Bootstrap',
true,
);
Logger.log(`Server start on ${config.HOST}:${config.PORT}`, 'Bootstrap', true);
}
bootstrap();
15 changes: 2 additions & 13 deletions src/middlewares/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
import {
HttpException,
HttpStatus,
Injectable,
Logger,
NestMiddleware,
UnauthorizedException,
} from '@nestjs/common';
import { HttpException, HttpStatus, Injectable, Logger, NestMiddleware, UnauthorizedException } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { config } from '../../config';
import { APIRequestFactory } from '../libs/request-factory';
Expand All @@ -21,11 +14,7 @@ export class AuthService implements NestMiddleware {
* @param {NextFunction} next
* @returns {Promise<void | Response>}
*/
public async use(
req: Request,
res: Response,
next: NextFunction,
): Promise<void | Response> {
public async use(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
// check if routes is exception or not
if (this.exceptRoutes(req.baseUrl)) return next();
// check token
Expand Down
Loading

0 comments on commit c32edde

Please sign in to comment.