Files
plp/apps/api/src/main.ts
T
2026-09-14 18:43:45 +08:00

54 lines
1.8 KiB
TypeScript

import "reflect-metadata";
import { ValidationPipe, type INestApplication } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import helmet from "helmet";
import type { Application } from "express";
import { AppModule } from "./app.module.js";
import { validateAuthEnvironment } from "./auth/auth.config.js";
import { HttpResponseInterceptor } from "./common/http-response.interceptor.js";
import { DomainExceptionFilter } from "./common/domain-exception.filter.js";
export function configureApp(app: INestApplication): void {
validateAuthEnvironment();
const allowedOrigin = process.env.WEB_ORIGIN ?? "http://localhost:3000";
const adapter = app.getHttpAdapter?.() as
{ getInstance(): Application } | undefined;
adapter
?.getInstance()
.set("trust proxy", process.env.TRUST_PROXY === "true" ? 1 : false);
app.setGlobalPrefix("api/v1");
app.use(helmet());
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}),
);
app.useGlobalInterceptors(new HttpResponseInterceptor());
app.useGlobalFilters(new DomainExceptionFilter());
app.enableCors({
origin(
origin: string | undefined,
callback: (error: Error | null, allow?: boolean) => void,
) {
callback(null, origin === undefined || origin === allowedOrigin);
},
credentials: true,
});
}
type AppFactory = () => Promise<INestApplication>;
export async function bootstrap(
appFactory: AppFactory = () => NestFactory.create(AppModule),
): Promise<void> {
validateAuthEnvironment();
const app = await appFactory();
configureApp(app);
app.enableShutdownHooks();
await app.listen(Number(process.env.PORT ?? 3001), "0.0.0.0");
}
if (process.env.NODE_ENV !== "test") void bootstrap();