metis-desk/modules/assets/src/api/module.ts

45 lines
2.0 KiB
TypeScript
Raw Normal View History

import { UniqueID } from "@repo/rdx-ddd";
import { Maybe, Result } from "@repo/rdx-utils";
import type { RequestHandler } from "express";
import type { Sequelize } from "sequelize";
import { AssetUseCases } from "./application/asset.use-cases";
import { AssetCatalogUseCases } from "./application/asset-catalog.use-cases";
import { seedAssetCatalog } from "./domain/asset-catalog-seed";
import { registerAssetRoutes } from "./infrastructure/http/asset.routes";
import { registerAssetCatalogRoutes } from "./infrastructure/http/asset-catalog.routes";
import { migrateInventory } from "./infrastructure/persistence/asset.model";
import {
CatalogModel,
migrateAssetCatalog,
} from "./infrastructure/persistence/asset-catalog.model";
import { AssetCatalogPersistenceMapper } from "./infrastructure/persistence/asset-catalog-persistence.mapper";
import { SequelizeAssetRepository } from "./infrastructure/persistence/sequelize-asset.repository";
import { SequelizeAssetCatalogRepository } from "./infrastructure/persistence/sequelize-asset-catalog.repository";
export async function createAssetModule(database: Sequelize, authenticate: RequestHandler) {
await migrateAssetCatalog(database);
await CatalogModel.findOrCreate({
where: { catalogKey: "global" },
defaults: { id: UniqueID.generateNewID().toPrimitive(), catalogKey: "global" },
});
const repository = new SequelizeAssetCatalogRepository(
database,
new AssetCatalogPersistenceMapper()
);
const seeded = await repository.update(Maybe.none(), (catalog) =>
Result.ok(seedAssetCatalog(catalog))
);
if (!seeded.isSuccess) {
throw new Error("No se pudo inicializar el catálogo de activos.");
}
await migrateInventory(database);
const inventory = new AssetUseCases(new SequelizeAssetRepository(database));
const useCases = new AssetCatalogUseCases(repository);
return {
register: (app: Parameters<typeof registerAssetCatalogRoutes>[0]) => {
registerAssetCatalogRoutes(app, useCases, authenticate);
registerAssetRoutes(app, inventory, authenticate);
},
};
}