Skip to content

Commit

Permalink
move task to its own module and extends TaskRepository
Browse files Browse the repository at this point in the history
  • Loading branch information
Johannbr committed Nov 18, 2024
1 parent 7016988 commit 3db1b33
Show file tree
Hide file tree
Showing 20 changed files with 219 additions and 44 deletions.
3 changes: 2 additions & 1 deletion apiv2/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@
"^@config/(.*)$": "<rootDir>/src/config/$1",
"^@infra/(.*)$": "<rootDir>/src/infra/$1",
"^@shared/(.*)$": "<rootDir>/src/shared/$1",
"^@notification/(.*)$": "<rootDir>/src/notification/$1"
"^@notification/(.*)$": "<rootDir>/src/notification/$1",
"^@task/(.*)$": "<rootDir>/src/task/$1"
},
"modulePathIgnorePatterns": [
"<rootDir>/packages"
Expand Down
1 change: 1 addition & 0 deletions apiv2/src/App.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { AdminModule } from "./admin/Admin.module";
import { LoggerRequestMiddleware } from "./shared/infra/LoggerRequest.middleware";
import { CorrelationIdMiddleware } from "./shared/infra/CorrelationId.middleware.js";
import { SharedModule } from "./shared/Shared.module";
import { TaskModule } from "./task/Task.module";

@Module({
imports: [
Expand Down
13 changes: 12 additions & 1 deletion apiv2/src/admin/Admin.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ import { etablissementMongoProviders } from "./infra/sejours/cle/etablissement/p
import { gatewayProviders } from "./infra/sejours/cle/initProvider/gateway";
import { guardProviders } from "./infra/sejours/cle/initProvider/guard";
import { useCaseProvider as useCaseProviders } from "./infra/sejours/cle/initProvider/useCase";
import { TaskModule } from "@task/Task.module";
import { AdminTaskRepository } from "./infra/task/AdminTaskMongo.repository";
import { QueueType } from "@shared/infra/Queue";
import { taskMongoProviders } from "@task/infra/TaskMongo.provider";
import { AdminTaskController } from "./infra/task/api/AdminTask.controller";

@Module({
imports: [
Expand All @@ -38,19 +43,25 @@ import { useCaseProvider as useCaseProviders } from "./infra/sejours/cle/initPro
BullModule.registerQueue({
name: NotificationQueueType.CONTACT,
}),
BullModule.registerQueue({
name: QueueType.ADMIN_TASK,
}),
TaskModule,
],
controllers: [ClasseController, AuthController],
controllers: [ClasseController, AuthController, AdminTaskController],
providers: [
ClasseService,
{ provide: AuthProvider, useClass: JwtTokenService },
...classeMongoProviders,
...referentMongoProviders,
...etablissementMongoProviders,
...guardProviders,
...taskMongoProviders,
Logger,
SigninReferent,
{ provide: NotificationGateway, useClass: NotificationProducer },
{ provide: ContactGateway, useClass: ContactProducer },
AdminTaskRepository,
...useCaseProviders,
...gatewayProviders,
],
Expand Down
37 changes: 37 additions & 0 deletions apiv2/src/admin/AdminJob.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Logger, Module } from "@nestjs/common";
import { AdminTaskConsumer } from "./infra/task/AdminTask.consumer";
import { AdminTaskRepository } from "./infra/task/AdminTaskMongo.repository";
import configuration from "@config/configuration";
import { QueueModule } from "@infra/Queue.module";
import { ConfigModule } from "@nestjs/config";
import { DatabaseModule } from "@infra/Database.module";
import { TaskModule } from "@task/Task.module";
import { taskMongoProviders } from "@task/infra/TaskMongo.provider";
import { BullModule } from "@nestjs/bullmq";
import { QueueType } from "@shared/infra/Queue";

@Module({
imports: [
TaskModule,
DatabaseModule,
ConfigModule.forRoot({
load: [configuration],
}),
QueueModule,
BullModule.registerQueue({
name: QueueType.ADMIN_TASK,
}),
],
providers: [
Logger,
AdminTaskConsumer,
AdminTaskRepository,
...taskMongoProviders,
// add use case here
],
})
export class AdminJobModule {
constructor(private logger: Logger) {
this.logger.log("AdminJobModule has started", "AdminJobModule");
}
}
17 changes: 17 additions & 0 deletions apiv2/src/admin/infra/iam/guard/SuperAdmin.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { CanActivate, ExecutionContext, Injectable, Logger } from "@nestjs/common";
import { isSuperAdmin } from "snu-lib";

@Injectable()
export class SuperAdminGuard implements CanActivate {
constructor() {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();

// TODO : request.user mapping
if (isSuperAdmin({ role: request.user.role, subRole: request.user.sousRole })) {
return true;
}

return false;
}
}
9 changes: 8 additions & 1 deletion apiv2/src/admin/infra/sejours/cle/initProvider/guard.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { SuperAdminGuard } from "src/admin/infra/iam/guard/SuperAdmin.guard";
import { ClasseAdminCleGuard } from "../classe/guard/ClasseAdminCle.guard";
import { ClasseDepartementGuard } from "../classe/guard/ClasseDepartement.guard";
import { ClasseGuardService } from "../classe/guard/ClasseGuard.service";
import { ClasseRegionGuard } from "../classe/guard/ClasseRegion.guard";

export const guardProviders = [ClasseGuardService, ClasseAdminCleGuard, ClasseRegionGuard, ClasseDepartementGuard];
export const guardProviders = [
ClasseGuardService,
ClasseAdminCleGuard,
ClasseRegionGuard,
ClasseDepartementGuard,
SuperAdminGuard,
];
Original file line number Diff line number Diff line change
@@ -1,34 +1,37 @@
import { Processor, WorkerHost } from "@nestjs/bullmq";
import { Inject, Logger } from "@nestjs/common";
import { Logger } from "@nestjs/common";
import { ConsumerResponse } from "@shared/infra/ConsumerResponse";
import { QueueType, TaskQueue } from "@shared/infra/Queue";
import { Job } from "bullmq";
import { TaskName } from "snu-lib";
import { QueueType, TaskQueue } from "../Queue";
import { AdminTaskRepository } from "./AdminTaskMongo.repository";

@Processor(QueueType.TASK)
export class TaskConsumer extends WorkerHost {
@Processor(QueueType.ADMIN_TASK)
export class AdminTaskConsumer extends WorkerHost {
constructor(
private logger: Logger,
// @Inject(TaskProvider) private readonly taskProvider: TaskProvider,
private adminTaskRepository: AdminTaskRepository,
) {
super();
}
// TODO call async usecase task
async process(job: Job<TaskQueue, any, TaskName>): Promise<ConsumerResponse> {
this.logger.log(`Processing task "${job.name}" with data ${JSON.stringify(job.data)}`, TaskConsumer.name);
this.logger.log(`Processing task "${job.name}" with data ${JSON.stringify(job.data)}`, AdminTaskConsumer.name);
await this.adminTaskRepository.toSuccess(job.data.id);
return ConsumerResponse.SUCCESS;
// return this.taskProvider
// .execute(job.name, job.data)
// .then(() => {
// this.logger.log(
// `Task "${job.name}" processed successfully with data ${JSON.stringify(job.data)}`,
// TaskConsumer.name,
// AdminTaskConsumer.name,
// );
// return ConsumerResponse.SUCCESS;
// })
// .catch((error) => {
// this.logger.error(
// `Error processing task "${job.name}" - ${error.message} - ${error.stack}`,
// TaskConsumer.name,
// AdminTaskConsumer.name,
// );
// throw error;
// });
Expand Down
26 changes: 26 additions & 0 deletions apiv2/src/admin/infra/task/AdminTaskMongo.repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { InjectQueue } from "@nestjs/bullmq";
import { Inject, Injectable } from "@nestjs/common";
import { QueueType } from "@shared/infra/Queue";
import { TaskGateway } from "@task/core/Task.gateway";
import { CreateTaskModel, TaskModel } from "@task/core/Task.model";
import { TaskMapper } from "@task/infra/Task.mapper";
import { Queue } from "bullmq";
import { Model } from "mongoose";
import { TASK_MONGOOSE_ENTITY, TaskDocument } from "src/task/infra/TaskMongo.provider";
import { TaskRepository } from "src/task/infra/TaskMongo.repository";

@Injectable()
export class AdminTaskRepository extends TaskRepository implements TaskGateway {
constructor(
@Inject(TASK_MONGOOSE_ENTITY) protected taskMongooseEntity: Model<TaskDocument>,
@InjectQueue(QueueType.ADMIN_TASK) private adminTaskQueue: Queue,
) {
super(taskMongooseEntity);
}

async create(task: CreateTaskModel): Promise<TaskModel> {
const createdTask = await super.create(task);
await this.adminTaskQueue.add(task.name, { ...TaskMapper.toQueue(createdTask) });
return createdTask;
}
}
28 changes: 28 additions & 0 deletions apiv2/src/admin/infra/task/api/AdminTask.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Body, Controller, Get, Param, Post, Put, UseGuards } from "@nestjs/common";
import { CreateTaskModel, TaskModel } from "@task/core/Task.model";
import { AdminTaskRepository } from "../AdminTaskMongo.repository";
import { SuperAdminGuard } from "../../iam/guard/SuperAdmin.guard";

@Controller("task")
export class AdminTaskController {
constructor(private adminTaskRepository: AdminTaskRepository) {}

@Get("/")
@UseGuards(SuperAdminGuard)
findAll(): Promise<TaskModel[]> {
return this.adminTaskRepository.findAll();
}

@Get(":id")
@UseGuards(SuperAdminGuard)
verify(@Param("id") id: string): Promise<TaskModel> {
return this.adminTaskRepository.findById(id);
}

// TODO for testing purposes only => REMOVE
@Post("/")
@UseGuards(SuperAdminGuard)
create(@Body() task: CreateTaskModel): Promise<TaskModel> {
return this.adminTaskRepository.create(task);
}
}
1 change: 1 addition & 0 deletions apiv2/src/infra/Queue.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ConfigModule, ConfigService } from "@nestjs/config";
import { BullModule } from "@nestjs/bullmq";
import { Module } from "@nestjs/common";
import { NotificationQueueType } from "@notification/infra/Notification";
import { QueueType } from "@shared/infra/Queue";

@Module({
imports: [
Expand Down
2 changes: 2 additions & 0 deletions apiv2/src/mainJob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import "./instrument"; // first
import { NestFactory } from "@nestjs/core";
import { NotificationJobModule } from "./notification/NotificationJob.module";
import { Logger } from "@nestjs/common";
import { AdminJobModule } from "./admin/AdminJob.module";

async function bootstrap() {
await NestFactory.createApplicationContext(NotificationJobModule);
await NestFactory.createApplicationContext(AdminJobModule);
Logger.log(`Job started`, "bootstrap mainJob");
// TODO: handle logs error here ?
// process.on("uncaughtException", (error) => {
Expand Down
9 changes: 0 additions & 9 deletions apiv2/src/shared/core/task/Task.gateway.ts

This file was deleted.

4 changes: 2 additions & 2 deletions apiv2/src/shared/infra/Queue.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { TaskModel } from "@shared/core/task/Task.model";
import { TaskModel } from "src/task/core/Task.model";

export enum QueueType {
TASK = "task",
ADMIN_TASK = "admin-task",
}

export type TaskQueue = Pick<TaskModel, "id" | "name">;
11 changes: 11 additions & 0 deletions apiv2/src/task/Task.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from "@nestjs/common";
import { TaskRepository } from "./infra/TaskMongo.repository";
import { taskMongoProviders } from "./infra/TaskMongo.provider";
import { DatabaseModule } from "@infra/Database.module";

@Module({
imports: [DatabaseModule],
providers: [TaskRepository, ...taskMongoProviders],
exports: [TaskRepository],
})
export class TaskModule {}
12 changes: 12 additions & 0 deletions apiv2/src/task/core/Task.gateway.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { CreateTaskModel, TaskModel } from "./Task.model";

export interface TaskGateway {
create(task: CreateTaskModel): Promise<TaskModel>;
findAll(): Promise<TaskModel[]>;
findById(id: string): Promise<TaskModel>;
delete(id: string): Promise<void>;
update(id: string, task: TaskModel): Promise<TaskModel>;
toSuccess(id: string): Promise<TaskModel>;
}

export const TaskGateway = Symbol("TaskGateway");
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { TaskModel } from "@shared/core/task/Task.model";
import { CreateTaskModel, TaskModel } from "src/task/core/Task.model";
import { TaskType } from "snu-lib";
import { TaskDocument } from "./TaskMongo.provider";
import { TaskQueue } from "../Queue";
import { TaskQueue } from "../../shared/infra/Queue";

export class TaskMapper {
static toModel(taskType: TaskDocument): TaskModel {
Expand All @@ -18,9 +18,9 @@ export class TaskMapper {
};
}

static toQueue(taskType: TaskDocument): TaskQueue {
static toQueue(taskType: TaskModel): TaskQueue {
return {
id: taskType._id.toString(),
id: taskType.id.toString(),
name: taskType.name,
};
}
Expand All @@ -40,4 +40,19 @@ export class TaskMapper {
updatedAt: taskModel.updatedAt,
};
}

static toEntityCreate(taskModel: CreateTaskModel): Omit<TaskType, "_id"> {
return {
name: taskModel.name,
libelle: taskModel.libelle,
startDate: taskModel.startDate,
endDate: taskModel.endDate,
status: taskModel.status,
metadata: {
...taskModel.metadata,
},
createdAt: new Date(),
updatedAt: new Date(),
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ TaskSchemaRef.pre("save", function (next) {
next();
});

export const classeMongoProviders = [
export const taskMongoProviders = [
{
provide: TASK_MONGOOSE_ENTITY,
useFactory: (connection: Connection) => connection.model(TaskName, TaskSchemaRef),
Expand Down
Loading

0 comments on commit 3db1b33

Please sign in to comment.