NestJS
NestJS 是一个基于 TypeScript/Node.js 的企业级后端框架,采用模块化设计,融合了 OOP(面向对象编程)、FP(函数式编程)和微服务架构。它底层支持 Express/Fastify,提供依赖注入、装饰器路由、GraphQL 集成等特性,适合构建高效、可维护的服务器端应用,尤其契合全栈 TypeScript 开发。
本指南将详细介绍如何在 CloudBase HTTP 云函数上开发和部署 NestJS 应用程序。
前提条件
在开始之前,请确保您已具备以下条件:
- Node.js 环境:版本 16.13 或更高(推荐 18.15+)
- npm 或 yarn:包管理工具
- NestJS CLI:全局安装 NestJS 命令行工具
- CloudBase 账号:已注册腾讯云账号并开通云开发服务
环境准备
1. 安装 NestJS CLI
# 全局安装 NestJS CLI
npm install -g @nestjs/cli
# 验证安装
nest --version
2. 创建 NestJS 应用
如果您已有 NestJS 应用,可以跳过此步骤。
# 创建新的 NestJS 应用
nest new nest-cloudbase-app
# 进入项目目录
cd nest-cloudbase-app
选择包管理器(推荐使用 npm):
? Which package manager would you ❤️ to use? (Use arrow keys)
❯ npm
yarn
pnpm
应用开发
1. 项目结构
创建完成后,您将得到以下项目结构:
nest-cloudbase-app/
├── src/
│ ├── app.controller.ts # 应用控制器
│ ├── app.module.ts # 应用模块
│ ├── app.service.ts # 应用服务
│ └── main.ts # 应用入口文件
├── test/ # 测试文件
├── package.json
├── tsconfig.json
└── nest-cli.json
2. 修改应用入口文件
编辑 src/main.ts 文件,配置端口为 9000(CloudBase HTTP 云函数要求):
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// 启用 CORS
app.enableCors({
origin: true,
credentials: true,
});
// CloudBase HTTP 云函数要求使用 9000 端口
const port = process.env.PORT || 9000;
await app.listen(port, '0.0.0.0');
console.log(`Application is running on: http://localhost:${port}`);
}
bootstrap();
3. 创建示例 API
创建用户模块
# 生成用户模块
nest generate module users
nest generate controller users
nest generate service users
编辑用户控制器
编辑 src/users/users.controller.ts:
import { Controller, Get, Post, Body, Param, Put, Delete } from '@nestjs/common';
import { UsersService } from './users.service';
export interface User {
id: number;
name: string;
email: string;
}
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get()
findAll(): User[] {
return this.usersService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string): User {
return this.usersService.findOne(+id);
}
@Post()
create(@Body() user: Omit<User, 'id'>): User {
return this.usersService.create(user);
}
@Put(':id')
update(@Param('id') id: string, @Body() user: Partial<User>): User {
return this.usersService.update(+id, user);
}
@Delete(':id')
remove(@Param('id') id: string): { message: string } {
this.usersService.remove(+id);
return { message: `User ${id} deleted successfully` };
}
}