@hazeljs/core

中文文档
2.1.0发布于 2026/11/17Apache-2.0TypeScriptCommonJS构建来源已验证近 30 天下载 7017

HazelJS的一部分——TypeScript的开源代理OS. 依赖性注射、路由、装饰和基础功能

中文使用文档
文档目录35 节
  1. 为什么?
  2. 特征
  3. 安装
  4. 快速启动
  5. 1. 设立主计长
  6. 2. 创建服务处
  7. 3. 创建模块
  8. 4. 启动申请书
  9. 依赖性注射
  10. 范围
  11. 构造器注入
  12. 运行和装饰
  13. HTTP 方法
  14. 参数装饰器
  15. 自定义元数据和参数装饰器
  16. 中间软件
  17. 全球中间软件
  18. 路由级别中端软件
  19. 全局例外过滤器
  20. 警卫
  21. 截取器
  22. 管道
  23. 验证
  24. 健康检查
  25. 优雅的关机
  26. 例外处理
  27. 测试
  28. 日志
  29. API 参考
  30. 装饰者
  31. 类
  32. 实例
  33. 捐款
  34. 许可证
  35. 链接

@hazeljs/分数

DI,路由,以及代理OS和HTTP API的模块.

内核每个HazelJS应用靴:模块,控制器,依赖性注入,中间软件. OS探员(@hazeljs/agent)运行于同一地点 HazelApp。类型脚本优先。 无快取或收紧依赖.

执行 没有 安装或导入 reflect-metadata 在您的应用程序中——这个软件包宣布并装入.

npm version npm downloads License: Apache-2.0

为什么?

HTTP / DI 层代理 OS 上座. 与 @hazeljs/agent,"技能门","守门员","守门员"和"特工"(Agent VM)在"REST"之外发船耐用剂——没有Nest + LangGraph + 一个工人车队.

完美为:

  • 团队将代理放在与API相同的类型Script后端
  • 以一个框架取代只快件或 DIY DI 堆栈
  • TypeScript- first DI 没有重型HTTP适配器

特征

  • 🎯 依赖性注射 - 与Singleton、Transient和Request Expect 范围有关的高级设计
  • 🎨 基于装饰的 API - 清洁、直观的编程模式
  • 🛣️ 路线 - 有参数提取的内建线路(无快车/快车)
  • 🔌 中间软件支持 - 全球和路由二级中间软件
  • 🛡️ 警卫和拦截器 - 请求验证和转化
  • 🔧 管道 - 数据转换和验证
  • 🏥 健康检查 - 内置活体、准备状态和启动探测器
  • 🛑 优雅的关机 - 适当清理和连接排水
  • 📊 日志 - 以温斯顿为基地的结构化伐木
  • ✅ 验证 - 用类验证器自动请求验证
  • 🧪 测试公用事业 - 配有测试模块的全面测试支持

安装

npm install @hazeljs/core

执行 没有 安装或导入 reflect-metadata 在你的应用程序. @hazeljs/core 声明并在导入时加载. 启用 experimentalDecorators 内 tsconfig.json。 。 。 .

快速启动

1. 设立主计长

import { Controller, Get, Post, Body, Param } from '@hazeljs/core';

@Controller('/users')
export class UserController {
  @Get()
  findAll() {
    return { users: [] };
  }

  @Get('/:id')
  findOne(@Param('id') id: string) {
    return { id, name: 'John Doe' };
  }

  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return { message: 'User created', data: createUserDto };
  }
}

2. 创建服务处

import { Injectable } from '@hazeljs/core';

@Injectable()
export class UserService {
  private users = [];

  findAll() {
    return this.users;
  }

  findOne(id: string) {
    return this.users.find((user) => user.id === id);
  }

  create(data: any) {
    const user = { id: Date.now().toString(), ...data };
    this.users.push(user);
    return user;
  }
}

3. 创建模块

import { HazelModule } from '@hazeljs/core';
import { UserController } from './user.controller';
import { UserService } from './user.service';

@HazelModule({
  controllers: [UserController],
  providers: [UserService],
})
export class AppModule {}

4. 启动申请书

import { HazelApp, BuiltInHealthChecks } from '@hazeljs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await HazelApp.create(AppModule);

  // Register health checks
  app.registerHealthCheck(BuiltInHealthChecks.memoryCheck(500));
  app.registerHealthCheck(BuiltInHealthChecks.eventLoopCheck(100));

  // Register shutdown handlers
  app.registerShutdownHandler({
    name: 'cleanup',
    handler: async () => {
      console.log('Cleaning up resources...');
    },
    timeout: 5000,
  });

  await app.listen(3000);
}

bootstrap();

依赖性注射

范围

import { Injectable, Scope } from '@hazeljs/core';

// Singleton (default) - one instance for entire app
@Injectable()
export class SingletonService {}

// Transient - new instance every time
@Injectable({ scope: Scope.TRANSIENT })
export class TransientService {}

// Request - one instance per HTTP request
@Injectable({ scope: Scope.REQUEST })
export class RequestContextService {}

构造器注入

@Injectable()
export class OrderService {
  constructor(
    private userService: UserService,
    private paymentService: PaymentService
  ) {}

  async createOrder(userId: string) {
    const user = await this.userService.findOne(userId);
    const payment = await this.paymentService.process(user);
    return { user, payment };
  }
}

运行和装饰

HTTP 方法

import { Controller, Get, Post, Put, Delete, Patch } from '@hazeljs/core';

@Controller('/api')
export class ApiController {
  @Get('/items')
  getItems() {}

  @Post('/items')
  createItem() {}

  @Put('/items/:id')
  updateItem() {}

  @Patch('/items/:id')
  patchItem() {}

  @Delete('/items/:id')
  deleteItem() {}
}

参数装饰器

import { Controller, Get, Post, Param, Query, Body, Headers, Req, Res } from '@hazeljs/core';

@Controller('/users')
export class UserController {
  @Get('/:id')
  findOne(@Param('id') id: string, @Query('include') include?: string) {
    return { id, include };
  }

  @Post()
  create(@Body() createUserDto: CreateUserDto, @Headers('authorization') auth: string) {
    return { data: createUserDto, auth };
  }

  @Get('/raw')
  rawAccess(@Req() req: Request, @Res() res: Response) {
    res.json({ message: 'Direct access to req/res' });
  }
}

自定义元数据和参数装饰器

附加自定义元数据, 用于守护或其他层 设置元数据 编号 : 获取元数据,并用 创建 Param 校正器数字 :

import { SetMetadata, getMetadata, createParamDecorator } from '@hazeljs/core';

// Custom metadata (e.g. for guards)
@SetMetadata('roles', ['admin'])
class AdminController {}

// Custom parameter decorator
const CurrentUser = createParamDecorator((_req, ctx) => ctx.user);

@Get('profile')
getProfile(@CurrentUser user: User) {
  return user;
}

使用自定义参数装饰器 无 括号: @CurrentUser见 完整 API 参考 页:1 ParamDecoratorContext 财务报告和审定财务报表 CUSTOM_METADATA_PREFIX。 。 。 .

中间软件

全球中间软件

import { Middleware, type RequestContext } from '@hazeljs/core';

@Injectable()
export class LoggerMiddleware implements Middleware {
  async use(context: RequestContext, next: () => Promise<unknown>) {
    console.log(`${context.method} ${context.url}`);
    return next();
  }
}

// Register globally
const app = await HazelApp.create(AppModule);
app.useGlobalMiddleware(new LoggerMiddleware());

路由级别中端软件

import { Controller, Get, UseMiddleware } from '@hazeljs/core';

@Controller('/admin')
@UseMiddleware(AuthMiddleware)
export class AdminController {
  @Get('/dashboard')
  @UseMiddleware(RoleCheckMiddleware)
  getDashboard() {
    return { data: 'admin dashboard' };
  }
}

全局例外过滤器

import { HazelApp, HttpExceptionFilter, type ExceptionFilter } from '@hazeljs/core';

const app = await HazelApp.create(AppModule);
app.useGlobalExceptionFilter(new HttpExceptionFilter());

警卫

import { CanActivate, ExecutionContext, Injectable, UseGuards } from '@hazeljs/core';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean | Promise<boolean> {
    const token = context.request.headers.authorization;
    return this.validateToken(token);
  }

  private validateToken(token: string | undefined): boolean {
    // Validate JWT token
    return !!token;
  }
}

// Use in controller
@Controller('/protected')
@UseGuards(AuthGuard)
export class ProtectedController {
  @Get()
  getData() {
    return { message: 'Protected data' };
  }
}

截取器

import { Interceptor, Injectable, UseInterceptors, type RequestContext } from '@hazeljs/core';

@Injectable()
export class TransformInterceptor implements Interceptor {
  async intercept(context: RequestContext, next: () => Promise<unknown>) {
    const result = await next();

    return {
      data: result,
      timestamp: new Date().toISOString(),
      path: context.url,
    };
  }
}

// Use globally or per route
@Controller('/api')
@UseInterceptors(TransformInterceptor)
export class ApiController {}

管道

import { Injectable, PipeTransform, type RequestContext } from '@hazeljs/core';

@Injectable()
export class NonEmptyPipe implements PipeTransform<string, string> {
  transform(value: string, _context: RequestContext): string {
    if (!value) {
      throw new Error('Value is required');
    }
    return value;
  }
}

// Prefer the built-in ValidationPipe with class-validator DTOs (see Validation below).

验证

import { IsEmail, IsString, MinLength } from 'class-validator';

export class CreateUserDto {
  @IsEmail()
  email: string;

  @IsString()
  @MinLength(8)
  password: string;

  @IsString()
  name: string;
}

@Controller('/users')
export class UserController {
  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    // Automatically validated before reaching here
    return createUserDto;
  }
}

健康检查

import { HazelApp, BuiltInHealthChecks } from '@hazeljs/core';

const app = await HazelApp.create(AppModule);

// Built-in checks
app.registerHealthCheck(BuiltInHealthChecks.memoryCheck(500)); // 500MB threshold
app.registerHealthCheck(BuiltInHealthChecks.eventLoopCheck(100)); // 100ms lag

// Custom health check
app.registerHealthCheck({
  name: 'database',
  check: async () => {
    try {
      await database.ping();
      return { status: 'healthy' };
    } catch (error) {
      return {
        status: 'unhealthy',
        message: error.message,
      };
    }
  },
  critical: true,
  timeout: 3000,
});

// Endpoints available:
// GET /health  - Liveness probe
// GET /ready   - Readiness probe
// GET /startup - Startup probe

优雅的关机

const app = await HazelApp.create(AppModule);

app.registerShutdownHandler({
  name: 'database',
  handler: async () => {
    await database.disconnect();
    console.log('Database disconnected');
  },
  timeout: 5000,
});

app.registerShutdownHandler({
  name: 'cache',
  handler: async () => {
    await redis.quit();
    console.log('Redis connection closed');
  },
  timeout: 3000,
});

await app.listen(3000);

// On SIGTERM/SIGINT:
// 1. HTTP server stops accepting new connections
// 2. Existing requests complete (up to 10s)
// 3. Shutdown handlers execute in order
// 4. Process exits cleanly

例外处理

import { ExceptionFilter, ExceptionContext } from '@hazeljs/core';

@Injectable()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(error: Error, context: ExceptionContext) {
    const response = context.response;

    response.status(500).json({
      statusCode: 500,
      message: error.message,
      timestamp: new Date().toISOString(),
      path: context.request.url,
    });
  }
}

// Use globally
app.useGlobalExceptionFilter(new HttpExceptionFilter());

测试

import { TestingModule } from '@hazeljs/core';
import { UserController } from './user.controller';
import { UserService } from './user.service';

describe('UserController', () => {
  let module: TestingModule;
  let controller: UserController;
  let service: UserService;

  beforeEach(async () => {
    module = await TestingModule.create({
      controllers: [UserController],
      providers: [
        {
          provide: UserService,
          useValue: {
            findAll: jest.fn().mockResolvedValue([]),
          },
        },
      ],
    });

    controller = module.get(UserController);
    service = module.get(UserService);
  });

  afterEach(async () => {
    await module.close();
  });

  it('should return all users', async () => {
    const result = await controller.findAll();
    expect(result).toEqual([]);
    expect(service.findAll).toHaveBeenCalled();
  });
});

日志

HTTP 请求以下列格式登录: METHOD path status duration (例如:. GET /api/health 200 3ms) (中文(简体) ).

新闻 var默认说明
LOG_LEVELinfo日志级别( 错误、 警告、 信息、 调试)
LOG_HTTPtrue设定为 false 以禁用 HTTP 请求日志
LOG_ENABLEDtrue设定为 false 关闭所有日志

启动和登记日志(控制器、路线、提供者) debug 级别。 使用 LOG_LEVEL=debug 解决麻烦.

API 参考

装饰者

  • @HazelModule(options) - 定义模块
  • @Controller(path) - 定义控制器
  • @Injectable(options?) - 标出可注射类
  • @Get(path?), (中文(简体) ), @Post(path?), (中文(简体) ), @Put(path?), (中文(简体) ), @Delete(path?), (中文(简体) ), @Patch(path?) - HTTP方法
  • @Param(name), (中文(简体) ), @Query(name), (中文(简体) ), @Body(), (中文(简体) ), @Headers(name), (中文(简体) ), @Req(), (中文(简体) ), @Res(), (中文(简体) ), @Ip(), (中文(简体) ), @Host() - 取出参数
  • @UseGuards(...guards), (中文(简体) ), @UseInterceptors(...interceptors), (中文(简体) ), @UsePipes(...pipes) - 应用警卫、拦截器、管道
  • @Public() 编号 : @SkipAuth() - 将路线标为公共路线
  • @Timeout(ms), (中文(简体) ), @Retry(options), (中文(简体) ), @Optional(), (中文(简体) ), @Session() - 每道行为
  • @ApiTags(...tags), (中文(简体) ), @ApiOperation(options) - OpenAPI 元数据
  • 设置元数据( 键, 值) - 将自定义元数据附加到一个类或方法(读取 getMetadata(key, target, propertyKey?)(中文(简体) )
  • 创建ParamDecator( 解析) - 建立自定义参数装饰器,从 (req, context, container)

类

  • HazelApp - 主要申请类别
  • TestingModule - 测试公用事业
  • Logger - 伐木服务

实例

见 实例 完整工作示例目录.

捐款

欢迎捐款! 请读我们的 贡献指南 详细情况.

许可证

Apache 2.0 © 海泽杰斯

版本与发布记录

@hazeljs/core 共发布 135 个版本,首次发布于 2026/02/07;过去 12 个月发布了 135 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.1.0latest2026/11/171 天前
2.0.182026/11/152 天前
2.0.172026/11/143 天前
2.0.162026/11/116 天前
2.0.152026/11/098 天前
2.0.142026/11/0710 天前

其他发布通道:beta → 0.2.0-beta.81,alpha → 0.2.0-alpha.6,rc → 0.2.0-rc.8。

关于 @hazeljs/core 的常见问题

@hazeljs/core 是什么?

HazelJS的一部分——TypeScript的开源代理OS. 依赖性注射、路由、装饰和基础功能

如何安装 @hazeljs/core?

在项目目录运行 npm install @hazeljs/core,或使用 pnpm add / yarn add / bun add。

@hazeljs/core 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@hazeljs/core 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@hazeljs/core 可以商用吗?

@hazeljs/core 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@hazeljs/core 的下载量有多少?

根据 npm 官方下载统计,@hazeljs/core 在 2026/10/18 – 2026/11/16 这 30 天内被下载 7,017 次,日均约 234 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@hazeljs/core 还在维护吗?

最新版本 2.1.0 发布于 2026/11/17(1 天前);至今共发布 135 个版本,其中过去 12 个月发布了 135 个;首次发布于 2026/02/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。