Skip to content

Commit

Permalink
feat: add new fastify controller
Browse files Browse the repository at this point in the history
This commit includes:

- Implementation of main script
- Configuration of Task table seeding
- Implementation of fastify Task controller
- implementation of fastify Task controller unit tests
  • Loading branch information
Leonardo Giraldi Moreno Giuranno committed May 23, 2024
1 parent 11653c9 commit 36646e4
Show file tree
Hide file tree
Showing 30 changed files with 1,406 additions and 7 deletions.
151 changes: 150 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
@@ -1 +1,150 @@
console.log("Hello world!");
import "reflect-metadata";
import Fastify from "fastify";
import { config } from "dotenv";
import cors from "@fastify/cors";
import { runSeeders } from "typeorm-extension";

if (process.env.NODE_ENV !== "production") {
config();
}

import { TaskController, RequestParamsId } from "@/infra/web/fastify/task";
import {
CreateTaskDsTypeorm,
DeleteTaskDsTypeorm,
ListTaskByIdDsTypeorm,
TaskDataMapperTypeorm,
TaskRepositoryTypeorm,
UpdateTaskDsTypeorm,
dsTypeorm,
} from "@/infra/datasource/typeorm";
import {
CreateTaskController,
CreateTaskPresenter,
DeleteTaskController,
DeleteTaskPresenter,
ListTaskByIdController,
ListTaskByIdPresenter,
UpdateTaskController,
UpdateTaskPresenter,
} from "@/adapters/task";
import {
CreateTaskInteractor,
DeleteTaskInteractor,
ListTaskByIdInteractor,
UpdateTaskInteractor,
} from "@/useCases/task";

const fastify = Fastify({
logger: process.env.NODE_ENV !== "test" ? true : false,
});

fastify.register(cors);

if (process.env.NODE_ENV !== "test") {
dsTypeorm
.initialize()
.then(async (ds) => {
console.log(
"Conexão com o banco de dados estabelecida com sucesso!"
);

if (process.env.NODE_ENV === "development") {
console.log("Executando seeders...");
await runSeeders(ds);
console.log("Seeders executados com sucesso!");
}
})
.catch((error) => {
console.log(
`Erro ao estabelecer a conexão com o banco de dados: ${error}`
);
process.exit(1);
});
}

const taskController = new TaskController(
new CreateTaskController(
new CreateTaskInteractor(
new CreateTaskDsTypeorm(
new TaskRepositoryTypeorm(
TaskDataMapperTypeorm,
dsTypeorm.createEntityManager()
)
),
new CreateTaskPresenter()
)
),
new UpdateTaskController(
new UpdateTaskInteractor(
new UpdateTaskDsTypeorm(
new TaskRepositoryTypeorm(
TaskDataMapperTypeorm,
dsTypeorm.createEntityManager()
)
),
new UpdateTaskPresenter()
)
),
new DeleteTaskController(
new DeleteTaskInteractor(
new DeleteTaskDsTypeorm(
new TaskRepositoryTypeorm(
TaskDataMapperTypeorm,
dsTypeorm.createEntityManager()
)
),
new DeleteTaskPresenter()
)
),
new ListTaskByIdController(
new ListTaskByIdInteractor(
new ListTaskByIdDsTypeorm(
new TaskRepositoryTypeorm(
TaskDataMapperTypeorm,
dsTypeorm.createEntityManager()
)
),
new ListTaskByIdPresenter()
)
)
);

fastify.post("/tasks", async (request, reply) => {
await taskController.insert(request, reply);
});
fastify.get<{ Params: RequestParamsId }>(
"/tasks/:id",
async (request, reply) => {
await taskController.findById(request, reply);
}
);
fastify.put<{ Params: RequestParamsId }>(
"/tasks/:id",
async (request, reply) => {
await taskController.update(request, reply);
}
);
fastify.delete<{ Params: RequestParamsId }>(
"/tasks/:id",
async (request, reply) => {
await taskController.delete(request, reply);
}
);

if (process.env.NODE_ENV !== "test") {
const port = parseInt(process.env.PORT ?? "3000");
fastify
.listen({
port,
})
.then(() => {
console.log(`Servidor iniciado na porta ${port}`);
})
.catch((error) => {
console.log(`Erro ao iniciar o servidor: ${error}`);
process.exit(1);
});
}

export { fastify };
13 changes: 10 additions & 3 deletions src/infra/datasource/typeorm/ds.typeorm.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { z } from "zod";
import { config } from "dotenv";
import { DataSource } from "typeorm";
import { DataSource, DataSourceOptions } from "typeorm";
import { SeederOptions } from "typeorm-extension";

import { MainSeeder } from "./seeds/main.seeder";

if (process.env.NODE_ENV !== "production") {
config();
}

const dsTypeorm = new DataSource({
const options: DataSourceOptions & SeederOptions = {
type: z
.enum(["mysql", "postgres", "mongodb"])
.parse(process.env.DATABASE_TYPE),
Expand All @@ -24,6 +27,10 @@ const dsTypeorm = new DataSource({
process.env.NODE_ENV === "test"
? []
: [`${__dirname}/migrations/*{.js,.ts}`],
});
seeds: [MainSeeder],
seedTracking: false,
};

const dsTypeorm = new DataSource(options);

export { dsTypeorm };
1 change: 1 addition & 0 deletions src/infra/datasource/typeorm/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from "./ds.typeorm";
export * from "./task";
export * from "./seeds";
1 change: 1 addition & 0 deletions src/infra/datasource/typeorm/seeds/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./main.seeder";
15 changes: 15 additions & 0 deletions src/infra/datasource/typeorm/seeds/main.seeder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { DataSource } from "typeorm";
import { Seeder, SeederFactoryManager, runSeeder } from "typeorm-extension";

import { TaskSeeder } from "../task/task.seeder";
import { taskSeederFactory } from "../task/task.seeder.factory";

class MainSeeder implements Seeder {
async run(dataSource: DataSource, _factoryManager: SeederFactoryManager) {
await runSeeder(dataSource, TaskSeeder, {
factories: [taskSeederFactory],
});
}
}

export { MainSeeder };
7 changes: 4 additions & 3 deletions src/infra/datasource/typeorm/task/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
export * from "./task.dataMapper.typeorm";
export * from "./task.factory.typeorm";
export * from "./task.repository.typeorm";
export * from "./createTask";
export * from "./deleteTask";
export * from "./listTaskById";
export * from "./updateTask";
export * from "./task.dataMapper.typeorm";
export * from "./task.factory.typeorm";
export * from "./task.repository.typeorm";
export * from "./task.seeder";
23 changes: 23 additions & 0 deletions src/infra/datasource/typeorm/task/task.seeder.factory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { setSeederFactory } from "typeorm-extension";

import { TaskDataMapperTypeorm } from "./task.dataMapper.typeorm";

const taskSeederFactory = setSeederFactory(TaskDataMapperTypeorm, (faker) => {
const task = new TaskDataMapperTypeorm();
task.createdAt = faker.date.past();
task.description = faker.lorem.words(4);
task.dueDate = faker.date.future();
task.id = faker.string.uuid();
task.priority = faker.helpers.arrayElement([
"low",
"medium",
"high",
"critical",
]);
task.status = faker.helpers.arrayElement(["todo", "inProgress", "done"]);
task.title = faker.lorem.words(3);

return task;
});

export { taskSeederFactory };
17 changes: 17 additions & 0 deletions src/infra/datasource/typeorm/task/task.seeder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { DataSource } from "typeorm";
import { Seeder, SeederFactoryManager } from "typeorm-extension";

import { TaskDataMapperTypeorm } from "./task.dataMapper.typeorm";

class TaskSeeder implements Seeder {
async run(dataSource: DataSource, factoryManager: SeederFactoryManager) {
const repository = dataSource.getRepository(TaskDataMapperTypeorm);
const entities = await repository.find();
await repository.remove(entities);

const taskFactory = factoryManager.get(TaskDataMapperTypeorm);
await taskFactory.saveMany(10);
}
}

export { TaskSeeder };
2 changes: 2 additions & 0 deletions src/infra/web/fastify/task/controllers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./task.controller";
export * from "./types";
Loading

0 comments on commit 36646e4

Please sign in to comment.