54 lines
1.4 KiB
TypeScript
54 lines
1.4 KiB
TypeScript
import Fastify, { type FastifyRequest, type FastifyReply } from "fastify";
|
|
import jwtPlugin from "@fastify/jwt";
|
|
import cookiePlugin from "@fastify/cookie";
|
|
|
|
declare module "fastify" {
|
|
interface FastifyInstance {
|
|
authenticate: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
|
}
|
|
}
|
|
import staticFiles from "@fastify/static";
|
|
import { join } from "path";
|
|
import { config } from "./lib/config";
|
|
import { migrate } from "./db/manager";
|
|
import { authRoutes } from "./routes/auth";
|
|
import { customerRoutes } from "./routes/customers";
|
|
import { startSizeCollector } from "./services/sizeCollector";
|
|
|
|
const app = Fastify({ logger: true });
|
|
|
|
await app.register(cookiePlugin);
|
|
await app.register(jwtPlugin, { secret: config.jwtSecret });
|
|
|
|
app.decorate("authenticate", async function (req: any, reply: any) {
|
|
try {
|
|
await req.jwtVerify();
|
|
} catch {
|
|
return reply.status(401).send({ message: "Unauthorized" });
|
|
}
|
|
});
|
|
|
|
app.register(staticFiles, {
|
|
root: join(import.meta.dir, "../frontend"),
|
|
prefix: "/",
|
|
});
|
|
|
|
app.get("/health", async () => ({ status: "ok" }));
|
|
|
|
app.register(authRoutes, { prefix: "/api" });
|
|
|
|
app.register(customerRoutes, {
|
|
prefix: "/api",
|
|
onRequest: [app.authenticate],
|
|
} as any);
|
|
|
|
await migrate();
|
|
startSizeCollector(app.log);
|
|
|
|
app.listen({ port: config.port, host: "0.0.0.0" }, (err) => {
|
|
if (err) {
|
|
app.log.error(err);
|
|
process.exit(1);
|
|
}
|
|
});
|