mirror of
https://gitlab.com/mobicoop/v3/service/ad.git
synced 2026-01-03 08:22:41 +00:00
install dependencies, create basic models
This commit is contained in:
@@ -1,7 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { ConfigurationModule } from './modules/configuration/configuration.module';
|
||||
// import { HealthModule } from './modules/health/health.module';
|
||||
import { AdModule } from './modules/ad/ad.module';
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true }),
|
||||
ConfigurationModule,
|
||||
// HealthModule,
|
||||
AdModule,
|
||||
],
|
||||
controllers: [],
|
||||
providers: [],
|
||||
})
|
||||
|
||||
22
src/main.ts
22
src/main.ts
@@ -1,8 +1,28 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
|
||||
import { join } from 'path';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
await app.listen(3000);
|
||||
app.connectMicroservice<MicroserviceOptions>({
|
||||
transport: Transport.TCP,
|
||||
});
|
||||
app.connectMicroservice<MicroserviceOptions>({
|
||||
transport: Transport.GRPC,
|
||||
options: {
|
||||
// package: ['ad', 'health'],
|
||||
package: ['health'],
|
||||
protoPath: [
|
||||
// join(__dirname, 'modules/ad/adapters/primaries/ad.proto'),
|
||||
join(__dirname, 'modules/health/adapters/primaries/health.proto'),
|
||||
],
|
||||
url: process.env.SERVICE_URL + ':' + process.env.SERVICE_PORT,
|
||||
loader: { keepCase: true },
|
||||
},
|
||||
});
|
||||
|
||||
await app.startAllMicroservices();
|
||||
await app.listen(process.env.HEALTH_SERVICE_PORT);
|
||||
}
|
||||
bootstrap();
|
||||
|
||||
8
src/modules/ad/ad.module.ts
Normal file
8
src/modules/ad/ad.module.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
controllers: [],
|
||||
providers: [],
|
||||
})
|
||||
export class AdModule {}
|
||||
8
src/modules/ad/adapters/secondaries/ads.repository.ts
Normal file
8
src/modules/ad/adapters/secondaries/ads.repository.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AdRepository } from '../../../database/src/domain/ad-repository';
|
||||
import { Ad } from '../../domain/entities/ad';
|
||||
|
||||
@Injectable()
|
||||
export class AdsRepository extends AdRepository<Ad> {
|
||||
protected _model = 'ad';
|
||||
}
|
||||
6
src/modules/ad/domain/entities/ad.ts
Normal file
6
src/modules/ad/domain/entities/ad.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { AutoMap } from '@automapper/classes';
|
||||
|
||||
export class Ad {
|
||||
@AutoMap()
|
||||
uuid: string;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { RabbitSubscribe } from '@golevelup/nestjs-rabbitmq';
|
||||
import { Controller } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { CommandBus } from '@nestjs/cqrs';
|
||||
import { DeleteConfigurationCommand } from '../../commands/delete-configuration.command';
|
||||
import { SetConfigurationCommand } from '../../commands/set-configuration.command';
|
||||
import { DeleteConfigurationRequest } from '../../domain/dtos/delete-configuration.request';
|
||||
import { SetConfigurationRequest } from '../../domain/dtos/set-configuration.request';
|
||||
import { Configuration } from '../../domain/entities/configuration';
|
||||
|
||||
@Controller()
|
||||
export class ConfigurationMessagerController {
|
||||
constructor(
|
||||
private readonly _commandBus: CommandBus,
|
||||
private readonly _configService: ConfigService,
|
||||
) {}
|
||||
|
||||
@RabbitSubscribe({
|
||||
name: 'setConfiguration',
|
||||
})
|
||||
public async setConfigurationHandler(message: string) {
|
||||
const configuration: Configuration = JSON.parse(message);
|
||||
if (
|
||||
configuration.domain ==
|
||||
this._configService.get<string>('SERVICE_CONFIGURATION_DOMAIN')
|
||||
) {
|
||||
const setConfigurationRequest: SetConfigurationRequest =
|
||||
new SetConfigurationRequest();
|
||||
setConfigurationRequest.domain = configuration.domain;
|
||||
setConfigurationRequest.key = configuration.key;
|
||||
setConfigurationRequest.value = configuration.value;
|
||||
await this._commandBus.execute(
|
||||
new SetConfigurationCommand(setConfigurationRequest),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@RabbitSubscribe({
|
||||
name: 'deleteConfiguration',
|
||||
})
|
||||
public async configurationDeletedHandler(message: string) {
|
||||
const deletedConfiguration: Configuration = JSON.parse(message);
|
||||
if (
|
||||
deletedConfiguration.domain ==
|
||||
this._configService.get<string>('SERVICE_CONFIGURATION_DOMAIN')
|
||||
) {
|
||||
const deleteConfigurationRequest = new DeleteConfigurationRequest();
|
||||
deleteConfigurationRequest.domain = deletedConfiguration.domain;
|
||||
deleteConfigurationRequest.key = deletedConfiguration.key;
|
||||
await this._commandBus.execute(
|
||||
new DeleteConfigurationCommand(deleteConfigurationRequest),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@RabbitSubscribe({
|
||||
name: 'propagateConfiguration',
|
||||
})
|
||||
public async propagateConfigurationsHandler(message: string) {
|
||||
const configurations: Array<Configuration> = JSON.parse(message);
|
||||
configurations.forEach(async (configuration) => {
|
||||
if (
|
||||
configuration.domain ==
|
||||
this._configService.get<string>('SERVICE_CONFIGURATION_DOMAIN')
|
||||
) {
|
||||
const setConfigurationRequest: SetConfigurationRequest =
|
||||
new SetConfigurationRequest();
|
||||
setConfigurationRequest.domain = configuration.domain;
|
||||
setConfigurationRequest.key = configuration.key;
|
||||
setConfigurationRequest.value = configuration.value;
|
||||
await this._commandBus.execute(
|
||||
new SetConfigurationCommand(setConfigurationRequest),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { InjectRedis } from '@liaoliaots/nestjs-redis';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Redis } from 'ioredis';
|
||||
import { IConfigurationRepository } from '../../domain/interfaces/configuration.repository';
|
||||
|
||||
@Injectable()
|
||||
export class RedisConfigurationRepository extends IConfigurationRepository {
|
||||
constructor(@InjectRedis() private readonly _redis: Redis) {
|
||||
super();
|
||||
}
|
||||
|
||||
async get(key: string): Promise<string> {
|
||||
return await this._redis.get(key);
|
||||
}
|
||||
|
||||
async set(key: string, value: string) {
|
||||
await this._redis.set(key, value);
|
||||
}
|
||||
|
||||
async del(key: string) {
|
||||
await this._redis.del(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { DeleteConfigurationRequest } from '../domain/dtos/delete-configuration.request';
|
||||
|
||||
export class DeleteConfigurationCommand {
|
||||
readonly deleteConfigurationRequest: DeleteConfigurationRequest;
|
||||
|
||||
constructor(deleteConfigurationRequest: DeleteConfigurationRequest) {
|
||||
this.deleteConfigurationRequest = deleteConfigurationRequest;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { SetConfigurationRequest } from '../domain/dtos/set-configuration.request';
|
||||
|
||||
export class SetConfigurationCommand {
|
||||
readonly setConfigurationRequest: SetConfigurationRequest;
|
||||
|
||||
constructor(setConfigurationRequest: SetConfigurationRequest) {
|
||||
this.setConfigurationRequest = setConfigurationRequest;
|
||||
}
|
||||
}
|
||||
68
src/modules/configuration/configuration.module.ts
Normal file
68
src/modules/configuration/configuration.module.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { RabbitMQConfig, RabbitMQModule } from '@golevelup/nestjs-rabbitmq';
|
||||
import { RedisModule, RedisModuleOptions } from '@liaoliaots/nestjs-redis';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { CqrsModule } from '@nestjs/cqrs';
|
||||
import { ConfigurationMessagerController } from './adapters/primaries/configuration-messager.controller';
|
||||
import { RedisConfigurationRepository } from './adapters/secondaries/redis-configuration.repository';
|
||||
import { DeleteConfigurationUseCase } from './domain/usecases/delete-configuration.usecase';
|
||||
import { GetConfigurationUseCase } from './domain/usecases/get-configuration.usecase';
|
||||
import { SetConfigurationUseCase } from './domain/usecases/set-configuration.usecase';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
CqrsModule,
|
||||
RedisModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: async (
|
||||
configService: ConfigService,
|
||||
): Promise<RedisModuleOptions> => ({
|
||||
config: {
|
||||
host: configService.get<string>('REDIS_HOST'),
|
||||
port: configService.get<number>('REDIS_PORT'),
|
||||
password: configService.get<string>('REDIS_PASSWORD'),
|
||||
},
|
||||
}),
|
||||
}),
|
||||
RabbitMQModule.forRootAsync(RabbitMQModule, {
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: async (
|
||||
configService: ConfigService,
|
||||
): Promise<RabbitMQConfig> => ({
|
||||
exchanges: [
|
||||
{
|
||||
name: configService.get<string>('RMQ_EXCHANGE'),
|
||||
type: 'topic',
|
||||
},
|
||||
],
|
||||
handlers: {
|
||||
setConfiguration: {
|
||||
exchange: configService.get<string>('RMQ_EXCHANGE'),
|
||||
routingKey: ['configuration.create', 'configuration.update'],
|
||||
},
|
||||
deleteConfiguration: {
|
||||
exchange: configService.get<string>('RMQ_EXCHANGE'),
|
||||
routingKey: 'configuration.delete',
|
||||
},
|
||||
propagateConfiguration: {
|
||||
exchange: configService.get<string>('RMQ_EXCHANGE'),
|
||||
routingKey: 'configuration.propagate',
|
||||
},
|
||||
},
|
||||
uri: configService.get<string>('RMQ_URI'),
|
||||
connectionInitOptions: { wait: false },
|
||||
enableControllerDiscovery: true,
|
||||
}),
|
||||
}),
|
||||
],
|
||||
controllers: [ConfigurationMessagerController],
|
||||
providers: [
|
||||
GetConfigurationUseCase,
|
||||
SetConfigurationUseCase,
|
||||
DeleteConfigurationUseCase,
|
||||
RedisConfigurationRepository,
|
||||
],
|
||||
})
|
||||
export class ConfigurationModule {}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class DeleteConfigurationRequest {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
domain: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
key: string;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class SetConfigurationRequest {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
domain: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
key: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
value: string;
|
||||
}
|
||||
12
src/modules/configuration/domain/entities/configuration.ts
Normal file
12
src/modules/configuration/domain/entities/configuration.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { AutoMap } from '@automapper/classes';
|
||||
|
||||
export class Configuration {
|
||||
@AutoMap()
|
||||
domain: string;
|
||||
|
||||
@AutoMap()
|
||||
key: string;
|
||||
|
||||
@AutoMap()
|
||||
value: string;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export abstract class IConfigurationRepository {
|
||||
abstract get(key: string): Promise<string>;
|
||||
abstract set(key: string, value: string): void;
|
||||
abstract del(key: string): void;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { CommandHandler } from '@nestjs/cqrs';
|
||||
import { RedisConfigurationRepository } from '../../adapters/secondaries/redis-configuration.repository';
|
||||
import { DeleteConfigurationCommand } from '../../commands/delete-configuration.command';
|
||||
|
||||
@CommandHandler(DeleteConfigurationCommand)
|
||||
export class DeleteConfigurationUseCase {
|
||||
constructor(private _configurationRepository: RedisConfigurationRepository) {}
|
||||
|
||||
async execute(deleteConfigurationCommand: DeleteConfigurationCommand) {
|
||||
await this._configurationRepository.del(
|
||||
deleteConfigurationCommand.deleteConfigurationRequest.domain +
|
||||
':' +
|
||||
deleteConfigurationCommand.deleteConfigurationRequest.key,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { QueryHandler } from '@nestjs/cqrs';
|
||||
import { RedisConfigurationRepository } from '../../adapters/secondaries/redis-configuration.repository';
|
||||
import { GetConfigurationQuery } from '../../queries/get-configuration.query';
|
||||
|
||||
@QueryHandler(GetConfigurationQuery)
|
||||
export class GetConfigurationUseCase {
|
||||
constructor(private _configurationRepository: RedisConfigurationRepository) {}
|
||||
|
||||
async execute(getConfigurationQuery: GetConfigurationQuery): Promise<string> {
|
||||
return this._configurationRepository.get(
|
||||
getConfigurationQuery.domain + ':' + getConfigurationQuery.key,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { CommandHandler } from '@nestjs/cqrs';
|
||||
import { RedisConfigurationRepository } from '../../adapters/secondaries/redis-configuration.repository';
|
||||
import { SetConfigurationCommand } from '../../commands/set-configuration.command';
|
||||
|
||||
@CommandHandler(SetConfigurationCommand)
|
||||
export class SetConfigurationUseCase {
|
||||
constructor(private _configurationRepository: RedisConfigurationRepository) {}
|
||||
|
||||
async execute(setConfigurationCommand: SetConfigurationCommand) {
|
||||
await this._configurationRepository.set(
|
||||
setConfigurationCommand.setConfigurationRequest.domain +
|
||||
':' +
|
||||
setConfigurationCommand.setConfigurationRequest.key,
|
||||
setConfigurationCommand.setConfigurationRequest.value,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export class GetConfigurationQuery {
|
||||
readonly domain: string;
|
||||
readonly key: string;
|
||||
|
||||
constructor(domain: string, key: string) {
|
||||
this.domain = domain;
|
||||
this.key = key;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { RedisConfigurationRepository } from '../../adapters/secondaries/redis-configuration.repository';
|
||||
import { DeleteConfigurationCommand } from '../../commands/delete-configuration.command';
|
||||
import { DeleteConfigurationRequest } from '../../domain/dtos/delete-configuration.request';
|
||||
import { DeleteConfigurationUseCase } from '../../domain/usecases/delete-configuration.usecase';
|
||||
|
||||
const mockRedisConfigurationRepository = {
|
||||
del: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
describe('DeleteConfigurationUseCase', () => {
|
||||
let deleteConfigurationUseCase: DeleteConfigurationUseCase;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: RedisConfigurationRepository,
|
||||
useValue: mockRedisConfigurationRepository,
|
||||
},
|
||||
|
||||
DeleteConfigurationUseCase,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
deleteConfigurationUseCase = module.get<DeleteConfigurationUseCase>(
|
||||
DeleteConfigurationUseCase,
|
||||
);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(deleteConfigurationUseCase).toBeDefined();
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should delete a key', async () => {
|
||||
jest.spyOn(mockRedisConfigurationRepository, 'del');
|
||||
const deleteConfigurationRequest: DeleteConfigurationRequest = {
|
||||
domain: 'my-domain',
|
||||
key: 'my-key',
|
||||
};
|
||||
await deleteConfigurationUseCase.execute(
|
||||
new DeleteConfigurationCommand(deleteConfigurationRequest),
|
||||
);
|
||||
|
||||
expect(mockRedisConfigurationRepository.del).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { RedisConfigurationRepository } from '../../adapters/secondaries/redis-configuration.repository';
|
||||
import { GetConfigurationUseCase } from '../../domain/usecases/get-configuration.usecase';
|
||||
import { GetConfigurationQuery } from '../../queries/get-configuration.query';
|
||||
|
||||
const mockRedisConfigurationRepository = {
|
||||
get: jest.fn().mockResolvedValue('my-value'),
|
||||
};
|
||||
|
||||
describe('GetConfigurationUseCase', () => {
|
||||
let getConfigurationUseCase: GetConfigurationUseCase;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: RedisConfigurationRepository,
|
||||
useValue: mockRedisConfigurationRepository,
|
||||
},
|
||||
|
||||
GetConfigurationUseCase,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
getConfigurationUseCase = module.get<GetConfigurationUseCase>(
|
||||
GetConfigurationUseCase,
|
||||
);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(getConfigurationUseCase).toBeDefined();
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should get a value for a key', async () => {
|
||||
const value: string = await getConfigurationUseCase.execute(
|
||||
new GetConfigurationQuery('my-domain', 'my-key'),
|
||||
);
|
||||
|
||||
expect(value).toBe('my-value');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { RedisConfigurationRepository } from '../../adapters/secondaries/redis-configuration.repository';
|
||||
import { getRedisToken } from '@liaoliaots/nestjs-redis';
|
||||
|
||||
const mockRedis = {
|
||||
get: jest.fn().mockResolvedValue('myValue'),
|
||||
set: jest.fn().mockImplementation(),
|
||||
del: jest.fn().mockImplementation(),
|
||||
};
|
||||
|
||||
describe('RedisConfigurationRepository', () => {
|
||||
let redisConfigurationRepository: RedisConfigurationRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: getRedisToken('default'),
|
||||
useValue: mockRedis,
|
||||
},
|
||||
RedisConfigurationRepository,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
redisConfigurationRepository = module.get<RedisConfigurationRepository>(
|
||||
RedisConfigurationRepository,
|
||||
);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(redisConfigurationRepository).toBeDefined();
|
||||
});
|
||||
|
||||
describe('interact', () => {
|
||||
it('should get a value', async () => {
|
||||
expect(await redisConfigurationRepository.get('myKey')).toBe('myValue');
|
||||
});
|
||||
it('should set a value', async () => {
|
||||
expect(
|
||||
await redisConfigurationRepository.set('myKey', 'myValue'),
|
||||
).toBeUndefined();
|
||||
});
|
||||
it('should delete a value', async () => {
|
||||
expect(await redisConfigurationRepository.del('myKey')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { RedisConfigurationRepository } from '../../adapters/secondaries/redis-configuration.repository';
|
||||
import { SetConfigurationCommand } from '../../commands/set-configuration.command';
|
||||
import { SetConfigurationRequest } from '../../domain/dtos/set-configuration.request';
|
||||
import { SetConfigurationUseCase } from '../../domain/usecases/set-configuration.usecase';
|
||||
|
||||
const mockRedisConfigurationRepository = {
|
||||
set: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
describe('SetConfigurationUseCase', () => {
|
||||
let setConfigurationUseCase: SetConfigurationUseCase;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: RedisConfigurationRepository,
|
||||
useValue: mockRedisConfigurationRepository,
|
||||
},
|
||||
|
||||
SetConfigurationUseCase,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
setConfigurationUseCase = module.get<SetConfigurationUseCase>(
|
||||
SetConfigurationUseCase,
|
||||
);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(setConfigurationUseCase).toBeDefined();
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should set a value for a key', async () => {
|
||||
jest.spyOn(mockRedisConfigurationRepository, 'set');
|
||||
const setConfigurationRequest: SetConfigurationRequest = {
|
||||
domain: 'my-domain',
|
||||
key: 'my-key',
|
||||
value: 'my-value',
|
||||
};
|
||||
await setConfigurationUseCase.execute(
|
||||
new SetConfigurationCommand(setConfigurationRequest),
|
||||
);
|
||||
|
||||
expect(mockRedisConfigurationRepository.set).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
9
src/modules/database/database.module.ts
Normal file
9
src/modules/database/database.module.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaService } from './src/adapters/secondaries/prisma-service';
|
||||
import { AdRepository } from './src/domain/ad-repository';
|
||||
|
||||
@Module({
|
||||
providers: [PrismaService, AdRepository],
|
||||
exports: [PrismaService, AdRepository],
|
||||
})
|
||||
export class DatabaseModule {}
|
||||
@@ -0,0 +1,202 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { PrismaClientKnownRequestError } from '@prisma/client/runtime';
|
||||
import { DatabaseException } from '../../exceptions/database.exception';
|
||||
import { ICollection } from '../../interfaces/collection.interface';
|
||||
import { IRepository } from '../../interfaces/repository.interface';
|
||||
import { PrismaService } from './prisma-service';
|
||||
|
||||
/**
|
||||
* Child classes MUST redefined _model property with appropriate model name
|
||||
*/
|
||||
@Injectable()
|
||||
export abstract class PrismaRepository<T> implements IRepository<T> {
|
||||
protected _model: string;
|
||||
|
||||
constructor(protected readonly _prisma: PrismaService) {}
|
||||
|
||||
async findAll(
|
||||
page = 1,
|
||||
perPage = 10,
|
||||
where?: any,
|
||||
include?: any,
|
||||
): Promise<ICollection<T>> {
|
||||
const [data, total] = await this._prisma.$transaction([
|
||||
this._prisma[this._model].findMany({
|
||||
where,
|
||||
include,
|
||||
skip: (page - 1) * perPage,
|
||||
take: perPage,
|
||||
}),
|
||||
this._prisma[this._model].count({
|
||||
where,
|
||||
}),
|
||||
]);
|
||||
return Promise.resolve({
|
||||
data,
|
||||
total,
|
||||
});
|
||||
}
|
||||
|
||||
async findOneByUuid(uuid: string): Promise<T> {
|
||||
try {
|
||||
const entity = await this._prisma[this._model].findUnique({
|
||||
where: { uuid },
|
||||
});
|
||||
|
||||
return entity;
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(
|
||||
PrismaClientKnownRequestError.name,
|
||||
e.code,
|
||||
e.message,
|
||||
);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async findOne(where: any, include?: any): Promise<T> {
|
||||
try {
|
||||
const entity = await this._prisma[this._model].findFirst({
|
||||
where: where,
|
||||
include: include,
|
||||
});
|
||||
|
||||
return entity;
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(PrismaClientKnownRequestError.name, e.code);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO : using any is not good, but needed for nested entities
|
||||
// TODO : Refactor for good clean architecture ?
|
||||
async create(entity: Partial<T> | any, include?: any): Promise<T> {
|
||||
try {
|
||||
const res = await this._prisma[this._model].create({
|
||||
data: entity,
|
||||
include: include,
|
||||
});
|
||||
|
||||
return res;
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(
|
||||
PrismaClientKnownRequestError.name,
|
||||
e.code,
|
||||
e.message,
|
||||
);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async update(uuid: string, entity: Partial<T>): Promise<T> {
|
||||
try {
|
||||
const updatedEntity = await this._prisma[this._model].update({
|
||||
where: { uuid },
|
||||
data: entity,
|
||||
});
|
||||
return updatedEntity;
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(
|
||||
PrismaClientKnownRequestError.name,
|
||||
e.code,
|
||||
e.message,
|
||||
);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async updateWhere(
|
||||
where: any,
|
||||
entity: Partial<T> | any,
|
||||
include?: any,
|
||||
): Promise<T> {
|
||||
try {
|
||||
const updatedEntity = await this._prisma[this._model].update({
|
||||
where: where,
|
||||
data: entity,
|
||||
include: include,
|
||||
});
|
||||
|
||||
return updatedEntity;
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(
|
||||
PrismaClientKnownRequestError.name,
|
||||
e.code,
|
||||
e.message,
|
||||
);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async delete(uuid: string): Promise<T> {
|
||||
try {
|
||||
const entity = await this._prisma[this._model].delete({
|
||||
where: { uuid },
|
||||
});
|
||||
|
||||
return entity;
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(
|
||||
PrismaClientKnownRequestError.name,
|
||||
e.code,
|
||||
e.message,
|
||||
);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async deleteMany(where: any): Promise<void> {
|
||||
try {
|
||||
const entity = await this._prisma[this._model].deleteMany({
|
||||
where: where,
|
||||
});
|
||||
|
||||
return entity;
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(
|
||||
PrismaClientKnownRequestError.name,
|
||||
e.code,
|
||||
e.message,
|
||||
);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async healthCheck(): Promise<boolean> {
|
||||
try {
|
||||
await this._prisma.$queryRaw`SELECT 1`;
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(
|
||||
PrismaClientKnownRequestError.name,
|
||||
e.code,
|
||||
e.message,
|
||||
);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient implements OnModuleInit {
|
||||
async onModuleInit() {
|
||||
await this.$connect();
|
||||
}
|
||||
|
||||
async enableShutdownHooks(app: INestApplication) {
|
||||
this.$on('beforeExit', async () => {
|
||||
await app.close();
|
||||
});
|
||||
}
|
||||
}
|
||||
3
src/modules/database/src/domain/ad-repository.ts
Normal file
3
src/modules/database/src/domain/ad-repository.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { PrismaRepository } from '../adapters/secondaries/prisma-repository.abstract';
|
||||
|
||||
export class AdRepository<T> extends PrismaRepository<T> {}
|
||||
24
src/modules/database/src/exceptions/database.exception.ts
Normal file
24
src/modules/database/src/exceptions/database.exception.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
export class DatabaseException implements Error {
|
||||
name: string;
|
||||
message: string;
|
||||
|
||||
constructor(
|
||||
private _type: string = 'unknown',
|
||||
private _code: string = '',
|
||||
message?: string,
|
||||
) {
|
||||
this.name = 'DatabaseException';
|
||||
this.message = message ?? 'An error occured with the database.';
|
||||
if (this.message.includes('Unique constraint failed')) {
|
||||
this.message = 'Already exists.';
|
||||
}
|
||||
}
|
||||
|
||||
get type(): string {
|
||||
return this._type;
|
||||
}
|
||||
|
||||
get code(): string {
|
||||
return this._code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export interface ICollection<T> {
|
||||
data: T[];
|
||||
total: number;
|
||||
}
|
||||
18
src/modules/database/src/interfaces/repository.interface.ts
Normal file
18
src/modules/database/src/interfaces/repository.interface.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { ICollection } from './collection.interface';
|
||||
|
||||
export interface IRepository<T> {
|
||||
findAll(
|
||||
page: number,
|
||||
perPage: number,
|
||||
params?: any,
|
||||
include?: any,
|
||||
): Promise<ICollection<T>>;
|
||||
findOne(where: any, include?: any): Promise<T>;
|
||||
findOneByUuid(uuid: string, include?: any): Promise<T>;
|
||||
create(entity: Partial<T> | any, include?: any): Promise<T>;
|
||||
update(uuid: string, entity: Partial<T>, include?: any): Promise<T>;
|
||||
updateWhere(where: any, entity: Partial<T> | any, include?: any): Promise<T>;
|
||||
delete(uuid: string): Promise<T>;
|
||||
deleteMany(where: any): Promise<void>;
|
||||
healthCheck(): Promise<boolean>;
|
||||
}
|
||||
461
src/modules/database/tests/unit/prisma-repository.spec.ts
Normal file
461
src/modules/database/tests/unit/prisma-repository.spec.ts
Normal file
@@ -0,0 +1,461 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { PrismaService } from '../../src/adapters/secondaries/prisma-service';
|
||||
import { PrismaRepository } from '../../src/adapters/secondaries/prisma-repository.abstract';
|
||||
import { DatabaseException } from '../../src/exceptions/database.exception';
|
||||
import { PrismaClientKnownRequestError } from '@prisma/client/runtime';
|
||||
|
||||
class FakeEntity {
|
||||
uuid?: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
let entityId = 2;
|
||||
const entityUuid = 'uuid-';
|
||||
const entityName = 'name-';
|
||||
|
||||
const createRandomEntity = (): FakeEntity => {
|
||||
const entity: FakeEntity = {
|
||||
uuid: `${entityUuid}${entityId}`,
|
||||
name: `${entityName}${entityId}`,
|
||||
};
|
||||
|
||||
entityId++;
|
||||
|
||||
return entity;
|
||||
};
|
||||
|
||||
const fakeEntityToCreate: FakeEntity = {
|
||||
name: 'test',
|
||||
};
|
||||
|
||||
const fakeEntityCreated: FakeEntity = {
|
||||
...fakeEntityToCreate,
|
||||
uuid: 'some-uuid',
|
||||
};
|
||||
|
||||
const fakeEntities: FakeEntity[] = [];
|
||||
Array.from({ length: 10 }).forEach(() => {
|
||||
fakeEntities.push(createRandomEntity());
|
||||
});
|
||||
|
||||
@Injectable()
|
||||
class FakePrismaRepository extends PrismaRepository<FakeEntity> {
|
||||
protected _model = 'fake';
|
||||
}
|
||||
|
||||
class FakePrismaService extends PrismaService {
|
||||
fake: any;
|
||||
}
|
||||
|
||||
const mockPrismaService = {
|
||||
$transaction: jest.fn().mockImplementation(async (data: any) => {
|
||||
const entities = await data[0];
|
||||
if (entities.length == 1) {
|
||||
return Promise.resolve([[fakeEntityCreated], 1]);
|
||||
}
|
||||
|
||||
return Promise.resolve([fakeEntities, fakeEntities.length]);
|
||||
}),
|
||||
$queryRaw: jest
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
throw new PrismaClientKnownRequestError('unknown request', {
|
||||
code: 'code',
|
||||
clientVersion: 'version',
|
||||
});
|
||||
})
|
||||
.mockImplementationOnce(() => {
|
||||
return true;
|
||||
})
|
||||
.mockImplementation(() => {
|
||||
throw new PrismaClientKnownRequestError('Database unavailable', {
|
||||
code: 'code',
|
||||
clientVersion: 'version',
|
||||
});
|
||||
}),
|
||||
fake: {
|
||||
create: jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce(fakeEntityCreated)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.mockImplementationOnce((params?: any) => {
|
||||
throw new PrismaClientKnownRequestError('unknown request', {
|
||||
code: 'code',
|
||||
clientVersion: 'version',
|
||||
});
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.mockImplementationOnce((params?: any) => {
|
||||
throw new Error('an unknown error');
|
||||
}),
|
||||
|
||||
findMany: jest.fn().mockImplementation((params?: any) => {
|
||||
if (params?.where?.limit == 1) {
|
||||
return Promise.resolve([fakeEntityCreated]);
|
||||
}
|
||||
|
||||
return Promise.resolve(fakeEntities);
|
||||
}),
|
||||
count: jest.fn().mockResolvedValue(fakeEntities.length),
|
||||
|
||||
findUnique: jest.fn().mockImplementation(async (params?: any) => {
|
||||
let entity;
|
||||
|
||||
if (params?.where?.uuid) {
|
||||
entity = fakeEntities.find(
|
||||
(entity) => entity.uuid === params?.where?.uuid,
|
||||
);
|
||||
}
|
||||
|
||||
if (!entity && params?.where?.uuid == 'unknown') {
|
||||
throw new PrismaClientKnownRequestError('unknown request', {
|
||||
code: 'code',
|
||||
clientVersion: 'version',
|
||||
});
|
||||
} else if (!entity) {
|
||||
throw new Error('no entity');
|
||||
}
|
||||
|
||||
return entity;
|
||||
}),
|
||||
|
||||
findFirst: jest
|
||||
.fn()
|
||||
.mockImplementationOnce((params?: any) => {
|
||||
if (params?.where?.name) {
|
||||
return Promise.resolve(
|
||||
fakeEntities.find((entity) => entity.name === params?.where?.name),
|
||||
);
|
||||
}
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.mockImplementationOnce((params?: any) => {
|
||||
throw new PrismaClientKnownRequestError('unknown request', {
|
||||
code: 'code',
|
||||
clientVersion: 'version',
|
||||
});
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.mockImplementationOnce((params?: any) => {
|
||||
throw new Error('an unknown error');
|
||||
}),
|
||||
|
||||
update: jest
|
||||
.fn()
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.mockImplementationOnce((params?: any) => {
|
||||
throw new PrismaClientKnownRequestError('unknown request', {
|
||||
code: 'code',
|
||||
clientVersion: 'version',
|
||||
});
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.mockImplementationOnce((params?: any) => {
|
||||
throw new PrismaClientKnownRequestError('unknown request', {
|
||||
code: 'code',
|
||||
clientVersion: 'version',
|
||||
});
|
||||
})
|
||||
.mockImplementationOnce((params: any) => {
|
||||
const entity = fakeEntities.find(
|
||||
(entity) => entity.name === params.where.name,
|
||||
);
|
||||
Object.entries(params.data).map(([key, value]) => {
|
||||
entity[key] = value;
|
||||
});
|
||||
|
||||
return Promise.resolve(entity);
|
||||
})
|
||||
.mockImplementation((params: any) => {
|
||||
const entity = fakeEntities.find(
|
||||
(entity) => entity.uuid === params.where.uuid,
|
||||
);
|
||||
Object.entries(params.data).map(([key, value]) => {
|
||||
entity[key] = value;
|
||||
});
|
||||
|
||||
return Promise.resolve(entity);
|
||||
}),
|
||||
|
||||
delete: jest
|
||||
.fn()
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.mockImplementationOnce((params?: any) => {
|
||||
throw new PrismaClientKnownRequestError('unknown request', {
|
||||
code: 'code',
|
||||
clientVersion: 'version',
|
||||
});
|
||||
})
|
||||
.mockImplementation((params: any) => {
|
||||
let found = false;
|
||||
|
||||
fakeEntities.forEach((entity, index) => {
|
||||
if (entity.uuid === params?.where?.uuid) {
|
||||
found = true;
|
||||
fakeEntities.splice(index, 1);
|
||||
}
|
||||
});
|
||||
|
||||
if (!found) {
|
||||
throw new Error();
|
||||
}
|
||||
}),
|
||||
|
||||
deleteMany: jest
|
||||
.fn()
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.mockImplementationOnce((params?: any) => {
|
||||
throw new PrismaClientKnownRequestError('unknown request', {
|
||||
code: 'code',
|
||||
clientVersion: 'version',
|
||||
});
|
||||
})
|
||||
.mockImplementation((params: any) => {
|
||||
let found = false;
|
||||
|
||||
fakeEntities.forEach((entity, index) => {
|
||||
if (entity.uuid === params?.where?.uuid) {
|
||||
found = true;
|
||||
fakeEntities.splice(index, 1);
|
||||
}
|
||||
});
|
||||
|
||||
if (!found) {
|
||||
throw new Error();
|
||||
}
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
describe('PrismaRepository', () => {
|
||||
let fakeRepository: FakePrismaRepository;
|
||||
let prisma: FakePrismaService;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
FakePrismaRepository,
|
||||
{
|
||||
provide: PrismaService,
|
||||
useValue: mockPrismaService,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
fakeRepository = module.get<FakePrismaRepository>(FakePrismaRepository);
|
||||
prisma = module.get<PrismaService>(PrismaService) as FakePrismaService;
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(fakeRepository).toBeDefined();
|
||||
expect(prisma).toBeDefined();
|
||||
});
|
||||
|
||||
describe('findAll', () => {
|
||||
it('should return an array of entities', async () => {
|
||||
jest.spyOn(prisma.fake, 'findMany');
|
||||
jest.spyOn(prisma.fake, 'count');
|
||||
jest.spyOn(prisma, '$transaction');
|
||||
|
||||
const entities = await fakeRepository.findAll();
|
||||
expect(entities).toStrictEqual({
|
||||
data: fakeEntities,
|
||||
total: fakeEntities.length,
|
||||
});
|
||||
});
|
||||
|
||||
it('should return an array containing only one entity', async () => {
|
||||
const entities = await fakeRepository.findAll(1, 10, { limit: 1 });
|
||||
|
||||
expect(prisma.fake.findMany).toHaveBeenCalledWith({
|
||||
skip: 0,
|
||||
take: 10,
|
||||
where: { limit: 1 },
|
||||
});
|
||||
expect(entities).toEqual({
|
||||
data: [fakeEntityCreated],
|
||||
total: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('should create an entity', async () => {
|
||||
jest.spyOn(prisma.fake, 'create');
|
||||
|
||||
const newEntity = await fakeRepository.create(fakeEntityToCreate);
|
||||
expect(newEntity).toBe(fakeEntityCreated);
|
||||
expect(prisma.fake.create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should throw a DatabaseException for client error', async () => {
|
||||
await expect(
|
||||
fakeRepository.create(fakeEntityToCreate),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
|
||||
it('should throw a DatabaseException if uuid is not found', async () => {
|
||||
await expect(
|
||||
fakeRepository.create(fakeEntityToCreate),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findOneByUuid', () => {
|
||||
it('should find an entity by uuid', async () => {
|
||||
const entity = await fakeRepository.findOneByUuid(fakeEntities[0].uuid);
|
||||
expect(entity).toBe(fakeEntities[0]);
|
||||
});
|
||||
|
||||
it('should throw a DatabaseException for client error', async () => {
|
||||
await expect(
|
||||
fakeRepository.findOneByUuid('unknown'),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
|
||||
it('should throw a DatabaseException if uuid is not found', async () => {
|
||||
await expect(
|
||||
fakeRepository.findOneByUuid('wrong-uuid'),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findOne', () => {
|
||||
it('should find one entity', async () => {
|
||||
const entity = await fakeRepository.findOne({
|
||||
name: fakeEntities[0].name,
|
||||
});
|
||||
|
||||
expect(entity.name).toBe(fakeEntities[0].name);
|
||||
});
|
||||
|
||||
it('should throw a DatabaseException for client error', async () => {
|
||||
await expect(
|
||||
fakeRepository.findOne({
|
||||
name: fakeEntities[0].name,
|
||||
}),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
|
||||
it('should throw a DatabaseException for unknown error', async () => {
|
||||
await expect(
|
||||
fakeRepository.findOne({
|
||||
name: fakeEntities[0].name,
|
||||
}),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('should throw a DatabaseException for client error', async () => {
|
||||
await expect(
|
||||
fakeRepository.update('fake-uuid', { name: 'error' }),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
await expect(
|
||||
fakeRepository.updateWhere({ name: 'error' }, { name: 'new error' }),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
|
||||
it('should update an entity with name', async () => {
|
||||
const newName = 'new-random-name';
|
||||
|
||||
await fakeRepository.updateWhere(
|
||||
{ name: fakeEntities[0].name },
|
||||
{
|
||||
name: newName,
|
||||
},
|
||||
);
|
||||
expect(fakeEntities[0].name).toBe(newName);
|
||||
});
|
||||
|
||||
it('should update an entity with uuid', async () => {
|
||||
const newName = 'random-name';
|
||||
|
||||
await fakeRepository.update(fakeEntities[0].uuid, {
|
||||
name: newName,
|
||||
});
|
||||
expect(fakeEntities[0].name).toBe(newName);
|
||||
});
|
||||
|
||||
it("should throw an exception if an entity doesn't exist", async () => {
|
||||
await expect(
|
||||
fakeRepository.update('fake-uuid', { name: 'error' }),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
await expect(
|
||||
fakeRepository.updateWhere({ name: 'error' }, { name: 'new error' }),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('should throw a DatabaseException for client error', async () => {
|
||||
await expect(fakeRepository.delete('fake-uuid')).rejects.toBeInstanceOf(
|
||||
DatabaseException,
|
||||
);
|
||||
});
|
||||
|
||||
it('should delete an entity', async () => {
|
||||
const savedUuid = fakeEntities[0].uuid;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const res = await fakeRepository.delete(savedUuid);
|
||||
|
||||
const deletedEntity = fakeEntities.find(
|
||||
(entity) => entity.uuid === savedUuid,
|
||||
);
|
||||
expect(deletedEntity).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should throw an exception if an entity doesn't exist", async () => {
|
||||
await expect(fakeRepository.delete('fake-uuid')).rejects.toBeInstanceOf(
|
||||
DatabaseException,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteMany', () => {
|
||||
it('should throw a DatabaseException for client error', async () => {
|
||||
await expect(
|
||||
fakeRepository.deleteMany({ uuid: 'fake-uuid' }),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
|
||||
it('should delete entities based on their uuid', async () => {
|
||||
const savedUuid = fakeEntities[0].uuid;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const res = await fakeRepository.deleteMany({ uuid: savedUuid });
|
||||
|
||||
const deletedEntity = fakeEntities.find(
|
||||
(entity) => entity.uuid === savedUuid,
|
||||
);
|
||||
expect(deletedEntity).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should throw an exception if an entity doesn't exist", async () => {
|
||||
await expect(
|
||||
fakeRepository.deleteMany({ uuid: 'fake-uuid' }),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('healthCheck', () => {
|
||||
it('should throw a DatabaseException for client error', async () => {
|
||||
await expect(fakeRepository.healthCheck()).rejects.toBeInstanceOf(
|
||||
DatabaseException,
|
||||
);
|
||||
});
|
||||
|
||||
it('should return a healthy result', async () => {
|
||||
const res = await fakeRepository.healthCheck();
|
||||
expect(res).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should throw an exception if database is not available', async () => {
|
||||
await expect(fakeRepository.healthCheck()).rejects.toBeInstanceOf(
|
||||
DatabaseException,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Controller } from '@nestjs/common';
|
||||
import { GrpcMethod } from '@nestjs/microservices';
|
||||
import { PrismaHealthIndicatorUseCase } from '../../domain/usecases/prisma.health-indicator.usecase';
|
||||
|
||||
enum ServingStatus {
|
||||
UNKNOWN = 0,
|
||||
SERVING = 1,
|
||||
NOT_SERVING = 2,
|
||||
}
|
||||
|
||||
interface HealthCheckRequest {
|
||||
service: string;
|
||||
}
|
||||
|
||||
interface HealthCheckResponse {
|
||||
status: ServingStatus;
|
||||
}
|
||||
|
||||
@Controller()
|
||||
export class HealthServerController {
|
||||
constructor(
|
||||
private readonly _prismaHealthIndicatorUseCase: PrismaHealthIndicatorUseCase,
|
||||
) {}
|
||||
|
||||
@GrpcMethod('Health', 'Check')
|
||||
async check(
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
data: HealthCheckRequest,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
metadata: any,
|
||||
): Promise<HealthCheckResponse> {
|
||||
const healthCheck = await this._prismaHealthIndicatorUseCase.isHealthy(
|
||||
'prisma',
|
||||
);
|
||||
return {
|
||||
status:
|
||||
healthCheck['prisma'].status == 'up'
|
||||
? ServingStatus.SERVING
|
||||
: ServingStatus.NOT_SERVING,
|
||||
};
|
||||
}
|
||||
}
|
||||
34
src/modules/health/adapters/primaries/health.controller.ts
Normal file
34
src/modules/health/adapters/primaries/health.controller.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import {
|
||||
HealthCheckService,
|
||||
HealthCheck,
|
||||
HealthCheckResult,
|
||||
} from '@nestjs/terminus';
|
||||
import { Messager } from '../secondaries/messager';
|
||||
import { PrismaHealthIndicatorUseCase } from '../../domain/usecases/prisma.health-indicator.usecase';
|
||||
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
constructor(
|
||||
private readonly _prismaHealthIndicatorUseCase: PrismaHealthIndicatorUseCase,
|
||||
private _healthCheckService: HealthCheckService,
|
||||
private _messager: Messager,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@HealthCheck()
|
||||
async check() {
|
||||
try {
|
||||
return await this._healthCheckService.check([
|
||||
async () => this._prismaHealthIndicatorUseCase.isHealthy('prisma'),
|
||||
]);
|
||||
} catch (error) {
|
||||
const healthCheckResult: HealthCheckResult = error.response;
|
||||
this._messager.publish(
|
||||
'logging.user.health.crit',
|
||||
JSON.stringify(healthCheckResult.error),
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
21
src/modules/health/adapters/primaries/health.proto
Normal file
21
src/modules/health/adapters/primaries/health.proto
Normal file
@@ -0,0 +1,21 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package health;
|
||||
|
||||
|
||||
service Health {
|
||||
rpc Check(HealthCheckRequest) returns (HealthCheckResponse);
|
||||
}
|
||||
|
||||
message HealthCheckRequest {
|
||||
string service = 1;
|
||||
}
|
||||
|
||||
message HealthCheckResponse {
|
||||
enum ServingStatus {
|
||||
UNKNOWN = 0;
|
||||
SERVING = 1;
|
||||
NOT_SERVING = 2;
|
||||
}
|
||||
ServingStatus status = 1;
|
||||
}
|
||||
12
src/modules/health/adapters/secondaries/message-broker.ts
Normal file
12
src/modules/health/adapters/secondaries/message-broker.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export abstract class IMessageBroker {
|
||||
exchange: string;
|
||||
|
||||
constructor(exchange: string) {
|
||||
this.exchange = exchange;
|
||||
}
|
||||
|
||||
abstract publish(routingKey: string, message: string): void;
|
||||
}
|
||||
18
src/modules/health/adapters/secondaries/messager.ts
Normal file
18
src/modules/health/adapters/secondaries/messager.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { IMessageBroker } from './message-broker';
|
||||
|
||||
@Injectable()
|
||||
export class Messager extends IMessageBroker {
|
||||
constructor(
|
||||
private readonly _amqpConnection: AmqpConnection,
|
||||
configService: ConfigService,
|
||||
) {
|
||||
super(configService.get<string>('RMQ_EXCHANGE'));
|
||||
}
|
||||
|
||||
publish(routingKey: string, message: string): void {
|
||||
this._amqpConnection.publish(this.exchange, routingKey, message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
HealthCheckError,
|
||||
HealthIndicator,
|
||||
HealthIndicatorResult,
|
||||
} from '@nestjs/terminus';
|
||||
import { AdsRepository } from '../../../ad/adapters/secondaries/ads.repository';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaHealthIndicatorUseCase extends HealthIndicator {
|
||||
constructor(private readonly _repository: AdsRepository) {
|
||||
super();
|
||||
}
|
||||
|
||||
async isHealthy(key: string): Promise<HealthIndicatorResult> {
|
||||
try {
|
||||
await this._repository.healthCheck();
|
||||
return this.getStatus(key, true);
|
||||
} catch (e) {
|
||||
throw new HealthCheckError('Prisma', {
|
||||
prisma: e.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
34
src/modules/health/health.module.ts
Normal file
34
src/modules/health/health.module.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { HealthServerController } from './adapters/primaries/health-server.controller';
|
||||
import { PrismaHealthIndicatorUseCase } from './domain/usecases/prisma.health-indicator.usecase';
|
||||
import { AdsRepository } from '../ad/adapters/secondaries/ads.repository';
|
||||
import { DatabaseModule } from '../database/database.module';
|
||||
import { HealthController } from './adapters/primaries/health.controller';
|
||||
import { TerminusModule } from '@nestjs/terminus';
|
||||
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { Messager } from './adapters/secondaries/messager';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TerminusModule,
|
||||
RabbitMQModule.forRootAsync(RabbitMQModule, {
|
||||
imports: [ConfigModule],
|
||||
useFactory: async (configService: ConfigService) => ({
|
||||
exchanges: [
|
||||
{
|
||||
name: configService.get<string>('RMQ_EXCHANGE'),
|
||||
type: 'topic',
|
||||
},
|
||||
],
|
||||
uri: configService.get<string>('RMQ_URI'),
|
||||
connectionInitOptions: { wait: false },
|
||||
}),
|
||||
inject: [ConfigService],
|
||||
}),
|
||||
DatabaseModule,
|
||||
],
|
||||
controllers: [HealthServerController, HealthController],
|
||||
providers: [PrismaHealthIndicatorUseCase, AdsRepository, Messager],
|
||||
})
|
||||
export class HealthModule {}
|
||||
47
src/modules/health/tests/unit/messager.spec.ts
Normal file
47
src/modules/health/tests/unit/messager.spec.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { Messager } from '../../adapters/secondaries/messager';
|
||||
|
||||
const mockAmqpConnection = {
|
||||
publish: jest.fn().mockImplementation(),
|
||||
};
|
||||
|
||||
const mockConfigService = {
|
||||
get: jest.fn().mockResolvedValue({
|
||||
RMQ_EXCHANGE: 'mobicoop',
|
||||
}),
|
||||
};
|
||||
|
||||
describe('Messager', () => {
|
||||
let messager: Messager;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [],
|
||||
providers: [
|
||||
Messager,
|
||||
{
|
||||
provide: AmqpConnection,
|
||||
useValue: mockAmqpConnection,
|
||||
},
|
||||
{
|
||||
provide: ConfigService,
|
||||
useValue: mockConfigService,
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
messager = module.get<Messager>(Messager);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(messager).toBeDefined();
|
||||
});
|
||||
|
||||
it('should publish a message', async () => {
|
||||
jest.spyOn(mockAmqpConnection, 'publish');
|
||||
messager.publish('test.create.info', 'my-test');
|
||||
expect(mockAmqpConnection.publish).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { PrismaHealthIndicatorUseCase } from '../../domain/usecases/prisma.health-indicator.usecase';
|
||||
import { UsersRepository } from '../../../user/adapters/secondaries/users.repository';
|
||||
import { PrismaClientKnownRequestError } from '@prisma/client/runtime';
|
||||
import { HealthCheckError, HealthIndicatorResult } from '@nestjs/terminus';
|
||||
|
||||
const mockUsersRepository = {
|
||||
healthCheck: jest
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
return Promise.resolve(true);
|
||||
})
|
||||
.mockImplementation(() => {
|
||||
throw new PrismaClientKnownRequestError('Service unavailable', {
|
||||
code: 'code',
|
||||
clientVersion: 'version',
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
describe('PrismaHealthIndicatorUseCase', () => {
|
||||
let prismaHealthIndicatorUseCase: PrismaHealthIndicatorUseCase;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: UsersRepository,
|
||||
useValue: mockUsersRepository,
|
||||
},
|
||||
PrismaHealthIndicatorUseCase,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
prismaHealthIndicatorUseCase = module.get<PrismaHealthIndicatorUseCase>(
|
||||
PrismaHealthIndicatorUseCase,
|
||||
);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(prismaHealthIndicatorUseCase).toBeDefined();
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should check health successfully', async () => {
|
||||
const healthIndicatorResult: HealthIndicatorResult =
|
||||
await prismaHealthIndicatorUseCase.isHealthy('prisma');
|
||||
|
||||
expect(healthIndicatorResult['prisma'].status).toBe('up');
|
||||
});
|
||||
|
||||
it('should throw an error if database is unavailable', async () => {
|
||||
await expect(
|
||||
prismaHealthIndicatorUseCase.isHealthy('prisma'),
|
||||
).rejects.toBeInstanceOf(HealthCheckError);
|
||||
});
|
||||
});
|
||||
});
|
||||
14
src/utils/pipes/rpc.validation-pipe.ts
Normal file
14
src/utils/pipes/rpc.validation-pipe.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Injectable, ValidationPipe } from '@nestjs/common';
|
||||
import { RpcException } from '@nestjs/microservices';
|
||||
|
||||
@Injectable()
|
||||
export class RpcValidationPipe extends ValidationPipe {
|
||||
createExceptionFactory() {
|
||||
return (validationErrors = []) => {
|
||||
return new RpcException({
|
||||
code: 3,
|
||||
message: this.flattenValidationErrors(validationErrors),
|
||||
});
|
||||
};
|
||||
}
|
||||
}
|
||||
20
src/utils/tests/unit/rpc-validation-pipe.usecase.spec.ts
Normal file
20
src/utils/tests/unit/rpc-validation-pipe.usecase.spec.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { ArgumentMetadata } from '@nestjs/common';
|
||||
import { UpdateUserRequest } from '../../../modules/user/domain/dtos/update-user.request';
|
||||
import { RpcValidationPipe } from '../../pipes/rpc.validation-pipe';
|
||||
|
||||
describe('RpcValidationPipe', () => {
|
||||
it('should not validate request', async () => {
|
||||
const target: RpcValidationPipe = new RpcValidationPipe({
|
||||
whitelist: true,
|
||||
forbidUnknownValues: false,
|
||||
});
|
||||
const metadata: ArgumentMetadata = {
|
||||
type: 'body',
|
||||
metatype: UpdateUserRequest,
|
||||
data: '',
|
||||
};
|
||||
await target.transform(<UpdateUserRequest>{}, metadata).catch((err) => {
|
||||
expect(err.message).toEqual('Rpc Exception');
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user