Skip to content

Commit 03de7a3

Browse files
authored
Merge pull request #179 from AlvaroDavi5/develop
Develop
2 parents f337db5 + 355c164 commit 03de7a3

File tree

10 files changed

+3953
-3330
lines changed

10 files changed

+3953
-3330
lines changed

package-lock.json

Lines changed: 3906 additions & 3320 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"$schema": "https://json.schemastore.org/package.json",
33
"name": "node_backend_boilerplate",
4-
"version": "6.3.3",
4+
"version": "6.4.0",
55
"description": "Node.js Boilerplate for Back-End using TypeScript",
66
"license": "MIT",
77
"private": false,

scripts/seed.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import UsersModel from '@core/infra/database/models/Users.model';
55
import UserPreferencesModel from '@core/infra/database/models/UserPreferences.model';
66

77

8-
async function getConnection() {
8+
async function getConnection(): Promise<DataSource> {
99
const connection = new DataSource(dbConfig);
1010

1111
const isInitialized = await testConnection(connection, console);
@@ -29,7 +29,7 @@ function getRepositories(connection: DataSource) {
2929
};
3030
}
3131

32-
async function seedDatabase() {
32+
async function seedDatabase(): Promise<void> {
3333
const connection = await getConnection();
3434
const { userRepository, userPreferenceRepository } = getRepositories(connection);
3535

src/modules/app/user/api/controllers/User.controller.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
Get, Post, Put, Patch, Delete,
66
UseGuards, UseFilters, UseInterceptors,
77
} from '@nestjs/common';
8-
import { ApiOperation, ApiTags, ApiProduces, ApiConsumes, ApiOkResponse, ApiCreatedResponse, ApiNoContentResponse } from '@nestjs/swagger';
8+
import { ApiOperation, ApiTags, ApiParam, ApiProduces, ApiConsumes, ApiOkResponse, ApiCreatedResponse, ApiNoContentResponse } from '@nestjs/swagger';
99
import { ModuleRef } from '@nestjs/core';
1010
import Exceptions from '@core/errors/Exceptions';
1111
import UserEntity, { IViewUser } from '@domain/entities/User.entity';
@@ -157,6 +157,7 @@ export default class UserController implements OnModuleInit {
157157
deprecated: false,
158158
})
159159
@Get('/:userId')
160+
@ApiParam({ name: 'userId', required: true, example: 'f0805007-af7a-4845-9c72-4f9d3f855380' })
160161
@ApiOkResponse({ type: UserEntity })
161162
@ApiConsumes('application/json')
162163
@ApiProduces('application/json')
@@ -179,6 +180,7 @@ export default class UserController implements OnModuleInit {
179180
deprecated: false,
180181
})
181182
@Patch('/:userId')
183+
@ApiParam({ name: 'userId', required: true, example: 'f0805007-af7a-4845-9c72-4f9d3f855380' })
182184
@ApiOkResponse({ type: UserEntity })
183185
@ApiConsumes('application/json')
184186
@ApiProduces('application/json')
@@ -202,6 +204,7 @@ export default class UserController implements OnModuleInit {
202204
deprecated: false,
203205
})
204206
@Delete('/:userId')
207+
@ApiParam({ name: 'userId', required: true, example: 'f0805007-af7a-4845-9c72-4f9d3f855380' })
205208
@ApiNoContentResponse({})
206209
@ApiConsumes('application/json')
207210
@ApiProduces('application/json')

src/modules/core/infra/database/connection.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ export async function syncConnection(connection: DataSource, logger?: Logger | L
4343

4444
export const DATABASE_CONNECTION_PROVIDER = Symbol('DatabaseConnectionProvider');
4545

46-
const databaseConnectionProvider: Provider = {
46+
const DatabaseConnectionProvider: Provider = {
4747
provide: DATABASE_CONNECTION_PROVIDER,
4848
scope: Scope.DEFAULT,
4949

@@ -79,4 +79,4 @@ const databaseConnectionProvider: Provider = {
7979
durable: false,
8080
};
8181

82-
export default databaseConnectionProvider;
82+
export default DatabaseConnectionProvider;

src/modules/core/infra/database/db.config.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { DataSource, DataSourceOptions } from 'typeorm';
22
import envsConfig from '@core/configs/envs.config';
3+
import UsersModel from './models/Users.model';
4+
import UserPreferencesModel from './models/UserPreferences.model';
35

46

57
function getDialect(dialect: string): 'mysql' | 'postgres' | 'sqlite' | 'mssql' {
@@ -30,7 +32,10 @@ export const dbConfig: DataSourceOptions = {
3032
charset: db.charset,
3133
timezone: db.timezone,
3234
logging: app.showExternalLogs,
33-
entities: ['build/modules/core/infra/database/models/**/*.js'],
35+
entities: [
36+
UsersModel,
37+
UserPreferencesModel,
38+
],
3439
migrations: ['build/modules/core/infra/database/migrations/**/*.js'],
3540
subscribers: [],
3641
pool: {

src/modules/core/start/Lifecycle.service.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { ConfigsInterface } from '@core/configs/envs.config';
1616
import { EmitterEventsEnum } from '@domain/enums/events.enum';
1717
import WebSocketServer from '@events/websocket/server/WebSocket.server';
1818
import EventEmitterClient from '@events/emitter/EventEmitter.client';
19+
import EventsQueueConsumer from '@events/queue/consumers/EventsQueue.consumer';
1920
import { EnvironmentsEnum } from '@common/enums/environments.enum';
2021
import { ProcessExitStatusEnum } from '@common/enums/processEvents.enum';
2122

@@ -24,6 +25,7 @@ import { ProcessExitStatusEnum } from '@common/enums/processEvents.enum';
2425
export default class LifecycleService implements OnModuleInit, OnApplicationBootstrap, OnModuleDestroy, BeforeApplicationShutdown, OnApplicationShutdown {
2526
private readonly appConfigs: ConfigsInterface['application'];
2627
private eventEmitterClient!: EventEmitterClient;
28+
private eventsQueueConsumer!: EventsQueueConsumer;
2729

2830
constructor(
2931
private readonly moduleRef: ModuleRef,
@@ -45,6 +47,7 @@ export default class LifecycleService implements OnModuleInit, OnApplicationBoot
4547

4648
public onModuleInit(): void {
4749
this.eventEmitterClient = this.moduleRef.get(EventEmitterClient, { strict: false });
50+
this.eventsQueueConsumer = this.moduleRef.get(EventsQueueConsumer, { strict: false });
4851

4952
this.logger.debug('Builded host module');
5053
}
@@ -56,13 +59,14 @@ export default class LifecycleService implements OnModuleInit, OnApplicationBoot
5659
}
5760

5861
public onModuleDestroy(): void {
59-
this.logger.warn('Closing HTTP server, disconnecting websocket clients, stopping crons and destroying cloud integrations');
62+
this.logger.warn('Closing HTTP server, disconnecting websocket clients, stopping crons and consumers and destroying cloud integrations');
6063

6164
try {
6265
// NOTE - gracefull shutdown
6366
this.httpAdapterHost.httpAdapter.close();
6467
this.webSocketServer.disconnectAllSockets();
6568
this.webSocketServer.disconnect();
69+
this.eventsQueueConsumer.disable();
6670
this.syncCronJob.stopCron();
6771
this.cognitoClient.destroy();
6872
this.sqsClient.destroy();

src/modules/events/queue/consumers/AbstractConsumer.consumer.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ export default abstract class AbstractQueueConsumer {
2424
protected queueName: QueueNamesEnum;
2525
protected queueUrl: string;
2626
private errorsCount = 0;
27+
private disabled = false;
2728

2829
constructor(
2930
consumerName: string,
@@ -53,8 +54,26 @@ export default abstract class AbstractQueueConsumer {
5354
this.logger.debug(`Created ${this.consumerName} to consume ${this.queueName} queue`);
5455
}
5556

57+
public disable(): void {
58+
this.logger.warn(`Disabling consumer ${this.consumerName}`);
59+
this.disabled = true;
60+
}
61+
62+
public enable(): void {
63+
this.logger.info(`Enabling consumer ${this.consumerName}`);
64+
this.disabled = false;
65+
}
66+
5667
protected async handleMessage(message: Message): Promise<void> {
5768
this.logger.info(`New message received from ${this.queueName}`);
69+
70+
if (this.disabled) {
71+
throw this.exceptions.internal({
72+
message: `Consumer ${this.consumerName} is disabled`,
73+
details: `MessageId: ${message.MessageId}`,
74+
});
75+
}
76+
5877
const done = await this.messageHandler.execute(message);
5978
if (done)
6079
await this.deleteMessage(message);

src/modules/events/queue/consumers/EventsQueue.consumer.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ export default class EventsQueueConsumer extends AbstractQueueConsumer {
3939
@SqsMessageHandler(EVENTS_QUEUE_NAME, true)
4040
public async handleMessageBatch(messages: Message[]): Promise<void> {
4141
for (const message of messages) {
42-
this.handleMessage(message);
42+
await this.handleMessage(message);
4343
}
4444
}
4545

tests/integration/modules/core/start/Lifecycle.service.test.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import S3Client from '@core/infra/integration/aws/S3.client';
1212
import CognitoClient from '@core/infra/integration/aws/Cognito.client';
1313
import LoggerService from '@core/logging/Logger.service';
1414
import EventEmitterClient from '@events/emitter/EventEmitter.client';
15+
import EventsQueueConsumer from '@events/queue/consumers/EventsQueue.consumer';
1516
import WebSocketServer from '@events/websocket/server/WebSocket.server';
1617
import { configServiceMock } from '@dev/mocks/mockedModules';
1718
import { mockObservable } from 'tests/integration/support/mocks/mockObservable';
@@ -53,6 +54,9 @@ describe('Modules :: Core :: Start :: LifecycleService', () => {
5354
const awsClientMock = {
5455
destroy: jest.fn((...args: unknown[]): void => { args.forEach((arg) => console.log(arg)); }),
5556
};
57+
const eventsQueueConsumerMock = {
58+
disable: jest.fn((): void => { console.log('Disabled consumer'); }),
59+
};
5660

5761
// ? build test app
5862
beforeAll(async () => {
@@ -69,6 +73,7 @@ describe('Modules :: Core :: Start :: LifecycleService', () => {
6973
{ provide: SnsClient, useValue: awsClientMock },
7074
{ provide: S3Client, useValue: awsClientMock },
7175
{ provide: CognitoClient, useValue: awsClientMock },
76+
{ provide: EventsQueueConsumer, useValue: eventsQueueConsumerMock },
7277
LoggerService,
7378
EventEmitterClient,
7479
LifecycleService,
@@ -87,11 +92,12 @@ describe('Modules :: Core :: Start :: LifecycleService', () => {
8792

8893
expect(mockObservable.call).toHaveBeenCalledWith('Builded host module');
8994
expect(mockObservable.call).toHaveBeenCalledWith(
90-
'Closing HTTP server, disconnecting websocket clients, stopping crons and destroying cloud integrations'
95+
'Closing HTTP server, disconnecting websocket clients, stopping crons and consumers and destroying cloud integrations'
9196
);
9297
expect(httpAdapterHostMock.httpAdapter.close).toHaveBeenCalledTimes(1);
9398
expect(webSocketServerMock.disconnectAllSockets).toHaveBeenCalledTimes(1);
9499
expect(webSocketServerMock.disconnect).toHaveBeenCalledTimes(1);
100+
expect(eventsQueueConsumerMock.disable).toHaveBeenCalledTimes(1);
95101
expect(syncCronJobMock.stopCron).toHaveBeenCalledTimes(1);
96102
expect(mockObservable.call).toHaveBeenCalledWith('Closing cache and databases connections');
97103
expect(mongoClientMock.disconnect).toHaveBeenCalledTimes(1);

0 commit comments

Comments
 (0)