feat: add Vercel serverless adapter for NestJS
This commit is contained in:
parent
c505421544
commit
1de8bae73d
|
|
@ -0,0 +1,66 @@
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { ExpressAdapter } from '@nestjs/platform-express';
|
||||||
|
import { AppModule } from '../dist/app.module';
|
||||||
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
|
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||||
|
import * as express from 'express';
|
||||||
|
|
||||||
|
// 缓存 app 实例,避免每次冷启动都重新创建
|
||||||
|
let cachedApp: any;
|
||||||
|
|
||||||
|
async function bootstrap() {
|
||||||
|
if (!cachedApp) {
|
||||||
|
const expressApp = express();
|
||||||
|
const app = await NestFactory.create(
|
||||||
|
AppModule,
|
||||||
|
new ExpressAdapter(expressApp),
|
||||||
|
);
|
||||||
|
|
||||||
|
// 配置 CORS
|
||||||
|
app.enableCors({
|
||||||
|
origin: [
|
||||||
|
'https://tradingadvfrontend.vercel.app',
|
||||||
|
'http://localhost:8000',
|
||||||
|
'http://localhost:3030',
|
||||||
|
],
|
||||||
|
credentials: true,
|
||||||
|
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
|
||||||
|
allowedHeaders: [
|
||||||
|
'Content-Type',
|
||||||
|
'Authorization',
|
||||||
|
'Accept',
|
||||||
|
'Origin',
|
||||||
|
'Referer',
|
||||||
|
'User-Agent',
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 全局验证管道
|
||||||
|
app.useGlobalPipes(
|
||||||
|
new ValidationPipe({
|
||||||
|
whitelist: true,
|
||||||
|
forbidNonWhitelisted: true,
|
||||||
|
transform: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Swagger 文档
|
||||||
|
const config = new DocumentBuilder()
|
||||||
|
.setTitle('API 文档')
|
||||||
|
.setVersion('1.0')
|
||||||
|
.addBearerAuth()
|
||||||
|
.build();
|
||||||
|
const document = SwaggerModule.createDocument(app, config);
|
||||||
|
SwaggerModule.setup('api', app, document);
|
||||||
|
|
||||||
|
await app.init();
|
||||||
|
cachedApp = expressApp;
|
||||||
|
}
|
||||||
|
return cachedApp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vercel Serverless handler
|
||||||
|
export default async function handler(req: any, res: any) {
|
||||||
|
const app = await bootstrap();
|
||||||
|
app(req, res);
|
||||||
|
}
|
||||||
|
|
@ -2,14 +2,14 @@
|
||||||
"version": 2,
|
"version": 2,
|
||||||
"builds": [
|
"builds": [
|
||||||
{
|
{
|
||||||
"src": "dist/main.js",
|
"src": "api/index.ts",
|
||||||
"use": "@vercel/node"
|
"use": "@vercel/node"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"routes": [
|
"routes": [
|
||||||
{
|
{
|
||||||
"src": "/(.*)",
|
"src": "/(.*)",
|
||||||
"dest": "dist/main.js"
|
"dest": "api/index.ts"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"buildCommand": "npx nest build",
|
"buildCommand": "npx nest build",
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue