用于构建高效且可扩展的服务器端应用程序的渐进式 Node.js 框架,深受 Angular 的启发。
Nest framework TypeScript starter repository.
包管理器使用 pnpm
,可以使用 npm
或 yarn
安装依赖。
$ pnpm install
# development 开发环境
$ pnpm run start
# watch mode 监听文件变化
$ pnpm run start:dev
# production mode 生产环境
$ pnpm run start:prod
使用 cross-env NODE_ENV=development
为不同环境设置变量。
可用于加载不同的配置文件。
{ "start:dev": "cross-env NODE_ENV=development nest start --watch" }
src/config/configuration.ts
文件中进行配置。
根据不同环境加载 .env
文件在 src/app.module.ts
修改(可能更喜欢单文件配置)。
在项目中使用 ConfigService
来获取配置。
// 注入
@Injectable()
export class HashingService {
constructor(private readonly configService: ConfigService<Configuration>) {}
async hash(value: string): Promise<string> {
return await bcrypt.hash(value, this.configService.get('saltRounds'));
}
}
// 在 main 中使用
const configService = app.get(ConfigService);
const PORT = configService.get<number>('port');
默认使用 redis
缓存,设置 REDIS_DISABLE=true
使用 memory
。
src/modules/auth/auth.module.ts
src/modules/auth/auth.service.ts
中使用 CacheService
来获取缓存。
接口限速
同上,使用的 redis 和内存缓存。
@Module({
imports: [
ThrottlerModule.forRootAsync({
inject: [ConfigService],
useFactory: async (conifg: ConfigService<Configuration>) => ({
ttl: 60,
limit: conifg.get('rateLimitMax'),
storage: conifg.get('REDIS_DISABLE')
? null
: new ThrottlerStorageRedisService(),
}),
}),
AuthModule,
],
providers: [
{
/** 节流器 */
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
})
export class AppModule {}
见 src/modules/auth
参考 src/decorators/auth.decorator.ts
中的装饰器进行鉴权。根据实际修改。
方法装饰器 @Auth('admin')
表示需要 admin 权限。
参数装饰器 @UserReq() user: User
获取已登录用户信息(会访问数据库)。
同上 @UserJwt() user: JwtDto
获取 JWT 用户信息(不会访问数据库)。
方法装饰器 AuthUnlogin()
表示可以不需要登录,但会尝试获取用户登录信息。
日志使用 winston
来记录。
见 src/config
和 src/middleware/logger.middleware.ts
。
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.
Nest is MIT licensed.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。
1. 开源生态
2. 协作、人、软件
3. 评估模型