跳转到内容

API Reference

@maxtan/nest-core 全部公开 API 速查索引。所有导出均通过 import { ... } from '@maxtan/nest-core' 引入。


模块(Modules)

所有模块提供 forRoot() / register() 双入口,global 默认 true 且可通过选项禁用。

模块配置类型说明
AuthModuleAuthModuleOptionsJWT 认证(Guard + Strategy + CLS 上下文)
CacheModuleCacheModuleOptionsRedis 缓存(ioredis 封装)
HealthModuleHealthModuleOptions健康检查(动态发现 + 并行检测)
LoggerModuleLoggerModuleOptions日志(Winston + SLS + 每日轮转)
MultipartModuleMultipartModuleOptions文件上传(Fastify 流式解析)
OperationModuleOperationModuleOptions操作审计(TraceID + 脱敏)
TransformModuleTransformModuleOptions响应转换(标准包装 + 日期转换)
PrismaModulePrismaModuleOptionsPrisma 数据访问层

类型(Types)

响应

typescript
interface Res<T = any> {
  code: number
  data: T
  message: string
  success: boolean
  timestamp: number
  traceId?: string
}

type SuccessRes<T = any> = Res<T> & { code: HttpStatus.OK }
type ErrorRes = Res<null>
type PageRes<T = any> = SuccessRes<Page<T>>

分页

typescript
interface PageQuery { current?: number; size?: number; sortBy?: string; sortOrder?: 'asc' | 'desc' }
interface Page<T = any> { size: number; current: number; total: number; pages: number; records: T[] }

认证

typescript
interface AuthModuleOptions {
  secret: string
  global?: boolean
  signOptions?: JwtSignOptions
  fieldMapping?: Record<string, string>
}

interface JwtStandardPayload {
  exp?: number; iat?: number; iss?: string; jti?: string
  sub?: string; aud?: string | string[]; nbf?: number
}

interface AuthPayload extends JwtStandardPayload {
  userId?: string; username?: string; account?: string
  jtd?: string; decryptedData?: Record<string, unknown>
  [key: string]: unknown
}

通用

typescript
enum MSG {
  SUCCESS, FAIL, PARAMETER_ERROR, PROGRAM_ERROR, DATA_ERROR,
  FORBIDDEN, NOT_TOKEN, INVALID_TOKEN, EXPIRED_TOKEN,
  NOT_FOUND, NOT_FOUND_DATA, UNAUTHORIZED
}

enum INJECT_ENUM {
  CACHE_OPTIONS, AUTH_OPTIONS, MULTIPART_OPTIONS,
  OPERATION_OPTIONS, TRANSFORM_OPTIONS, HEALTH_OPTIONS, LOGGER_OPTIONS
}

type ID = string | number
type Timestamp = number
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | 'HEAD'
type SortOrder = 'asc' | 'desc' | 'ASC' | 'DESC'
type Nullable<T> = T | null
type Undef<T> = T | undefined
type Maybe<T> = T | null | undefined

装饰器(Decorators)

装饰器签名说明
@AuthPublic()() => MethodDecorator标记路由为公开(跳过 AuthGuard)
@CurrentUser()(key?: keyof AuthPayload) => ParameterDecorator获取当前认证用户信息
@Multipart()(options?: MultipartDecoratorOptions | ZodType) => MethodDecorator启用 multipart 解析
@MultipartData()() => ParameterDecorator获取解析后的 multipart 数据
@XmlDecorator()() => ParameterDecorator解析 XML 请求体
@Operation()(options?: OperationOptions) => MethodDecorator操作审计配置
@PrismaTransactional()(options?: PrismaTransactionalOptions) => MethodDecorator声明式事务

管道(Pipes)

typescript
// Zod 验证管道
class ZodPipe implements PipeTransform { constructor(schema: ZodType, options?: ZodPipeOptions) }
const Zod = (schema: ZodType, options?: ZodPipeOptions) => new ZodPipe(schema, options)

// Zod 错误格式化
function getZodError(error: ZodError, showAll?: boolean, separator?: string): string
function getZodError(error: ZodError, schema: ZodType, showAll?: boolean, separator?: string): string

// Multipart 管道
class MultipartPipe { constructor(reflector: Reflector, options?: MultipartPipeOptions) }

拦截器 & 过滤器

typescript
// 响应拦截器(TransformModule 自动注册)
class ResponseInterceptor<T> implements NestInterceptor<T, Res<T>>

// 全局异常过滤器
class AllExceptionsFilter extends BaseExceptionFilter

异常类

typescript
class AppException extends HttpException { constructor(message: string, code?: number) }
class CacheNotReadyException extends Error {}

Prisma 数据访问层

核心类

typescript
abstract class PrismaBaseService<C extends PrismaClientLike> implements OnModuleInit, OnModuleDestroy
abstract class PrismaRepository<T = any>
class PrismaQueryBuilder<T extends Record<string, any>>

查询工具

typescript
// 分页
function prismaPage<T>(model: PrismaModel, params: PrismaPageParams): Promise<Page<T>>
function prismaPaginate(current?: number, size?: number): { skip: number; take: number }

// 搜索 & 过滤
function prismaKeyword(keyword: string | undefined, fields: string[]): Record<string, any> | undefined
function prismaContains<T>(query: T, fields: string[], mode?: PrismaContainsMode): Record<string, any>

// 排序(支持白名单)
function prismaOrderBy(sortBy?: string, sortOrder?: PrismaSortOrder, allowedFields?: string[]): Record<string, PrismaSortOrder> | undefined

// 组合查询构建
function buildPrismaQuery<T>(params: BuildPrismaQueryParams<T>): { where; skip?; take?; orderBy? }

// 日期范围
interface DateRangeField { start: string; end: string; target: string }

中间件

typescript
// 软删除扩展
function createSoftDeleteExtension(options?: SoftDeleteMiddlewareOptions): PrismaExtensionObject
function discoverSoftDeleteModels(client: PrismaClientLike, field?: string): string[]

// 审计扩展
function createAuditExtension(options?: AuditMiddlewareOptions): PrismaExtensionObject
function discoverAuditModels(client: PrismaClientLike, createdByField?: string, updatedByField?: string): string[]

// 审计字段常量
const PRISMA_AUDIT_COLUMNS: { createdBy: string; updatedBy: string }

事务

typescript
function PrismaTransactional(options?: PrismaTransactionalOptions): MethodDecorator
function usePrismaClient<T>(prisma: T): T
function usePrisma<T>(holder: T): T
function isInTransaction(): boolean

CRUD & 工具

typescript
function prismaSoftRemove(delegate: any, where: any, options?: SoftRemoveOptions): Promise<any>
function prismaExists(delegate: any, where: any): Promise<boolean>

字段选择

typescript
function prismaExclude(client: PrismaClientLike, model: string, exclude: string[]): PrismaSelectObject
function prismaSelect(client: PrismaClientLike, model: string, select: string[]): PrismaSelectObject
function getScalarFields(client: PrismaClientLike, model: string): string[]
function prismaExcludeSets(client: PrismaClientLike, model: string, setName: string): PrismaSelectObject
const PrismaFieldSets: Record<string, Record<string, string[]>>

树结构

typescript
function buildTree<T>(items: T[], options?: PrismaTreeOptions<T>): TreeNode<T>[]
function flattenTree<T>(tree: TreeNode<T>[], depth?: number): (T & { _depth: number })[]
function findTreeNode<T>(tree: TreeNode<T>[], predicate: (node: TreeNode<T>) => boolean): TreeNode<T> | undefined
function getTreePath<T>(tree: TreeNode<T>[], predicate: (node: TreeNode<T>) => boolean): TreeNode<T>[]

type TreeNode<T> = T & { children: TreeNode<T>[] }

元数据 & Zod

typescript
function getModelsMeta(client: object): PrismaModelMeta[]
function getModelFields(client: PrismaClientLike, modelName: string): PrismaFieldInfo[]
function generateZodSuggestions(client: PrismaClientLike, modelName: string, options?: object): string
function listPrismaModels(client: PrismaClientLike): string[]

瞬态错误重试

typescript
function wrapWithRetryableRaw(client: RetryableClient, options?: PrismaRetryOptions): void
interface PrismaRetryOptions { maxRetries?: number; baseDelayMs?: number }

工具函数(Utils)

响应

typescript
function resMessage<T>(data: T, message: string): ResMessage<T>
function buildRes<T>(data?: T, message?: string, traceId?: string): Res<T>
function buildErrorRes<T>(message: string, status?: number, data?: T, traceId?: string): Res<T>
function getBasePage<T>(size?: number, current?: number): Page<T>
class ResMessage<T> { constructor(data: T, message: string) }

加密

typescript
function encryptAES(data: string, key: string | Buffer): string
function decryptAES(encryptedData: string, key: string | Buffer): string

ID 生成

typescript
function generateSnowflakeId(): string
function guid(): string              // UUID v4
function generateHex(length: number): string  // 指定长度十六进制
function randomDigits6(): string     // 6 位随机数字
function randomHex4(): string        // 4 位十六进制

对象

typescript
function isEmpty(value: unknown): boolean
function isNotEmpty(value: unknown): boolean
function isPlainObject(value: unknown): boolean
function cleanObject<T>(obj: T, options?: CleanObjectOptions): Partial<T>
const CleanObjectPresets: { full: CleanObjectOptions }

日期

typescript
function formatDate(date: Date | null | undefined, formatStr: string): string

日志

typescript
const logger: winston.Logger
function createLogger(options?: AllLoggerOptions): void
class WinstonLoggerService implements LoggerService

缓存

typescript
class LRUCache<K, V> {
  constructor(maxSize?: number, ttl?: number)
  get(key: K): V | undefined
  set(key: K, value: V): void
  has(key: K): boolean
  delete(key: K): boolean
  clear(): void
  get size(): number
}

Snowflake

typescript
function createSnowflake(options?: SnowflakeOptions): SnowflakeInstance
function decodeSnowflakeTimestamp(id: string | bigint, epoch?: number | Date): number
function getSnowflakeDate(id: string | bigint, epoch?: number | Date): Date

环境变量

typescript
function validateEnv<T extends ZodType>(schema: T): z.infer<T>
function validateEnv<T extends ZodType>(schema: T, options: { onError: 'log' }): z.infer<T> | null
function validateEnv<T extends ZodType>(schema: T, options: { onError: 'throw' }): z.infer<T>
class EnvValidationError extends Error { issues: ZodError['issues'] }

// 环境变量预处理器
function zPort(): ZodType
function zBoolEnv(): ZodType
function zEnvStr(): ZodType
function zEnvNum(toInt?: boolean): ZodType

Zod 预处理器

字符串

工具行为
zStrtrim + 空→undefined + optional
zStrEmptytrim + 保留空串
zStrNulltrim + 空→null + nullable
zVarChar(max, min?)Prisma VarChar 对齐
zVarCharNull(max, min?)Prisma VarChar + nullable

数值

工具行为
zNum(toInt?)string→number + NaN/Infinity 防护
zIntzNum(true) 快捷方式
zDecimal(precision?, scale?)Prisma Decimal 对齐

布尔 & 日期

工具行为
zBool'true'/'1'/'yes'/'false'/'0'/'no' 智能解析
zDateISO 字符串 / 13位 / 10位时间戳 → Date

数组 & 枚举

工具行为
zArr逗号分隔字符串→数组
zArrOf(options?)自定义分隔符 + 去重
zStrArr(options?)字符串数组
zEnumInt(...values)整数枚举
zEnumStr(...values)字符串枚举
zJson<T>()JSON 字符串自动解析

分页 & 查询

工具行为
zPage(options?)分页 Schema 工厂
zPageWithKeyword(options?)分页 + keyword
zDateRange(options?)日期范围(start/end)
zQueryInt(options?)HTTP 查询参数→整数
zQueryId(options?)HTTP 查询参数→ID
zQueryEnumInt(...values)HTTP 查询参数→整数枚举
zQueryEnumStr(...values)HTTP 查询参数→字符串枚举

其他

工具行为
zId非空字符串 ID
zIds字符串 ID 数组