35 lines
865 B
TypeScript
Executable File
35 lines
865 B
TypeScript
Executable File
import type { FastifyPluginAsync } from "fastify";
|
|
import fp from "fastify-plugin";
|
|
import { MikroORM } from "@mikro-orm/postgresql";
|
|
import config from "@/mikro-orm.config";
|
|
import Logger from "@/lib/logger";
|
|
|
|
declare module "fastify" {
|
|
interface FastifyInstance {
|
|
orm: MikroORM;
|
|
}
|
|
}
|
|
|
|
const logger = new Logger("Lib | database");
|
|
|
|
const Database: FastifyPluginAsync = async (fastify) => {
|
|
const orm = await MikroORM.init(config);
|
|
|
|
if (process.env.NODE_ENV !== "production") {
|
|
try {
|
|
await orm.schema.updateSchema();
|
|
logger.info("Database migration completed.");
|
|
} catch (err) {
|
|
logger.error("Migration failed:", err);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
fastify.decorate("orm", orm);
|
|
|
|
fastify.addHook("onClose", async () => {
|
|
await orm.close(true);
|
|
});
|
|
};
|
|
|
|
export default fp(Database); |