mirror of
https://gitlab.com/mobicoop/v3/service/configuration.git
synced 2026-01-09 16:32:40 +00:00
add configuration module
This commit is contained in:
@@ -1,22 +0,0 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
describe('AppController', () => {
|
||||
let appController: AppController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const app: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
}).compile();
|
||||
|
||||
appController = app.get<AppController>(AppController);
|
||||
});
|
||||
|
||||
describe('root', () => {
|
||||
it('should return "Hello World!"', () => {
|
||||
expect(appController.getHello()).toBe('Hello World!');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,12 +0,0 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
@Controller()
|
||||
export class AppController {
|
||||
constructor(private readonly appService: AppService) {}
|
||||
|
||||
@Get()
|
||||
getHello(): string {
|
||||
return this.appService.getHello();
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,16 @@
|
||||
import { classes } from '@automapper/classes';
|
||||
import { AutomapperModule } from '@automapper/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { ConfigurationModule } from './modules/configuration/configuration.module';
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true }),
|
||||
AutomapperModule.forRoot({ strategyInitializer: classes() }),
|
||||
ConfigurationModule,
|
||||
],
|
||||
controllers: [],
|
||||
providers: [],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@Injectable()
|
||||
export class AppService {
|
||||
getHello(): string {
|
||||
return 'Hello World!';
|
||||
}
|
||||
}
|
||||
20
src/main.ts
20
src/main.ts
@@ -1,8 +1,24 @@
|
||||
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);
|
||||
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
|
||||
AppModule,
|
||||
{
|
||||
transport: Transport.GRPC,
|
||||
options: {
|
||||
package: 'configuration',
|
||||
protoPath: join(
|
||||
__dirname,
|
||||
'modules/configuration/adapters/primaries/configuration.proto',
|
||||
),
|
||||
url: process.env.SERVICE_URL + ':' + process.env.SERVICE_PORT,
|
||||
loader: { keepCase: true },
|
||||
},
|
||||
},
|
||||
);
|
||||
await app.listen();
|
||||
}
|
||||
bootstrap();
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { Mapper } from '@automapper/core';
|
||||
import { InjectMapper } from '@automapper/nestjs';
|
||||
import { Controller, UsePipes } from '@nestjs/common';
|
||||
import { CommandBus, QueryBus } from '@nestjs/cqrs';
|
||||
import { GrpcMethod, RpcException } from '@nestjs/microservices';
|
||||
import { DatabaseException } from 'src/modules/database/src/exceptions/database.exception';
|
||||
import { ICollection } from 'src/modules/database/src/interfaces/collection.interface';
|
||||
import { RpcValidationPipe } from 'src/utils/pipes/rpc.validation-pipe';
|
||||
import { CreateConfigurationCommand } from '../../commands/create-configuration.command';
|
||||
import { DeleteConfigurationCommand } from '../../commands/delete-configuration.command';
|
||||
import { UpdateConfigurationCommand } from '../../commands/update-configuration.command';
|
||||
import { CreateConfigurationRequest } from '../../domain/dtos/create-configuration.request';
|
||||
import { FindAllConfigurationsRequest } from '../../domain/dtos/find-all-configurations.request';
|
||||
import { FindConfigurationByUuidRequest } from '../../domain/dtos/find-configuration-by-uuid.request';
|
||||
import { UpdateConfigurationRequest } from '../../domain/dtos/update-configuration.request';
|
||||
import { Configuration } from '../../domain/entities/configuration';
|
||||
import { FindAllConfigurationsQuery } from '../../queries/find-all-configurations.query';
|
||||
import { FindConfigurationByUuidQuery } from '../../queries/find-configuration-by-uuid.query';
|
||||
import { ConfigurationPresenter } from './configuration.presenter';
|
||||
|
||||
@UsePipes(
|
||||
new RpcValidationPipe({
|
||||
whitelist: true,
|
||||
forbidUnknownValues: false,
|
||||
}),
|
||||
)
|
||||
@Controller()
|
||||
export class ConfigurationController {
|
||||
constructor(
|
||||
private readonly _commandBus: CommandBus,
|
||||
private readonly _queryBus: QueryBus,
|
||||
@InjectMapper() private readonly _mapper: Mapper,
|
||||
) {}
|
||||
|
||||
@GrpcMethod('ConfigurationService', 'FindAll')
|
||||
async findAll(
|
||||
data: FindAllConfigurationsRequest,
|
||||
): Promise<ICollection<Configuration>> {
|
||||
const configurationCollection = await this._queryBus.execute(
|
||||
new FindAllConfigurationsQuery(data),
|
||||
);
|
||||
return Promise.resolve({
|
||||
data: configurationCollection.data.map((configuration: Configuration) =>
|
||||
this._mapper.map(configuration, Configuration, ConfigurationPresenter),
|
||||
),
|
||||
total: configurationCollection.total,
|
||||
});
|
||||
}
|
||||
|
||||
@GrpcMethod('ConfigurationService', 'FindOneByUuid')
|
||||
async findOneByUuid(
|
||||
data: FindConfigurationByUuidRequest,
|
||||
): Promise<ConfigurationPresenter> {
|
||||
try {
|
||||
const configuration = await this._queryBus.execute(
|
||||
new FindConfigurationByUuidQuery(data),
|
||||
);
|
||||
return this._mapper.map(
|
||||
configuration,
|
||||
Configuration,
|
||||
ConfigurationPresenter,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new RpcException({
|
||||
code: 5,
|
||||
message: 'Configuration not found',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@GrpcMethod('ConfigurationService', 'Create')
|
||||
async createConfiguration(
|
||||
data: CreateConfigurationRequest,
|
||||
): Promise<ConfigurationPresenter> {
|
||||
try {
|
||||
const configuration = await this._commandBus.execute(
|
||||
new CreateConfigurationCommand(data),
|
||||
);
|
||||
return this._mapper.map(
|
||||
configuration,
|
||||
Configuration,
|
||||
ConfigurationPresenter,
|
||||
);
|
||||
} catch (e) {
|
||||
if (e instanceof DatabaseException) {
|
||||
if (e.message.includes('Already exists')) {
|
||||
throw new RpcException({
|
||||
code: 6,
|
||||
message: 'Configuration already exists',
|
||||
});
|
||||
}
|
||||
}
|
||||
throw new RpcException({});
|
||||
}
|
||||
}
|
||||
|
||||
@GrpcMethod('ConfigurationService', 'Update')
|
||||
async updateConfiguration(
|
||||
data: UpdateConfigurationRequest,
|
||||
): Promise<ConfigurationPresenter> {
|
||||
try {
|
||||
const configuration = await this._commandBus.execute(
|
||||
new UpdateConfigurationCommand(data),
|
||||
);
|
||||
|
||||
return this._mapper.map(
|
||||
configuration,
|
||||
Configuration,
|
||||
ConfigurationPresenter,
|
||||
);
|
||||
} catch (e) {
|
||||
if (e instanceof DatabaseException) {
|
||||
if (e.message.includes('not found')) {
|
||||
throw new RpcException({
|
||||
code: 5,
|
||||
message: 'Configuration not found',
|
||||
});
|
||||
}
|
||||
}
|
||||
throw new RpcException({});
|
||||
}
|
||||
}
|
||||
|
||||
@GrpcMethod('ConfigurationService', 'Delete')
|
||||
async deleteConfiguration(
|
||||
data: FindConfigurationByUuidRequest,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this._commandBus.execute(new DeleteConfigurationCommand(data.uuid));
|
||||
|
||||
return Promise.resolve();
|
||||
} catch (e) {
|
||||
if (e instanceof DatabaseException) {
|
||||
if (e.message.includes('not found')) {
|
||||
throw new RpcException({
|
||||
code: 5,
|
||||
message: 'Configuration not found',
|
||||
});
|
||||
}
|
||||
}
|
||||
throw new RpcException({});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { AutoMap } from '@automapper/classes';
|
||||
|
||||
export class ConfigurationPresenter {
|
||||
@AutoMap()
|
||||
value: string;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package configuration;
|
||||
|
||||
service ConfigurationService {
|
||||
rpc FindOneByUuid(ConfigurationByUuid) returns (Configuration);
|
||||
rpc FindAll(ConfigurationFilter) returns (Configurations);
|
||||
rpc Create(Configuration) returns (Configuration);
|
||||
rpc Update(Configuration) returns (Configuration);
|
||||
rpc Delete(ConfigurationByUuid) returns (Empty);
|
||||
}
|
||||
|
||||
message ConfigurationByUuid {
|
||||
string uuid = 1;
|
||||
}
|
||||
|
||||
message Configuration {
|
||||
string uuid = 1;
|
||||
Domain domain = 2;
|
||||
string key = 3;
|
||||
string value = 4;
|
||||
}
|
||||
|
||||
enum Domain {
|
||||
user = 0;
|
||||
}
|
||||
|
||||
message ConfigurationFilter {
|
||||
optional int32 page = 1;
|
||||
optional int32 perPage = 2;
|
||||
}
|
||||
|
||||
message Configurations {
|
||||
repeated Configuration data = 1;
|
||||
int32 total = 2;
|
||||
}
|
||||
|
||||
message Empty {}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigRepository } from '../../../database/src/domain/configuration.repository';
|
||||
import { Configuration } from '../../domain/entities/configuration';
|
||||
|
||||
@Injectable()
|
||||
export class ConfigurationRepository extends ConfigRepository<Configuration> {
|
||||
protected _model = 'configuration';
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { CreateConfigurationRequest } from '../domain/dtos/create-configuration.request';
|
||||
|
||||
export class CreateConfigurationCommand {
|
||||
readonly createConfigurationRequest: CreateConfigurationRequest;
|
||||
|
||||
constructor(request: CreateConfigurationRequest) {
|
||||
this.createConfigurationRequest = request;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export class DeleteConfigurationCommand {
|
||||
readonly uuid: string;
|
||||
|
||||
constructor(uuid: string) {
|
||||
this.uuid = uuid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { UpdateConfigurationRequest } from '../domain/dtos/update-configuration.request';
|
||||
|
||||
export class UpdateConfigurationCommand {
|
||||
readonly updateConfigurationRequest: UpdateConfigurationRequest;
|
||||
|
||||
constructor(request: UpdateConfigurationRequest) {
|
||||
this.updateConfigurationRequest = request;
|
||||
}
|
||||
}
|
||||
14
src/modules/configuration/configuration.module.ts
Normal file
14
src/modules/configuration/configuration.module.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CqrsModule } from '@nestjs/cqrs';
|
||||
import { DatabaseModule } from '../database/database.module';
|
||||
import { ConfigRepository } from '../database/src/domain/configuration.repository';
|
||||
import { ConfigurationController } from './adapters/primaries/configuration.controller';
|
||||
import { ConfigurationProfile } from './mappers/configuration.profile';
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, CqrsModule],
|
||||
exports: [],
|
||||
controllers: [ConfigurationController],
|
||||
providers: [ConfigurationProfile, ConfigRepository],
|
||||
})
|
||||
export class ConfigurationModule {}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { AutoMap } from '@automapper/classes';
|
||||
import { IsEmail, IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
import { Domain } from './domain.enum';
|
||||
|
||||
export class CreateConfigurationRequest {
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@AutoMap()
|
||||
uuid?: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@AutoMap()
|
||||
domain: Domain;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@AutoMap()
|
||||
key: string;
|
||||
|
||||
@IsEmail()
|
||||
@IsNotEmpty()
|
||||
@AutoMap()
|
||||
value: string;
|
||||
}
|
||||
3
src/modules/configuration/domain/dtos/domain.enum.ts
Normal file
3
src/modules/configuration/domain/dtos/domain.enum.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export enum Domain {
|
||||
user = 'user',
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { IsInt, IsOptional } from 'class-validator';
|
||||
|
||||
export class FindAllConfigurationsRequest {
|
||||
@IsInt()
|
||||
@IsOptional()
|
||||
page?: number;
|
||||
|
||||
@IsInt()
|
||||
@IsOptional()
|
||||
perPage?: number;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class FindConfigurationByUuidRequest {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
uuid: string;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { AutoMap } from '@automapper/classes';
|
||||
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
import { Domain } from './domain.enum';
|
||||
|
||||
export class UpdateConfigurationRequest {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@AutoMap()
|
||||
uuid: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@AutoMap()
|
||||
domain?: Domain;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@AutoMap()
|
||||
key?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
@AutoMap()
|
||||
value?: string;
|
||||
}
|
||||
16
src/modules/configuration/domain/entities/configuration.ts
Normal file
16
src/modules/configuration/domain/entities/configuration.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { AutoMap } from '@automapper/classes';
|
||||
import { Domain } from '../dtos/domain.enum';
|
||||
|
||||
export class Configuration {
|
||||
@AutoMap()
|
||||
uuid: string;
|
||||
|
||||
@AutoMap()
|
||||
domain: Domain;
|
||||
|
||||
@AutoMap()
|
||||
key: string;
|
||||
|
||||
@AutoMap()
|
||||
value: string;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Mapper } from '@automapper/core';
|
||||
import { InjectMapper } from '@automapper/nestjs';
|
||||
import { CommandHandler } from '@nestjs/cqrs';
|
||||
import { ConfigurationRepository } from '../../adapters/secondaries/configuration.repository';
|
||||
import { CreateConfigurationCommand } from '../../commands/create-configuration.command';
|
||||
import { CreateConfigurationRequest } from '../dtos/create-configuration.request';
|
||||
import { Configuration } from '../entities/configuration';
|
||||
|
||||
@CommandHandler(CreateConfigurationCommand)
|
||||
export class CreateConfigurationUseCase {
|
||||
constructor(
|
||||
private readonly _repository: ConfigurationRepository,
|
||||
@InjectMapper() private readonly _mapper: Mapper,
|
||||
) {}
|
||||
|
||||
async execute(command: CreateConfigurationCommand): Promise<Configuration> {
|
||||
const entity = this._mapper.map(
|
||||
command.createConfigurationRequest,
|
||||
CreateConfigurationRequest,
|
||||
Configuration,
|
||||
);
|
||||
|
||||
try {
|
||||
const configuration = await this._repository.create(entity);
|
||||
return configuration;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { CommandHandler } from '@nestjs/cqrs';
|
||||
import { ConfigurationRepository } from '../../adapters/secondaries/configuration.repository';
|
||||
import { DeleteConfigurationCommand } from '../../commands/delete-configuration.command';
|
||||
import { Configuration } from '../entities/configuration';
|
||||
|
||||
@CommandHandler(DeleteConfigurationCommand)
|
||||
export class DeleteConfigurationUseCase {
|
||||
constructor(private readonly _repository: ConfigurationRepository) {}
|
||||
|
||||
async execute(command: DeleteConfigurationCommand): Promise<Configuration> {
|
||||
try {
|
||||
const configuration = await this._repository.delete(command.uuid);
|
||||
return configuration;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { QueryHandler } from '@nestjs/cqrs';
|
||||
import { ICollection } from 'src/modules/database/src/interfaces/collection.interface';
|
||||
import { ConfigurationRepository } from '../../adapters/secondaries/configuration.repository';
|
||||
import { FindAllConfigurationsQuery } from '../../queries/find-all-configurations.query';
|
||||
import { Configuration } from '../entities/configuration';
|
||||
|
||||
@QueryHandler(FindAllConfigurationsQuery)
|
||||
export class FindAllConfigurationsUseCase {
|
||||
constructor(private readonly _repository: ConfigurationRepository) {}
|
||||
|
||||
async execute(
|
||||
findAllConfigurationsQuery: FindAllConfigurationsQuery,
|
||||
): Promise<ICollection<Configuration>> {
|
||||
return this._repository.findAll(
|
||||
findAllConfigurationsQuery.page,
|
||||
findAllConfigurationsQuery.perPage,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { QueryHandler } from '@nestjs/cqrs';
|
||||
import { ConfigurationRepository } from '../../adapters/secondaries/configuration.repository';
|
||||
import { FindConfigurationByUuidQuery } from '../../queries/find-configuration-by-uuid.query';
|
||||
import { Configuration } from '../entities/configuration';
|
||||
|
||||
@QueryHandler(FindConfigurationByUuidQuery)
|
||||
export class FindConfigurationByUuidUseCase {
|
||||
constructor(private readonly _repository: ConfigurationRepository) {}
|
||||
|
||||
async execute(
|
||||
findConfigurationByUuid: FindConfigurationByUuidQuery,
|
||||
): Promise<Configuration> {
|
||||
try {
|
||||
const configuration = await this._repository.findOneByUuid(
|
||||
findConfigurationByUuid.uuid,
|
||||
);
|
||||
if (!configuration) throw new NotFoundException();
|
||||
return configuration;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Mapper } from '@automapper/core';
|
||||
import { InjectMapper } from '@automapper/nestjs';
|
||||
import { CommandHandler } from '@nestjs/cqrs';
|
||||
import { ConfigurationRepository } from '../../adapters/secondaries/configuration.repository';
|
||||
import { UpdateConfigurationCommand } from '../../commands/update-configuration.command';
|
||||
import { UpdateConfigurationRequest } from '../dtos/update-configuration.request';
|
||||
import { Configuration } from '../entities/configuration';
|
||||
|
||||
@CommandHandler(UpdateConfigurationCommand)
|
||||
export class UpdateConfigurationUseCase {
|
||||
constructor(
|
||||
private readonly _repository: ConfigurationRepository,
|
||||
@InjectMapper() private readonly _mapper: Mapper,
|
||||
) {}
|
||||
|
||||
async execute(command: UpdateConfigurationCommand): Promise<Configuration> {
|
||||
const entity = this._mapper.map(
|
||||
command.updateConfigurationRequest,
|
||||
UpdateConfigurationRequest,
|
||||
Configuration,
|
||||
);
|
||||
|
||||
try {
|
||||
const configuration = await this._repository.update(
|
||||
command.updateConfigurationRequest.uuid,
|
||||
entity,
|
||||
);
|
||||
return configuration;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
29
src/modules/configuration/mappers/configuration.profile.ts
Normal file
29
src/modules/configuration/mappers/configuration.profile.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { createMap, forMember, ignore, Mapper } from '@automapper/core';
|
||||
import { AutomapperProfile, InjectMapper } from '@automapper/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigurationPresenter } from '../adapters/primaries/configuration.presenter';
|
||||
import { CreateConfigurationRequest } from '../domain/dtos/create-configuration.request';
|
||||
import { UpdateConfigurationRequest } from '../domain/dtos/update-configuration.request';
|
||||
import { Configuration } from '../domain/entities/configuration';
|
||||
|
||||
@Injectable()
|
||||
export class ConfigurationProfile extends AutomapperProfile {
|
||||
constructor(@InjectMapper() mapper: Mapper) {
|
||||
super(mapper);
|
||||
}
|
||||
|
||||
override get profile() {
|
||||
return (mapper: any) => {
|
||||
createMap(mapper, Configuration, ConfigurationPresenter);
|
||||
|
||||
createMap(mapper, CreateConfigurationRequest, Configuration);
|
||||
|
||||
createMap(
|
||||
mapper,
|
||||
UpdateConfigurationRequest,
|
||||
Configuration,
|
||||
forMember((dest) => dest.uuid, ignore()),
|
||||
);
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { FindAllConfigurationsRequest } from '../domain/dtos/find-all-configurations.request';
|
||||
|
||||
export class FindAllConfigurationsQuery {
|
||||
page: number;
|
||||
perPage: number;
|
||||
|
||||
constructor(findAllConfigurationsRequest?: FindAllConfigurationsRequest) {
|
||||
this.page = findAllConfigurationsRequest?.page ?? 1;
|
||||
this.perPage = findAllConfigurationsRequest?.perPage ?? 10;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { FindConfigurationByUuidRequest } from '../domain/dtos/find-configuration-by-uuid.request';
|
||||
|
||||
export class FindConfigurationByUuidQuery {
|
||||
readonly uuid: string;
|
||||
|
||||
constructor(findConfigurationByUuidRequest: FindConfigurationByUuidRequest) {
|
||||
this.uuid = findConfigurationByUuidRequest.uuid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { classes } from '@automapper/classes';
|
||||
import { AutomapperModule } from '@automapper/nestjs';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ConfigurationRepository } from '../../adapters/secondaries/configuration.repository';
|
||||
import { CreateConfigurationCommand } from '../../commands/create-configuration.command';
|
||||
import { CreateConfigurationRequest } from '../../domain/dtos/create-configuration.request';
|
||||
import { Domain } from '../../domain/dtos/domain.enum';
|
||||
import { Configuration } from '../../domain/entities/configuration';
|
||||
import { CreateConfigurationUseCase } from '../../domain/usecases/create-configuration.usecase';
|
||||
import { ConfigurationProfile } from '../../mappers/configuration.profile';
|
||||
|
||||
const newConfigurationRequest: CreateConfigurationRequest = {
|
||||
domain: Domain.user,
|
||||
key: 'minAge',
|
||||
value: '16',
|
||||
};
|
||||
const newConfigurationCommand: CreateConfigurationCommand =
|
||||
new CreateConfigurationCommand(newConfigurationRequest);
|
||||
|
||||
const mockConfigurationRepository = {
|
||||
create: jest
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
return Promise.resolve({
|
||||
...newConfigurationRequest,
|
||||
uuid: 'bb281075-1b98-4456-89d6-c643d3044a91',
|
||||
});
|
||||
})
|
||||
.mockImplementation(() => {
|
||||
throw new Error('Already exists');
|
||||
}),
|
||||
};
|
||||
|
||||
describe('CreateConfigurationUseCase', () => {
|
||||
let createConfigurationUseCase: CreateConfigurationUseCase;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [AutomapperModule.forRoot({ strategyInitializer: classes() })],
|
||||
providers: [
|
||||
{
|
||||
provide: ConfigurationRepository,
|
||||
useValue: mockConfigurationRepository,
|
||||
},
|
||||
CreateConfigurationUseCase,
|
||||
ConfigurationProfile,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
createConfigurationUseCase = module.get<CreateConfigurationUseCase>(
|
||||
CreateConfigurationUseCase,
|
||||
);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(createConfigurationUseCase).toBeDefined();
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should create and return a new configuration', async () => {
|
||||
const newConfiguration: Configuration =
|
||||
await createConfigurationUseCase.execute(newConfigurationCommand);
|
||||
|
||||
expect(newConfiguration.key).toBe(newConfigurationRequest.key);
|
||||
expect(newConfiguration.uuid).toBeDefined();
|
||||
});
|
||||
|
||||
it('should throw an error if configuration already exists', async () => {
|
||||
await expect(
|
||||
createConfigurationUseCase.execute(newConfigurationCommand),
|
||||
).rejects.toBeInstanceOf(Error);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ConfigurationRepository } from '../../adapters/secondaries/configuration.repository';
|
||||
import { DeleteConfigurationCommand } from '../../commands/delete-configuration.command';
|
||||
import { Domain } from '../../domain/dtos/domain.enum';
|
||||
import { DeleteConfigurationUseCase } from '../../domain/usecases/delete-configuration.usecase';
|
||||
|
||||
const mockConfigurations = [
|
||||
{
|
||||
uuid: 'bb281075-1b98-4456-89d6-c643d3044a91',
|
||||
domain: Domain.user,
|
||||
key: 'key1',
|
||||
value: 'value1',
|
||||
},
|
||||
{
|
||||
uuid: 'bb281075-1b98-4456-89d6-c643d3044a92',
|
||||
domain: Domain.user,
|
||||
key: 'key2',
|
||||
value: 'value2',
|
||||
},
|
||||
{
|
||||
uuid: 'bb281075-1b98-4456-89d6-c643d3044a93',
|
||||
domain: Domain.user,
|
||||
key: 'key3',
|
||||
value: 'value3',
|
||||
},
|
||||
];
|
||||
|
||||
const mockConfigurationRepository = {
|
||||
delete: jest
|
||||
.fn()
|
||||
.mockImplementationOnce((uuid: string) => {
|
||||
let savedConfiguration = {};
|
||||
mockConfigurations.forEach((configuration, index) => {
|
||||
if (configuration.uuid === uuid) {
|
||||
savedConfiguration = { ...configuration };
|
||||
mockConfigurations.splice(index, 1);
|
||||
}
|
||||
});
|
||||
return savedConfiguration;
|
||||
})
|
||||
.mockImplementation(() => {
|
||||
throw new Error('Error');
|
||||
}),
|
||||
};
|
||||
|
||||
describe('DeleteConfigurationUseCase', () => {
|
||||
let deleteConfigurationUseCase: DeleteConfigurationUseCase;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: ConfigurationRepository,
|
||||
useValue: mockConfigurationRepository,
|
||||
},
|
||||
DeleteConfigurationUseCase,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
deleteConfigurationUseCase = module.get<DeleteConfigurationUseCase>(
|
||||
DeleteConfigurationUseCase,
|
||||
);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(deleteConfigurationUseCase).toBeDefined();
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should delete a configuration', async () => {
|
||||
const savedUuid = mockConfigurations[0].uuid;
|
||||
const deleteConfigurationCommand = new DeleteConfigurationCommand(
|
||||
savedUuid,
|
||||
);
|
||||
await deleteConfigurationUseCase.execute(deleteConfigurationCommand);
|
||||
|
||||
const deletedConfiguration = mockConfigurations.find(
|
||||
(configuration) => configuration.uuid === savedUuid,
|
||||
);
|
||||
expect(deletedConfiguration).toBeUndefined();
|
||||
});
|
||||
it('should throw an error if configuration does not exist', async () => {
|
||||
await expect(
|
||||
deleteConfigurationUseCase.execute(
|
||||
new DeleteConfigurationCommand('wrong uuid'),
|
||||
),
|
||||
).rejects.toBeInstanceOf(Error);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ConfigurationRepository } from '../../adapters/secondaries/configuration.repository';
|
||||
import { Domain } from '../../domain/dtos/domain.enum';
|
||||
import { FindAllConfigurationsRequest } from '../../domain/dtos/find-all-configurations.request';
|
||||
import { FindAllConfigurationsUseCase } from '../../domain/usecases/find-all-configurations.usecase';
|
||||
import { FindAllConfigurationsQuery } from '../../queries/find-all-configurations.query';
|
||||
|
||||
const findAllConfigurationsRequest: FindAllConfigurationsRequest =
|
||||
new FindAllConfigurationsRequest();
|
||||
findAllConfigurationsRequest.page = 1;
|
||||
findAllConfigurationsRequest.perPage = 10;
|
||||
|
||||
const findAllConfigurationsQuery: FindAllConfigurationsQuery =
|
||||
new FindAllConfigurationsQuery(findAllConfigurationsRequest);
|
||||
|
||||
const mockConfigurations = [
|
||||
{
|
||||
uuid: 'bb281075-1b98-4456-89d6-c643d3044a91',
|
||||
domain: Domain.user,
|
||||
key: 'key1',
|
||||
value: 'value1',
|
||||
},
|
||||
{
|
||||
uuid: 'bb281075-1b98-4456-89d6-c643d3044a92',
|
||||
domain: Domain.user,
|
||||
key: 'key2',
|
||||
value: 'value2',
|
||||
},
|
||||
{
|
||||
uuid: 'bb281075-1b98-4456-89d6-c643d3044a93',
|
||||
domain: Domain.user,
|
||||
key: 'key3',
|
||||
value: 'value3',
|
||||
},
|
||||
];
|
||||
|
||||
const mockConfigurationRepository = {
|
||||
findAll: jest
|
||||
.fn()
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.mockImplementation((query?: FindAllConfigurationsQuery) => {
|
||||
return Promise.resolve(mockConfigurations);
|
||||
}),
|
||||
};
|
||||
|
||||
describe('FindAllConfigurationsUseCase', () => {
|
||||
let findAllConfigurationsUseCase: FindAllConfigurationsUseCase;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: ConfigurationRepository,
|
||||
useValue: mockConfigurationRepository,
|
||||
},
|
||||
FindAllConfigurationsUseCase,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
findAllConfigurationsUseCase = module.get<FindAllConfigurationsUseCase>(
|
||||
FindAllConfigurationsUseCase,
|
||||
);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(findAllConfigurationsUseCase).toBeDefined();
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should return an array filled with configurations', async () => {
|
||||
const configurations = await findAllConfigurationsUseCase.execute(
|
||||
findAllConfigurationsQuery,
|
||||
);
|
||||
|
||||
expect(configurations).toBe(mockConfigurations);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ConfigurationRepository } from '../../adapters/secondaries/configuration.repository';
|
||||
import { Domain } from '../../domain/dtos/domain.enum';
|
||||
import { FindConfigurationByUuidRequest } from '../../domain/dtos/find-configuration-by-uuid.request';
|
||||
import { FindConfigurationByUuidUseCase } from '../../domain/usecases/find-configuration-by-uuid.usecase';
|
||||
import { FindConfigurationByUuidQuery } from '../../queries/find-configuration-by-uuid.query';
|
||||
|
||||
const mockConfiguration = {
|
||||
uuid: 'bb281075-1b98-4456-89d6-c643d3044a91',
|
||||
domain: Domain.user,
|
||||
key: 'key1',
|
||||
value: 'value1',
|
||||
};
|
||||
|
||||
const mockConfigurationRepository = {
|
||||
findOneByUuid: jest
|
||||
.fn()
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
.mockImplementationOnce((query?: FindConfigurationByUuidQuery) => {
|
||||
return Promise.resolve(mockConfiguration);
|
||||
})
|
||||
.mockImplementation(() => {
|
||||
return Promise.resolve(undefined);
|
||||
}),
|
||||
};
|
||||
|
||||
describe('FindConfigurationByUuidUseCase', () => {
|
||||
let findConfigurationByUuidUseCase: FindConfigurationByUuidUseCase;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [],
|
||||
providers: [
|
||||
{
|
||||
provide: ConfigurationRepository,
|
||||
useValue: mockConfigurationRepository,
|
||||
},
|
||||
FindConfigurationByUuidUseCase,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
findConfigurationByUuidUseCase = module.get<FindConfigurationByUuidUseCase>(
|
||||
FindConfigurationByUuidUseCase,
|
||||
);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(findConfigurationByUuidUseCase).toBeDefined();
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should return a Configuration', async () => {
|
||||
const findConfigurationByUuidRequest: FindConfigurationByUuidRequest =
|
||||
new FindConfigurationByUuidRequest();
|
||||
findConfigurationByUuidRequest.uuid =
|
||||
'bb281075-1b98-4456-89d6-c643d3044a91';
|
||||
const Configuration = await findConfigurationByUuidUseCase.execute(
|
||||
new FindConfigurationByUuidQuery(findConfigurationByUuidRequest),
|
||||
);
|
||||
expect(Configuration).toBe(mockConfiguration);
|
||||
});
|
||||
it('should throw an error if Configuration does not exist', async () => {
|
||||
const findConfigurationByUuidRequest: FindConfigurationByUuidRequest =
|
||||
new FindConfigurationByUuidRequest();
|
||||
findConfigurationByUuidRequest.uuid =
|
||||
'bb281075-1b98-4456-89d6-c643d3044a90';
|
||||
await expect(
|
||||
findConfigurationByUuidUseCase.execute(
|
||||
new FindConfigurationByUuidQuery(findConfigurationByUuidRequest),
|
||||
),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { classes } from '@automapper/classes';
|
||||
import { AutomapperModule } from '@automapper/nestjs';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { ConfigurationRepository } from '../../adapters/secondaries/configuration.repository';
|
||||
import { UpdateConfigurationCommand } from '../../commands/update-configuration.command';
|
||||
import { UpdateConfigurationRequest } from '../../domain/dtos/update-configuration.request';
|
||||
import { Configuration } from '../../domain/entities/configuration';
|
||||
import { UpdateConfigurationUseCase } from '../../domain/usecases/update-configuration.usecase';
|
||||
import { ConfigurationProfile } from '../../mappers/configuration.profile';
|
||||
|
||||
const originalConfiguration: Configuration = new Configuration();
|
||||
originalConfiguration.uuid = 'bb281075-1b98-4456-89d6-c643d3044a91';
|
||||
originalConfiguration.key = 'key1';
|
||||
|
||||
const updateConfigurationRequest: UpdateConfigurationRequest = {
|
||||
uuid: 'bb281075-1b98-4456-89d6-c643d3044a91',
|
||||
key: 'Dane',
|
||||
};
|
||||
|
||||
const updateConfigurationCommand: UpdateConfigurationCommand =
|
||||
new UpdateConfigurationCommand(updateConfigurationRequest);
|
||||
|
||||
const mockConfigurationRepository = {
|
||||
update: jest
|
||||
.fn()
|
||||
.mockImplementationOnce((uuid: string, params: any) => {
|
||||
originalConfiguration.key = params.key;
|
||||
|
||||
return Promise.resolve(originalConfiguration);
|
||||
})
|
||||
.mockImplementation(() => {
|
||||
throw new Error('Error');
|
||||
}),
|
||||
};
|
||||
|
||||
describe('UpdateConfigurationUseCase', () => {
|
||||
let updateConfigurationUseCase: UpdateConfigurationUseCase;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [AutomapperModule.forRoot({ strategyInitializer: classes() })],
|
||||
|
||||
providers: [
|
||||
{
|
||||
provide: ConfigurationRepository,
|
||||
useValue: mockConfigurationRepository,
|
||||
},
|
||||
UpdateConfigurationUseCase,
|
||||
ConfigurationProfile,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
updateConfigurationUseCase = module.get<UpdateConfigurationUseCase>(
|
||||
UpdateConfigurationUseCase,
|
||||
);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(updateConfigurationUseCase).toBeDefined();
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should update a configuration', async () => {
|
||||
const updatedConfiguration: Configuration =
|
||||
await updateConfigurationUseCase.execute(updateConfigurationCommand);
|
||||
|
||||
expect(updatedConfiguration.key).toBe(updateConfigurationRequest.key);
|
||||
});
|
||||
it('should throw an error if configuration does not exist', async () => {
|
||||
await expect(
|
||||
updateConfigurationUseCase.execute(updateConfigurationCommand),
|
||||
).rejects.toBeInstanceOf(Error);
|
||||
});
|
||||
});
|
||||
});
|
||||
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 { ConfigRepository } from './src/domain/configuration.repository';
|
||||
|
||||
@Module({
|
||||
providers: [PrismaService, ConfigRepository],
|
||||
exports: [PrismaService, ConfigRepository],
|
||||
})
|
||||
export class DatabaseModule {}
|
||||
@@ -0,0 +1,163 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { PrismaRepository } from '../adapters/secondaries/prisma-repository.abstract';
|
||||
|
||||
export class ConfigRepository<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;
|
||||
}
|
||||
16
src/modules/database/src/interfaces/repository.interface.ts
Normal file
16
src/modules/database/src/interfaces/repository.interface.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
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>;
|
||||
}
|
||||
244
src/modules/database/tests/unit/prisma-repository.spec.ts
Normal file
244
src/modules/database/tests/unit/prisma-repository.spec.ts
Normal file
@@ -0,0 +1,244 @@
|
||||
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';
|
||||
|
||||
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]);
|
||||
}),
|
||||
fake: {
|
||||
create: jest.fn().mockResolvedValue(fakeEntityCreated),
|
||||
|
||||
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) {
|
||||
throw new Error('no entity');
|
||||
}
|
||||
|
||||
return entity;
|
||||
}),
|
||||
|
||||
findFirst: jest.fn().mockImplementation((params?: any) => {
|
||||
if (params?.where?.name) {
|
||||
return Promise.resolve(
|
||||
fakeEntities.find((entity) => entity.name === params?.where?.name),
|
||||
);
|
||||
}
|
||||
}),
|
||||
|
||||
update: jest.fn().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().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);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findOne', () => {
|
||||
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 if uuid is not found', async () => {
|
||||
await expect(
|
||||
fakeRepository.findOneByUuid('wrong-uuid'),
|
||||
).rejects.toBeInstanceOf(DatabaseException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('update', () => {
|
||||
it('should update an entity', 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);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
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('findOne', () => {
|
||||
it('should find one entity', async () => {
|
||||
const entity = await fakeRepository.findOne({
|
||||
name: fakeEntities[0].name,
|
||||
});
|
||||
|
||||
expect(entity.name).toBe(fakeEntities[0].name);
|
||||
});
|
||||
});
|
||||
});
|
||||
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),
|
||||
});
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user