crate/update/validate auth

This commit is contained in:
Gsk54 2022-12-16 16:46:14 +01:00
parent d74f720280
commit 03d718036d
40 changed files with 2353 additions and 129 deletions

22
.env Normal file
View File

@ -0,0 +1,22 @@
# SERVICE
SERVICE_CONTAINER=v3-auth
SERVICE_URL=0.0.0.0
SERVICE_PORT=5002
# PRISMA
DATABASE_URL="postgresql://auth:auth@v3-auth-db:5432/auth?schema=public"
# POSTGRES
POSTGRES_CONTAINER=v3-auth-db
POSTGRES_IMAGE=postgres:15.0
POSTGRES_DB=auth
POSTGRES_PASSWORD=auth
POSTGRES_USER=auth
POSTGRES_PORT=5402
# PGADMIN
PGADMIN_CONTAINER=v3-auth-pgadmin
PGADMIN_IMAGE=dpage/pgadmin4:6.12
PGADMIN_EMAIL=it@mobicoop.org
PGADMIN_PASSWORD=auth
PGADMIN_PORT=8402

View File

@ -1,22 +1,22 @@
# SERVICE
SERVICE_CONTAINER=v3_user
SERVICE_PORT=3001
SERVICE_URL=localhost:3001
SERVICE_CONTAINER=v3-auth
SERVICE_URL=0.0.0.0
SERVICE_PORT=5002
# PRISMA
DATABASE_URL="postgresql://user:user@db:5432/user?schema=public"
DATABASE_URL="postgresql://auth:auth@db:5432/auth?schema=public"
# POSTGRES
POSTGRES_CONTAINER=v3_user_db
POSTGRES_CONTAINER=v3-auth-db
POSTGRES_IMAGE=postgres:15.0
POSTGRES_DB=user
POSTGRES_PASSWORD=user
POSTGRES_USER=user
POSTGRES_PORT=5401
POSTGRES_DB=auth
POSTGRES_PASSWORD=auth
POSTGRES_USER=auth
POSTGRES_PORT=5402
# PGADMIN
PGADMIN_CONTAINER=v3_user_pgadmin
PGADMIN_CONTAINER=v3-auth-pgadmin
PGADMIN_IMAGE=dpage/pgadmin4:6.12
PGADMIN_EMAIL=it@mobicoop.org
PGADMIN_PASSWORD=user
PGADMIN_PORT=8401
PGADMIN_PASSWORD=auth
PGADMIN_PORT=8402

View File

@ -20,7 +20,13 @@ Then execute :
docker-compose up -d
```
The app runs automatically on the port defined in `SERVICE_PORT` of `.env` file (default : _3002_).
The app runs automatically on the port defined in `SERVICE_PORT` of `.env` file (default : _5002_).
You then need to set the appropriate rights for PGAdmin container :
```bash
sudo chown -R 5050:5050 postgresql/.pgadmin_data
```
## Database migration
@ -32,7 +38,36 @@ docker exec v3_user sh -c "npx prisma migrate dev"
## Usage
TBC
The app exposes the following [gRPC](https://grpc.io/) services :
- **Create** : create an auth
```json
{
"uuid": "30f49838-3f24-42bb-a489-8ffb480173ae",
"username": "john.doe@email.com",
"password": "John123"
}
```
- **Update** : update an auth (username and/or password)
```json
{
"uuid": "30f49838-3f24-42bb-a489-8ffb480173ae",
"username": "johnny.doe@email.com",
"password": "John1234"
}
```
- **Validate** : validate an auth (= authentication with username/password)
```json
{
"username": "john.doe@email.com",
"password": "John123"
}
```
## Test

View File

@ -13,11 +13,13 @@ services:
- .env
command: npm run start:dev
ports:
- "${SERVICE_PORT:-3002}:5000"
- "${SERVICE_PORT:-5002}:${SERVICE_PORT:-5002}"
depends_on:
- db
networks:
- mobicoop-v3
v3-network:
aliases:
- v3-auth-api
db:
container_name: ${POSTGRES_CONTAINER}
@ -32,7 +34,9 @@ services:
volumes:
- ./postgresql/.db_data:/var/lib/postgresql/data:rw
networks:
- mobicoop-v3
v3-network:
aliases:
- v3-auth-db
pgadmin:
container_name: ${PGADMIN_CONTAINER}
@ -47,11 +51,13 @@ services:
- ./postgresql/.pgadmin_data:/var/lib/pgadmin:rw
restart: unless-stopped
networks:
- mobicoop-v3
v3-network:
aliases:
- v3-auth-pgadmin
depends_on:
- db
networks:
mobicoop-v3:
external:
name: mobicoop-v3
v3-network:
name: v3-network
driver: bridge

1275
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -21,9 +21,21 @@
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@automapper/classes": "^8.7.7",
"@automapper/core": "^8.7.7",
"@automapper/nestjs": "^8.7.7",
"@grpc/grpc-js": "^1.8.0",
"@grpc/proto-loader": "^0.7.4",
"@nestjs/common": "^9.0.0",
"@nestjs/config": "^2.2.0",
"@nestjs/core": "^9.0.0",
"@nestjs/cqrs": "^9.0.1",
"@nestjs/microservices": "^9.2.1",
"@nestjs/platform-express": "^9.0.0",
"@prisma/client": "^4.7.1",
"bcrypt": "^5.1.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0"
@ -32,6 +44,7 @@
"@nestjs/cli": "^9.0.0",
"@nestjs/schematics": "^9.0.0",
"@nestjs/testing": "^9.0.0",
"@types/bcrypt": "^5.0.0",
"@types/express": "^4.17.13",
"@types/jest": "28.1.8",
"@types/node": "^16.0.0",
@ -43,6 +56,7 @@
"eslint-plugin-prettier": "^4.0.0",
"jest": "28.1.3",
"prettier": "^2.3.2",
"prisma": "^4.7.1",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "28.0.8",

View File

@ -0,0 +1,10 @@
-- CreateTable
CREATE TABLE "auth" (
"uuid" UUID NOT NULL,
"username" TEXT NOT NULL,
"password" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "auth_pkey" PRIMARY KEY ("uuid")
);

View File

@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"

21
prisma/schema.prisma Normal file
View File

@ -0,0 +1,21 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Auth {
uuid String @id @db.Uuid
username String
password String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@map("auth")
}

View File

@ -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!');
});
});
});

View File

@ -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();
}
}

View File

@ -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 { AuthModule } from './modules/auth/auth.module';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
imports: [
ConfigModule.forRoot({ isGlobal: true }),
AutomapperModule.forRoot({ strategyInitializer: classes() }),
AuthModule,
],
controllers: [],
providers: [],
})
export class AppModule {}

View File

@ -1,8 +0,0 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@ -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: 'auth',
protoPath: join(
__dirname,
'modules/auth/adapters/primaries/auth.proto',
),
url: process.env.SERVICE_URL + ':' + process.env.SERVICE_PORT,
loader: { keepCase: true },
},
},
);
await app.listen();
}
bootstrap();

View File

@ -0,0 +1,70 @@
import { Mapper } from '@automapper/core';
import { InjectMapper } from '@automapper/nestjs';
import { Controller } from '@nestjs/common';
import { CommandBus, QueryBus } from '@nestjs/cqrs';
import { GrpcMethod, RpcException } from '@nestjs/microservices';
import { DatabaseException } from 'src/modules/database/src/exceptions/DatabaseException';
import { CreateAuthCommand } from '../../commands/create-auth.command';
import { UpdateAuthCommand } from '../../commands/update-auth.command';
import { CreateAuthRequest } from '../../domain/dto/create-auth.request';
import { UpdateAuthRequest } from '../../domain/dto/update-auth.request';
import { ValidateAuthRequest } from '../../domain/dto/validate-auth.request';
import { Auth } from '../../domain/entities/auth';
import { ValidateQuery } from '../../queries/validate.query';
import { AuthPresenter } from './auth.presenter';
@Controller()
export class AuthController {
constructor(
private readonly _commandBus: CommandBus,
private readonly _queryBus: QueryBus,
@InjectMapper() private readonly _mapper: Mapper,
) {}
@GrpcMethod('AuthService', 'Validate')
async validate(data: ValidateAuthRequest): Promise<AuthPresenter> {
try {
const auth = await this._queryBus.execute(
new ValidateQuery(data.username, data.password),
);
return this._mapper.map(auth, Auth, AuthPresenter);
} catch (e) {
throw new RpcException({
code: 7,
message: 'Permission denied',
});
}
}
@GrpcMethod('AuthService', 'Create')
async createUser(data: CreateAuthRequest): Promise<AuthPresenter> {
try {
const auth = await this._commandBus.execute(new CreateAuthCommand(data));
return this._mapper.map(auth, Auth, AuthPresenter);
} catch (e) {
if (e instanceof DatabaseException) {
if (e.message.includes('Already exists')) {
throw new RpcException({
code: 6,
message: 'Auth already exists',
});
}
}
throw new RpcException({});
}
}
@GrpcMethod('AuthService', 'Update')
async updateAuth(data: UpdateAuthRequest): Promise<AuthPresenter> {
try {
const auth = await this._commandBus.execute(new UpdateAuthCommand(data));
return this._mapper.map(auth, Auth, AuthPresenter);
} catch (e) {
throw new RpcException({
code: 7,
message: 'Permission denied',
});
}
}
}

View File

@ -0,0 +1,9 @@
import { AutoMap } from '@automapper/classes';
export class AuthPresenter {
@AutoMap()
uuid: string;
@AutoMap()
username: string;
}

View File

@ -0,0 +1,32 @@
syntax = "proto3";
package auth;
service AuthService {
rpc Validate(AuthByUsernamePassword) returns (AuthByUuid);
rpc Create(AuthWithPassword) returns (Auth);
rpc Update(AuthWithPassword) returns (Auth);
rpc Delete(AuthByUuid) returns (Empty);
}
message AuthByUsernamePassword {
string username = 1;
string password = 2;
}
message AuthWithPassword {
string uuid = 1;
string username = 2;
string password = 3;
}
message AuthByUuid {
string uuid = 1;
}
message Auth {
string uuid = 1;
string username = 2;
}
message Empty {}

View File

@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
import { AuthNZRepository } from '../../../database/src/domain/authnz-repository';
import { Auth } from '../../domain/entities/auth';
@Injectable()
export class AuthRepository extends AuthNZRepository<Auth> {
protected _model = 'auth';
}

View File

@ -0,0 +1,23 @@
import { Module } from '@nestjs/common';
import { CqrsModule } from '@nestjs/cqrs';
import { DatabaseModule } from '../database/database.module';
import { AuthController } from './adapters/primaries/auth.controller';
import { CreateAuthUseCase } from './domain/usecases/create-auth.usecase';
import { ValidateUseCase } from './domain/usecases/validate-auth.usecase';
import { AuthProfile } from './mappers/auth.profile';
import { AuthRepository } from './adapters/secondaries/auth.repository';
import { UpdateAuthUseCase } from './domain/usecases/update-auth.usecase';
@Module({
imports: [DatabaseModule, CqrsModule],
controllers: [AuthController],
providers: [
AuthProfile,
AuthRepository,
ValidateUseCase,
CreateAuthUseCase,
UpdateAuthUseCase,
],
exports: [],
})
export class AuthModule {}

View File

@ -0,0 +1,9 @@
import { CreateAuthRequest } from '../domain/dto/create-auth.request';
export class CreateAuthCommand {
readonly createAuthRequest: CreateAuthRequest;
constructor(request: CreateAuthRequest) {
this.createAuthRequest = request;
}
}

View File

@ -0,0 +1,9 @@
import { UpdateAuthRequest } from '../domain/dto/update-auth.request';
export class UpdateAuthCommand {
readonly updateAuthRequest: UpdateAuthRequest;
constructor(request: UpdateAuthRequest) {
this.updateAuthRequest = request;
}
}

View File

@ -0,0 +1,18 @@
import { AutoMap } from '@automapper/classes';
import { IsNotEmpty, IsString } from 'class-validator';
export class CreateAuthRequest {
@IsString()
@AutoMap()
uuid: string;
@IsString()
@IsNotEmpty()
@AutoMap()
username: string;
@IsString()
@IsNotEmpty()
@AutoMap()
password: string;
}

View File

@ -0,0 +1,16 @@
import { AutoMap } from '@automapper/classes';
import { IsString } from 'class-validator';
export class UpdateAuthRequest {
@IsString()
@AutoMap()
uuid: string;
@IsString()
@AutoMap()
username?: string;
@IsString()
@AutoMap()
password?: string;
}

View File

@ -0,0 +1,11 @@
import { IsNotEmpty, IsString } from 'class-validator';
export class ValidateAuthRequest {
@IsString()
@IsNotEmpty()
username: string;
@IsString()
@IsNotEmpty()
password: string;
}

View File

@ -0,0 +1,12 @@
import { AutoMap } from '@automapper/classes';
export class Auth {
@AutoMap()
uuid: string;
@AutoMap()
username: string;
@AutoMap()
password: string;
}

View File

@ -0,0 +1,20 @@
import { CommandHandler } from '@nestjs/cqrs';
import { AuthRepository } from '../../adapters/secondaries/auth.repository';
import { CreateAuthCommand } from '../../commands/create-auth.command';
import { Auth } from '../entities/auth';
import * as bcrypt from 'bcrypt';
@CommandHandler(CreateAuthCommand)
export class CreateAuthUseCase {
constructor(private readonly _repository: AuthRepository) {}
async execute(command: CreateAuthCommand): Promise<Auth> {
const { password, ...authWithoutPassword } = command.createAuthRequest;
const hash = await bcrypt.hash(password, 10);
return this._repository.create({
password: hash,
...authWithoutPassword,
});
}
}

View File

@ -0,0 +1,29 @@
import { Mapper } from '@automapper/core';
import { InjectMapper } from '@automapper/nestjs';
import { CommandHandler } from '@nestjs/cqrs';
import { AuthRepository } from '../../adapters/secondaries/auth.repository';
import { UpdateAuthCommand } from '../../commands/update-auth.command';
import { Auth } from '../entities/auth';
import * as bcrypt from 'bcrypt';
@CommandHandler(UpdateAuthCommand)
export class UpdateAuthUseCase {
constructor(
private readonly _repository: AuthRepository,
@InjectMapper() private readonly _mapper: Mapper,
) {}
async execute(command: UpdateAuthCommand): Promise<Auth> {
const { uuid, username, password } = command.updateAuthRequest;
const request = {};
if (username) {
request['username'] = username;
}
if (password) {
const hash = await bcrypt.hash(password, 10);
request['password'] = hash;
}
return this._repository.update(uuid, request);
}
}

View File

@ -0,0 +1,23 @@
import { QueryHandler } from '@nestjs/cqrs';
import { AuthRepository } from '../../adapters/secondaries/auth.repository';
import { ValidateQuery } from '../../queries/validate.query';
import { Auth } from '../entities/auth';
import * as bcrypt from 'bcrypt';
import { NotFoundException, UnauthorizedException } from '@nestjs/common';
@QueryHandler(ValidateQuery)
export class ValidateUseCase {
constructor(private readonly _authRepository: AuthRepository) {}
async execute(validate: ValidateQuery): Promise<Auth> {
const auth = await this._authRepository.findOne({
username: validate.username,
});
if (auth) {
const isMatch = await bcrypt.compare(validate.password, auth.password);
if (isMatch) return auth;
throw new UnauthorizedException();
}
throw new NotFoundException();
}
}

View File

@ -0,0 +1,18 @@
import { createMap, Mapper } from '@automapper/core';
import { AutomapperProfile, InjectMapper } from '@automapper/nestjs';
import { Injectable } from '@nestjs/common';
import { AuthPresenter } from '../adapters/primaries/auth.presenter';
import { Auth } from '../domain/entities/auth';
@Injectable()
export class AuthProfile extends AutomapperProfile {
constructor(@InjectMapper() mapper: Mapper) {
super(mapper);
}
override get profile() {
return (mapper) => {
createMap(mapper, Auth, AuthPresenter);
};
}
}

View File

@ -0,0 +1,9 @@
export class ValidateQuery {
readonly username: string;
readonly password: string;
constructor(username: string, password: string) {
this.username = username;
this.password = password;
}
}

View File

@ -0,0 +1,61 @@
import { classes } from '@automapper/classes';
import { AutomapperModule } from '@automapper/nestjs';
import { Test, TestingModule } from '@nestjs/testing';
import { AuthRepository } from '../../adapters/secondaries/auth.repository';
import { CreateAuthCommand } from '../../commands/create-auth.command';
import { CreateAuthRequest } from '../../domain/dto/create-auth.request';
import { Auth } from '../../domain/entities/auth';
import { CreateAuthUseCase } from '../../domain/usecases/create-auth.usecase';
import { AuthProfile } from '../../mappers/auth.profile';
import * as bcrypt from 'bcrypt';
const newAuthRequest: CreateAuthRequest = {
uuid: 'bb281075-1b98-4456-89d6-c643d3044a91',
username: 'john.doe@email.com',
password: 'John123',
};
const newAuthCommand: CreateAuthCommand = new CreateAuthCommand(newAuthRequest);
const mockAuthRepository = {
create: jest.fn().mockResolvedValue({
uuid: newAuthRequest.uuid,
username: newAuthRequest.username,
password: bcrypt.hashSync(newAuthRequest.password, 10),
}),
};
describe('CreateAuthUseCase', () => {
let createAuthUseCase: CreateAuthUseCase;
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [AutomapperModule.forRoot({ strategyInitializer: classes() })],
providers: [
{
provide: AuthRepository,
useValue: mockAuthRepository,
},
CreateAuthUseCase,
AuthProfile,
],
}).compile();
createAuthUseCase = module.get<CreateAuthUseCase>(CreateAuthUseCase);
});
it('should be defined', () => {
expect(createAuthUseCase).toBeDefined();
});
describe('execute', () => {
it('should create an auth and returns new entity object', async () => {
const newAuth: Auth = await createAuthUseCase.execute(newAuthCommand);
expect(newAuth.username).toBe(newAuthRequest.username);
expect(
bcrypt.compareSync(newAuthRequest.password, newAuth.password),
).toBeTruthy();
});
});
});

View File

@ -0,0 +1,119 @@
import { classes } from '@automapper/classes';
import { AutomapperModule } from '@automapper/nestjs';
import { Test, TestingModule } from '@nestjs/testing';
import { UpdateAuthCommand } from '../../commands/update-auth.command';
import { UpdateAuthRequest } from '../../domain/dto/update-auth.request';
import { Auth } from '../../domain/entities/auth';
import * as bcrypt from 'bcrypt';
import { UpdateAuthUseCase } from '../../domain/usecases/update-auth.usecase';
import { AuthRepository } from '../../adapters/secondaries/auth.repository';
import { AuthProfile } from '../../mappers/auth.profile';
const originalAuth: Auth = new Auth();
originalAuth.uuid = 'bb281075-1b98-4456-89d6-c643d3044a91';
originalAuth.username = 'john.doe@email.com';
originalAuth.password = 'encrypted_password';
const updateUsernameAuthRequest: UpdateAuthRequest = {
uuid: 'bb281075-1b98-4456-89d6-c643d3044a91',
username: 'johnny.doe@email.com',
};
const updatePasswordAuthRequest: UpdateAuthRequest = {
uuid: 'bb281075-1b98-4456-89d6-c643d3044a91',
password: 'John1234',
};
const updateAuthRequest: UpdateAuthRequest = {
uuid: 'bb281075-1b98-4456-89d6-c643d3044a91',
username: 'johnny.doe@email.com',
password: 'John1234',
};
const updateUsernameAuthCommand: UpdateAuthCommand = new UpdateAuthCommand(
updateUsernameAuthRequest,
);
const updatePasswordAuthCommand: UpdateAuthCommand = new UpdateAuthCommand(
updatePasswordAuthRequest,
);
const updateAuthCommand: UpdateAuthCommand = new UpdateAuthCommand(
updateAuthRequest,
);
const mockAuthRepository = {
update: jest.fn().mockImplementation((uuid: string, params: any) => {
if (params.username && params.password) {
const auth: Auth = { ...originalAuth };
auth.username = params.username;
auth.password = params.password;
return Promise.resolve(auth);
}
if (params.username) {
const auth: Auth = { ...originalAuth };
auth.username = params.username;
return Promise.resolve(auth);
}
if (params.password) {
const auth: Auth = { ...originalAuth };
auth.password = params.password;
return Promise.resolve(auth);
}
}),
};
describe('UpdateAuthUseCase', () => {
let updateAuthUseCase: UpdateAuthUseCase;
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [AutomapperModule.forRoot({ strategyInitializer: classes() })],
providers: [
{
provide: AuthRepository,
useValue: mockAuthRepository,
},
UpdateAuthUseCase,
AuthProfile,
],
}).compile();
updateAuthUseCase = module.get<UpdateAuthUseCase>(UpdateAuthUseCase);
});
it('should be defined', () => {
expect(updateAuthUseCase).toBeDefined();
});
describe('execute', () => {
it('should update the username of an Auth', async () => {
const updatedAuth: Auth = await updateAuthUseCase.execute(
updateUsernameAuthCommand,
);
expect(updatedAuth.username).toBe(updateUsernameAuthRequest.username);
});
it('should update the password of an Auth', async () => {
const updatedAuth: Auth = await updateAuthUseCase.execute(
updatePasswordAuthCommand,
);
expect(
bcrypt.compareSync(
updatePasswordAuthRequest.password,
updatedAuth.password,
),
).toBeTruthy();
});
it('should update the username and the password of an Auth', async () => {
const updatedAuth: Auth = await updateAuthUseCase.execute(
updateAuthCommand,
);
expect(updatedAuth.username).toBe(updateAuthRequest.username);
expect(
bcrypt.compareSync(updateAuthRequest.password, updatedAuth.password),
).toBeTruthy();
});
});
});

View File

@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { AuthRepository } from '../auth/adapters/secondaries/auth.repository';
import { PrismaService } from './src/adapters/secondaries/prisma-service';
@Module({
providers: [PrismaService, AuthRepository],
exports: [PrismaService, AuthRepository],
})
export class DatabaseModule {}

View File

@ -0,0 +1,165 @@
import { Injectable } from '@nestjs/common';
import { PrismaClientKnownRequestError } from '@prisma/client/runtime';
import { DatabaseException } from '../../exceptions/DatabaseException';
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<void> {
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();
}
}
}
}

View File

@ -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();
});
}
}

View File

@ -0,0 +1,3 @@
import { PrismaRepository } from '../adapters/secondaries/prisma-repository.abstract';
export class AuthNZRepository<T> extends PrismaRepository<T> {}

View 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;
}
}

View File

@ -0,0 +1,4 @@
export interface ICollection<T> {
data: T[];
total: number;
}

View 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<void>;
}

View 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/DatabaseException';
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);
});
});
});