feat: 添加API路由和CORS配置

- 为AppController添加api/v1/templates路由前缀
- 改进API响应格式,统一返回ApiResponse结构
- 添加错误处理和类型定义
- 启用CORS支持多平台访问
- 添加服务启动日志信息
This commit is contained in:
杨明明 2025-09-03 18:29:03 +08:00
parent e30d7cc4da
commit d2a4db2863
2 changed files with 71 additions and 8 deletions

View File

@ -1,21 +1,66 @@
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { TemplateService } from './templates/index'
@Controller()
import { Template } from './templates/types';
interface ApiResponse<T = any> {
status: boolean | string;
data: T;
msg: string;
}
@Controller('api/v1/templates')
export class AppController {
constructor(private readonly tempalte: TemplateService) { }
@Get()
async getTemplates() {
return this.tempalte.getAllTemplates();
async getTemplates(): Promise<ApiResponse<Template[]>> {
const templates = this.tempalte.getAllTemplates();
return {
status: true,
data: templates,
msg: 'success'
};
}
@Get(':templateCode')
async getTemplate(@Param('templateCode') templateCode: string) {
return this.tempalte.getTemplate(templateCode);
async getTemplate(@Param('templateCode') templateCode: string): Promise<ApiResponse<Template | null>> {
const template = this.tempalte.getTemplate(templateCode);
if (template) {
return {
status: true,
data: template,
msg: 'success'
};
}
return {
status: false,
data: null,
msg: '模板不存在'
};
}
@Post()
async executeTemplate(@Body('imageUrl') imageUrl: string, @Body('templateCode') templateCode: string) {
return this.tempalte.executeTemplate(templateCode, imageUrl);
async executeTemplate(@Body('imageUrl') imageUrl: string, @Body('templateCode') templateCode: string): Promise<ApiResponse<string | null>> {
try {
const result = await this.tempalte.executeTemplate(templateCode, imageUrl);
if (result) {
return {
status: true,
data: result,
msg: 'success'
};
}
return {
status: false,
data: null,
msg: '执行失败'
};
} catch (e) {
return {
status: false,
data: null,
msg: e.message
};
}
}
}

View File

@ -3,6 +3,24 @@ import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
// 启用 CORS 支持多平台访问
app.enableCors({
origin: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
credentials: true,
});
// 设置全局前缀
app.setGlobalPrefix('');
const port = process.env.PORT ?? 3000;
await app.listen(port);
console.log(`🚀 多平台小程序后台服务启动成功!`);
console.log(`📡 服务地址: http://localhost:${port}`);
console.log(`📋 模板管理 API: http://localhost:${port}/api/v1/templates`);
console.log(`🔗 Webhook API: http://localhost:${port}/api/v1/webhook`);
}
bootstrap();