Add global API prefix and route remapping for health checks in main.ts
This commit is contained in:
@@ -1,5 +1,6 @@
|
|||||||
import { ValidationPipe } from '@nestjs/common';
|
import { RequestMethod, ValidationPipe } from '@nestjs/common';
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import type { NextFunction, Request, Response } from 'express';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
@@ -21,6 +22,25 @@ async function bootstrap() {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Prefer a stable `/api/*` surface in all environments.
|
||||||
|
// Some deployments/proxies may strip `/api` (e.g. nginx rewrite), so we also
|
||||||
|
// accept legacy non-prefixed routes by internally re-mapping them.
|
||||||
|
app.setGlobalPrefix('api', {
|
||||||
|
exclude: [{ path: 'health', method: RequestMethod.ALL }],
|
||||||
|
});
|
||||||
|
app.use((req: Request, _res: Response, next: NextFunction) => {
|
||||||
|
if (req.url === '/health' || req.url.startsWith('/health?') || req.url.startsWith('/api/')) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
if (req.url === '/api' || req.url.startsWith('/api?')) {
|
||||||
|
req.url = req.url.replace(/^\/api/, '/api/');
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
|
||||||
|
req.url = `/api${req.url.startsWith('/') ? '' : '/'}${req.url}`;
|
||||||
|
return next();
|
||||||
|
});
|
||||||
|
|
||||||
await app.listen(process.env.PORT ?? 3000);
|
await app.listen(process.env.PORT ?? 3000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user