0.5.4 • Published 1 year ago

@maxtan/nest-core v0.5.4

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

@maxtan/nest-core

NestJS 增强工具包,提供了一系列开箱即用的模块和工具,帮助您快速构建高效、规范的 NestJS 应用。

功能特性

  • 日志系统: 基于 log4js 的灵活日志系统,支持控制台、文件、阿里云 SLS 等多种输出方式
  • 缓存模块: 基于 Redis 的高性能缓存解决方案
  • 异常过滤器: 统一的异常处理机制,自动记录异常日志
  • 工具函数库: 常用辅助函数集合
  • 授权模块: 基于 JWT 的认证和授权系统,支持灵活配置

安装

npm install @maxtan/nest-core

# 或使用 pnpm
pnpm add @maxtan/nest-core

使用指南

日志模块

基础配置

import { allLogger } from '@maxtan/nest-core'

// 在应用启动时配置日志
allLogger() // 默认配置,日志输出到控制台和文件

使用日志工具

import { logger } from '@maxtan/nest-core'

// 使用默认logger记录不同级别的日志
logger.debug('调试信息')
logger.info('普通信息')
logger.warn('警告信息')
logger.error('错误信息')
logger.fatal('致命错误')

配置阿里云 SLS 日志

import { allLogger } from '@maxtan/nest-core'

// 配置包含阿里云 SLS 的日志
allLogger(
  {
    accessKeyId: 'your-ak',
    secretAccessKey: 'your-sk',
    projectName: 'your-project',
    logStoreName: 'your-logstore',
    // 可选配置
    endpoint: 'https://cn-hangzhou.log.aliyuncs.com',
    topic: 'myapp',
    env: 'production'
  },
  true // 第二个参数表示是否同时输出到控制台
)

缓存模块

import { CacheModule } from '@maxtan/nest-core'

@Module({
  imports: [
    CacheModule.register(
      {
        url: 'redis://localhost:6379'
        // 其他 Redis 客户端选项
      },
      true
    ) // 第二个参数表示是否全局注册模块
  ]
})
export class AppModule {}

在服务中使用:

import { Injectable } from '@nestjs/common'
import { CacheService } from '@maxtan/nest-core'

@Injectable()
export class YourService {
  constructor(private readonly cacheService: CacheService) {}

  async getData(key: string) {
    // 从缓存获取数据,cacheService.get 会自动解析 JSON
    const cached = await this.cacheService.get(key)
    if (cached) return cached // 直接返回解析后的数据

    // 获取数据并缓存
    const data = await this.fetchData()
    await this.cacheService.set(key, data, 3600) // 缓存1小时,如果是json 需要手动序列号
    return data
  }
}

授权模块

授权模块提供了基于 JWT 的认证和授权功能,可以轻松集成到您的 NestJS 应用中。

基本使用

import { AuthModule } from '@maxtan/nest-core'

@Module({
  imports: [
    AuthModule.register({
      secret: 'your-jwt-secret-key'
    })
  ]
})
export class AppModule {}

自定义配置

您可以自定义 JWT 签名选项:

import { AuthModule } from '@maxtan/nest-core'

@Module({
  imports: [
    AuthModule.register({
      secret: 'your-jwt-secret-key',
      signOptions: {
        expiresIn: '7d', // Token有效期7天
        issuer: 'your-app', // 发行方
        audience: 'your-users' // 目标用户
      }
    })
  ]
})
export class AppModule {}

保护路由

使用 AuthGuard 保护您的路由:

import { Controller, Get, UseGuards } from '@nestjs/common'
import { AuthGuard } from '@maxtan/nest-core'

@Controller('protected')
@UseGuards(AuthGuard)
export class ProtectedController {
  @Get()
  getProtectedData() {
    return { message: '这是受保护的数据' }
  }
}

全局应用 AuthGuard

您可以在应用级别全局应用 AuthGuard,这样所有路由默认都会受到保护:

import { Module } from '@nestjs/common'
import { APP_GUARD } from '@nestjs/core'
import { AuthGuard, AuthModule } from '@maxtan/nest-core'

@Module({
  imports: [
    AuthModule.register({
      secret: 'your-jwt-secret-key'
    })
    // 其他模块...
  ],
  providers: [
    {
      provide: APP_GUARD,
      useClass: AuthGuard
    }
  ]
})
export class AppModule {}

当启用全局 AuthGuard 后,可以使用 @AuthPublic() 装饰器来标记不需要认证的公开路由:

import { Controller, Get } from '@nestjs/common'
import { AuthPublic } from '@maxtan/nest-core'

@Controller('public')
export class PublicController {
  @Get()
  @AuthPublic()
  getPublicData() {
    return { message: '这是公开数据,无需认证' }
  }
}

获取当前用户

从请求中获取当前认证用户:

import { Controller, Get, Request, UseGuards } from '@nestjs/common'
import { AuthGuard } from '@maxtan/nest-core'

@Controller('profile')
@UseGuards(AuthGuard)
export class ProfileController {
  @Get()
  getProfile(@Request() req) {
    // req.user 包含了 JWT payload 中的信息
    return req.user
  }
}

使用 AuthDecorator 获取用户信息

更简洁的方式是使用 AuthDecorator 装饰器来直接获取认证用户信息:

import { Controller, Get, UseGuards } from '@nestjs/common'
import { AuthGuard, AuthDecorator } from '@maxtan/nest-core'

@Controller('profile')
@UseGuards(AuthGuard)
export class ProfileController {
  @Get()
  getProfile(@AuthDecorator() auth) {
    // auth 包含完整的认证用户信息
    return auth
  }

  @Get('username')
  getUsername(@AuthDecorator('username') username: string) {
    // 直接获取指定字段
    return { username }
  }

  @Get('data')
  getData(@AuthDecorator('data') data: any) {
    // 获取自定义数据字段
    return data
  }
}

AuthDecorator 可以接受一个可选的参数,用于指定要获取的 JWT payload 中的字段名。如果不提供参数,将返回整个认证对象。

异常过滤器

异常过滤器会捕获应用中的所有异常,并以统一的格式返回响应,同时记录详细的错误日志:

import { APP_FILTER } from '@nestjs/core'
import { AllExceptionsFilter } from '@maxtan/nest-core'

@Module({
  providers: [
    {
      provide: APP_FILTER,
      useClass: AllExceptionsFilter
    }
  ]
})
export class AppModule {}

配置参考

SlsAppenderOptions

参数类型描述
accessKeyIdstring阿里云访问密钥ID
secretAccessKeystring阿里云访问密钥密码
endpointstringSLS服务端点,默认'https://cn-hangzhou.log.aliyuncs.com'
projectNamestringSLS项目名称
logStoreNamestringSLS日志存储名称
topicstring日志主题,默认'nest'
envstring环境标识,默认'production'

AuthModuleOptions

参数类型描述
secretstring用于签名 JWT 的密钥
signOptionsJwtSignOptionsJWT 签名选项,包含过期时间、发行方等配置

最佳实践

  1. 在启动时配置全局日志:使用 allLogger 函数在应用初始化时配置日志系统,确保所有日志都能被正确捕获。

  2. 使用不同的日志级别:根据信息的重要程度选择合适的日志级别,如调试信息使用 debug,错误信息使用 error 等。

  3. 区分环境配置

    • 开发环境:启用控制台日志,使用较低的日志级别(如 debug)
    • 生产环境:禁用或减少控制台日志,使用较高的日志级别(如 info 或 warn),启用 SLS 日志
  4. 错误处理结合异常过滤器:使用 AllExceptionsFilter 统一处理异常,确保所有异常都被正确记录。

  5. 利用阿里云 SLS 进行日志分析:在生产环境中使用阿里云 SLS 进行集中式日志管理和分析,方便问题排查。

  6. 合理使用缓存:对频繁访问但不常变化的数据使用缓存,并设置合理的过期时间。

  7. 授权与认证安全

    • 使用足够长且复杂的 JWT 密钥
    • 设置合理的 Token 过期时间
    • 考虑在生产环境中使用非对称加密算法(RS256)
    • 实现 Token 刷新机制以提高安全性

许可证

ISC

0.5.4

1 year ago

0.5.3

1 year ago

0.5.2

1 year ago

0.5.1

1 year ago

0.5.0

1 year ago

0.4.1

1 year ago

0.4.0

1 year ago

0.3.0

1 year ago

0.2.0

1 year ago