mirror of
https://gitlab.com/mobicoop/v3/service/matcher.git
synced 2026-01-01 08:22:41 +00:00
first commit
This commit is contained in:
@@ -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,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 { MatcherRepository } from './src/domain/matcher-repository';
|
||||
|
||||
@Module({
|
||||
providers: [PrismaService, MatcherRepository],
|
||||
exports: [PrismaService, MatcherRepository],
|
||||
})
|
||||
export class DatabaseModule {}
|
||||
@@ -0,0 +1,256 @@
|
||||
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 findAllByQuery(
|
||||
include: Array<string>,
|
||||
where: Array<string>,
|
||||
): Promise<ICollection<T>> {
|
||||
const query = `SELECT ${include.join(',')} FROM ${
|
||||
this._model
|
||||
} WHERE ${where.join(' AND ')}`;
|
||||
const data: Array<T> = await this._prisma.$queryRawUnsafe(query);
|
||||
return Promise.resolve({
|
||||
data,
|
||||
total: data.length,
|
||||
});
|
||||
}
|
||||
|
||||
async createWithFields(fields: object): Promise<number> {
|
||||
try {
|
||||
const command = `INSERT INTO ${this._model} (${Object.keys(fields).join(
|
||||
',',
|
||||
)}) VALUES (${Object.values(fields).join(',')})`;
|
||||
return await this._prisma.$executeRawUnsafe(command);
|
||||
} catch (e) {
|
||||
if (e instanceof PrismaClientKnownRequestError) {
|
||||
throw new DatabaseException(
|
||||
PrismaClientKnownRequestError.name,
|
||||
e.code,
|
||||
e.message,
|
||||
);
|
||||
} else {
|
||||
throw new DatabaseException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async updateWithFields(uuid: string, entity: Partial<T>): Promise<number> {
|
||||
entity['"updatedAt"'] = `to_timestamp(${Date.now()} / 1000.0)`;
|
||||
const values = Object.keys(entity).map((key) => `${key} = ${entity[key]}`);
|
||||
try {
|
||||
const command = `UPDATE ${this._model} SET ${values.join(
|
||||
', ',
|
||||
)} WHERE uuid = '${uuid}'`;
|
||||
return await this._prisma.$executeRawUnsafe(command);
|
||||
} 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/matcher-repository.ts
Normal file
3
src/modules/database/src/domain/matcher-repository.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { PrismaRepository } from '../adapters/secondaries/prisma-repository.abstract';
|
||||
|
||||
export class MatcherRepository<T> extends PrismaRepository<T> {}
|
||||
4
src/modules/database/src/domain/point.type.ts
Normal file
4
src/modules/database/src/domain/point.type.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export type Point = {
|
||||
lon: number;
|
||||
lat: number;
|
||||
};
|
||||
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>;
|
||||
}
|
||||
571
src/modules/database/tests/unit/prisma-repository.spec.ts
Normal file
571
src/modules/database/tests/unit/prisma-repository.spec.ts
Normal file
@@ -0,0 +1,571 @@
|
||||
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]);
|
||||
}),
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
$queryRawUnsafe: jest.fn().mockImplementation((query?: string) => {
|
||||
return Promise.resolve(fakeEntities);
|
||||
}),
|
||||
$executeRawUnsafe: jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce(fakeEntityCreated)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.mockImplementationOnce((fields: object) => {
|
||||
throw new PrismaClientKnownRequestError('unknown request', {
|
||||
code: 'code',
|
||||
clientVersion: 'version',
|
||||
});
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.mockImplementationOnce((fields: object) => {
|
||||
throw new Error('an unknown error');
|
||||
})
|
||||
.mockResolvedValueOnce(fakeEntityCreated)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.mockImplementationOnce((fields: object) => {
|
||||
throw new PrismaClientKnownRequestError('unknown request', {
|
||||
code: 'code',
|
||||
clientVersion: 'version',
|
||||
});
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.mockImplementationOnce((fields: object) => {
|
||||
throw new Error('an unknown error');
|
||||
}),
|
||||
$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('findAllByquery', () => {
|
||||
it('should return an array of entities', async () => {
|
||||
const entities = await fakeRepository.findAllByQuery(
|
||||
['uuid', 'name'],
|
||||
['name is not null'],
|
||||
);
|
||||
expect(entities).toStrictEqual({
|
||||
data: fakeEntities,
|
||||
total: fakeEntities.length,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('createWithFields', () => {
|
||||
it('should create an entity', async () => {
|
||||
jest.spyOn(prisma, '$queryRawUnsafe');
|
||||
|
||||
const newEntity = await fakeRepository.createWithFields({
|
||||
uuid: '804319b3-a09b-4491-9f82-7976bfce0aff',
|
||||
name: 'my-name',
|
||||
});
|
||||
expect(newEntity).toBe(fakeEntityCreated);
|
||||
expect(prisma.$queryRawUnsafe).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should throw a DatabaseException for client error', async () => {
|
||||
await expect(
|
||||
fakeRepository.createWithFields({
|
||||
uuid: '804319b3-a09b-4491-9f82-7976bfce0aff',
|
||||
name: 'my-name',
|
||||
}),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
|
||||
it('should throw a DatabaseException if uuid is not found', async () => {
|
||||
await expect(
|
||||
fakeRepository.createWithFields({
|
||||
name: 'my-name',
|
||||
}),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateWithFields', () => {
|
||||
it('should update an entity', async () => {
|
||||
jest.spyOn(prisma, '$queryRawUnsafe');
|
||||
|
||||
const updatedEntity = await fakeRepository.updateWithFields(
|
||||
'804319b3-a09b-4491-9f82-7976bfce0aff',
|
||||
{
|
||||
name: 'my-name',
|
||||
},
|
||||
);
|
||||
expect(updatedEntity).toBe(fakeEntityCreated);
|
||||
expect(prisma.$queryRawUnsafe).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should throw a DatabaseException for client error', async () => {
|
||||
await expect(
|
||||
fakeRepository.updateWithFields(
|
||||
'804319b3-a09b-4491-9f82-7976bfce0aff',
|
||||
{
|
||||
name: 'my-name',
|
||||
},
|
||||
),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
|
||||
it('should throw a DatabaseException if uuid is not found', async () => {
|
||||
await expect(
|
||||
fakeRepository.updateWithFields(
|
||||
'804319b3-a09b-4491-9f82-7976bfce0aff',
|
||||
{
|
||||
name: 'my-name',
|
||||
},
|
||||
),
|
||||
).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,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
14
src/modules/utils/pipes/rpc.validation-pipe.ts
Normal file
14
src/modules/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),
|
||||
});
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { ArgumentMetadata } from '@nestjs/common';
|
||||
import { UpdateTerritoryRequest } from '../../../modules/territory/domain/dtos/update-territory.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: UpdateTerritoryRequest,
|
||||
data: '',
|
||||
};
|
||||
await target
|
||||
.transform(<UpdateTerritoryRequest>{}, metadata)
|
||||
.catch((err) => {
|
||||
expect(err.message).toEqual('Rpc Exception');
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user