@hestjs/demo 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +194 -275
  2. package/package.json +9 -9
  3. package/dist/index.js +0 -18829
package/README.md CHANGED
@@ -1,175 +1,156 @@
1
- # HestJS 🚀
1
+ # HestJS Demo Application 🚀
2
2
 
3
- 一个基于 **Hono + Bun + TSyringe** 的现代化 TypeScript 后端框架,提供类似 NestJS 的开发体验,但具有更轻量和更高性能的特点。
3
+ 一个基于 **HestJS** 框架的现代化 TypeScript 演示应用,展示了类似 NestJS 的开发体验,但具有更轻量和更高性能的特点。
4
4
 
5
5
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue.svg)](https://www.typescriptlang.org/)
6
6
  [![Bun](https://img.shields.io/badge/Bun-latest-orange.svg)](https://bun.sh/)
7
7
  [![Hono](https://img.shields.io/badge/Hono-4.x-green.svg)](https://hono.dev/)
8
8
  [![License](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
9
9
 
10
- ## 特性
10
+ ## 🏗️ 项目结构
11
11
 
12
- - 🎯 **装饰器驱动** - 使用装饰器定义控制器、服务、中间件
13
- - 💉 **依赖注入** - 基于 TSyringe 的完整 DI 容器,用户透明
14
- - 🏗️ **模块化架构** - 采用模块系统组织代码
15
- - **高性能** - 基于 Hono 和 Bun 获得最佳性能
16
- - 🔒 **类型安全** - 完全的 TypeScript 支持
17
- - 🛡️ **验证系统** - 基于 TypeBox 的强大验证功能
18
- - 🔄 **拦截器** - 灵活的请求/响应拦截机制
19
- - 🚨 **异常处理** - 完善的异常过滤和处理系统
12
+ ```
13
+ src/
14
+ ├── main.ts # 应用入口点
15
+ ├── app.module.ts # 根模块
16
+ ├── app.controller.ts # 应用控制器
17
+ ├── app.service.ts # 应用服务
18
+ ├── config/ # 配置文件
19
+ │ └── app.config.ts # 应用配置
20
+ ├── common/ # 公共组件
21
+ │ ├── filters/ # 全局过滤器
22
+ │ │ └── http-exception.filter.ts
23
+ │ └── interceptors/ # 全局拦截器
24
+ │ └── response.interceptor.ts
25
+ └── modules/ # 功能模块
26
+ ├── users/ # 用户模块
27
+ │ ├── dto/ # 数据传输对象
28
+ │ │ └── user.dto.ts
29
+ │ ├── entities/ # 实体定义
30
+ │ │ └── user.entity.ts
31
+ │ ├── users.controller.ts
32
+ │ ├── users.service.ts
33
+ │ └── users.module.ts
34
+ └── custom-validation/ # 自定义验证模块
35
+ ├── dto/
36
+ │ └── custom-validation.dto.ts
37
+ ├── custom-validation.controller.ts
38
+ ├── custom-validation.service.ts
39
+ └── custom-validation.module.ts
40
+ ```
20
41
 
21
42
  ## 🚀 快速开始
22
43
 
23
- ### 安装
44
+ ### 安装依赖
24
45
 
25
46
  ```bash
26
- # 克隆项目
27
- git clone https://github.com/aqz236/hest.git
28
- cd HestJS
29
-
30
- # 安装依赖
31
47
  bun install
48
+ ```
32
49
 
33
- # 构建包
34
- bun run build
50
+ ### 开发环境
35
51
 
36
- # 运行示例应用
37
- cd apps/hest-demo
52
+ ```bash
53
+ # 开发模式(热重载)
38
54
  bun run dev
39
- ```
40
-
41
- ### 创建你的第一个应用
42
55
 
43
- ```typescript
44
- // app.controller.ts
45
- import { Controller, Get, Post, Body } from "@hestjs/core";
46
- import { IsString, IsEmail, IsNumber } from "@hestjs/validation";
56
+ # 或者在 monorepo 根目录
57
+ turbo run dev --filter=@hestjs/demo
58
+ ```
47
59
 
48
- export class CreateUserDto {
49
- @IsString({ minLength: 2, maxLength: 50 })
50
- name!: string;
60
+ ### 构建和部署
51
61
 
52
- @IsEmail()
53
- email!: string;
62
+ ```bash
63
+ # 构建
64
+ bun run build
54
65
 
55
- @IsNumber({ minimum: 0, maximum: 120 })
56
- age!: number;
57
- }
66
+ # 生产环境运行
67
+ bun run start:prod
58
68
 
59
- @Controller("/api")
60
- export class AppController {
61
- @Get("/users")
62
- getUsers() {
63
- return { users: [] };
64
- }
65
-
66
- @Post("/users")
67
- createUser(@Body(CreateUserDto) createUserDto: CreateUserDto) {
68
- // createUserDto 已经过验证和类型转换
69
- return { success: true, data: createUserDto };
70
- }
71
- }
69
+ # 创建独立可执行文件
70
+ bun run build:binary
71
+ ./dist/hest-demo
72
72
  ```
73
73
 
74
- ```typescript
75
- // app.module.ts
76
- import { Module } from "@hestjs/core";
77
- import { AppController } from "./app.controller";
78
-
79
- @Module({
80
- controllers: [AppController],
81
- })
82
- export class AppModule {}
83
- ```
74
+ ## 📡 API 文档
84
75
 
85
- ```typescript
86
- // main.ts
87
- import { HestFactory } from "@hestjs/core";
88
- import { ValidationInterceptor } from "@hestjs/validation";
89
- import { AppModule } from "./app.module";
76
+ ### 基础端点
90
77
 
91
- async function bootstrap() {
92
- const app = await HestFactory.create(AppModule);
78
+ - `GET /api` - 应用信息
79
+ - `GET /api/health` - 健康检查
93
80
 
94
- // 启用全局验证
95
- app.useGlobalInterceptors(new ValidationInterceptor());
81
+ ### 用户管理 (`/users`)
96
82
 
97
- await app.listen(3000);
98
- console.log("🚀 Application is running on: http://localhost:3000");
99
- }
83
+ - `GET /users` - 获取所有用户
84
+ - `GET /users/:id` - 获取特定用户
85
+ - `POST /users` - 创建新用户
86
+ - `POST /users/:id` - 更新用户信息
100
87
 
101
- bootstrap();
88
+ #### 请求示例:
89
+
90
+ ```bash
91
+ # 创建用户
92
+ curl -X POST http://localhost:3002/users \
93
+ -H "Content-Type: application/json" \
94
+ -d '{
95
+ "name": "John Doe",
96
+ "email": "john@example.com",
97
+ "age": 30,
98
+ "password": "password123"
99
+ }'
102
100
  ```
103
101
 
104
- ## 📁 项目结构
102
+ ### 自定义验证 (`/api/custom`)
105
103
 
106
- ```
107
- packages/
108
- ├── core/ # 核心框架包
109
- │ ├── decorators/ # 装饰器定义
110
- │ ├── interfaces/ # 核心接口
111
- │ ├── application/ # 应用核心
112
- │ └── exceptions/ # 异常处理
113
- ├── validation/ # 验证模块
114
- │ ├── decorators/ # 验证装饰器
115
- │ ├── pipes/ # 验证管道
116
- │ └── interceptors/ # 验证拦截器
117
- └── ...
104
+ - `GET /api/custom` - 验证功能说明
105
+ - `POST /api/custom/validate` - 测试自定义验证
106
+ - `POST /api/custom/search` - 测试搜索参数验证
107
+ - `GET /api/custom/examples` - 获取验证示例
108
+
109
+ #### 请求示例:
110
+
111
+ ```bash
112
+ # 自定义验证
113
+ curl -X POST http://localhost:3002/api/custom/validate \
114
+ -H "Content-Type: application/json" \
115
+ -d '{
116
+ "username": "john_doe123",
117
+ "role": "user",
118
+ "userId": "123e4567-e89b-12d3-a456-426614174000",
119
+ "phoneNumber": "13812345678",
120
+ "location": { "lat": 39.9042, "lng": 116.4074 },
121
+ "emails": ["john@example.com", "john.doe@company.com"]
122
+ }'
118
123
  ```
119
124
 
120
- ## 🎯 核心概念
125
+ ## 🛠️ 核心功能
121
126
 
122
- ### 控制器 (Controllers)
127
+ ### 1. 模块化架构
123
128
 
124
- ```typescript
125
- @Controller("/users")
126
- export class UserController {
127
- @Get("/")
128
- findAll() {
129
- return { users: [] };
130
- }
131
-
132
- @Get("/:id")
133
- findOne(@Param("id") id: string) {
134
- return { user: { id } };
135
- }
136
-
137
- @Post("/")
138
- create(@Body(CreateUserDto) createUserDto: CreateUserDto) {
139
- return { success: true };
140
- }
141
- }
142
- ```
129
+ - **清晰的模块分离**:每个功能模块都有自己的控制器、服务、DTO 和实体
130
+ - **依赖注入**:使用 `@Injectable()` 和 `@Module()` 装饰器
131
+ - **模块导入/导出**:支持模块间的依赖关系
143
132
 
144
- ### 服务和依赖注入 (Services & DI)
133
+ ### 2. 强类型验证
145
134
 
146
- ```typescript
147
- @Injectable()
148
- export class UserService {
149
- async findAll() {
150
- return [];
151
- }
152
-
153
- async create(userData: any) {
154
- // 创建用户逻辑
155
- return userData;
156
- }
157
- }
135
+ - **TypeBox 集成**:使用 TypeBox 进行运行时类型验证
136
+ - **自定义验证器**:支持复杂的业务逻辑验证
137
+ - **联合类型支持**:支持 TypeScript 的高级类型特性
158
138
 
159
- @Controller("/users")
160
- export class UserController {
161
- constructor(private readonly userService: UserService) {}
139
+ ### 3. 中间件和拦截器
162
140
 
163
- @Get("/")
164
- async findAll() {
165
- return await this.userService.findAll();
166
- }
167
- }
168
- ```
141
+ - **全局异常过滤器**:统一的错误处理
142
+ - **响应拦截器**:统一的响应格式
143
+ - **CORS 支持**:跨域资源共享配置
144
+ - **请求日志**:自动记录请求和响应
145
+
146
+ ### 4. 配置管理
169
147
 
170
- ### 验证系统 (Validation)
148
+ - **环境变量支持**:通过 `.env` 文件配置
149
+ - **类型安全配置**:使用 TypeScript 确保配置的类型安全
171
150
 
172
- #### 基础验证装饰器
151
+ ## 🔧 验证功能展示
152
+
153
+ ### 基础验证
173
154
 
174
155
  ```typescript
175
156
  export class CreateUserDto {
@@ -179,209 +160,147 @@ export class CreateUserDto {
179
160
  @IsEmail()
180
161
  email!: string;
181
162
 
182
- @IsNumber({ minimum: 18, maximum: 100 })
163
+ @IsNumber()
164
+ @Min(0)
165
+ @Max(120)
183
166
  age!: number;
184
-
185
- @IsOptional()
186
- @IsString()
187
- bio?: string;
188
167
  }
189
168
  ```
190
169
 
191
- #### 自定义验证 (TypeBox API)
170
+ ### 高级验证
192
171
 
193
172
  ```typescript
194
- import { Type } from "@sinclair/typebox";
195
- import { Custom, CommonValidators, SchemaFactory } from "@hestjs/validation";
196
-
197
- export class AdvancedDto {
198
- // 使用 TypeBox API 自定义验证
173
+ export class CustomValidationDto {
174
+ // 正则表达式验证
199
175
  @Custom(
200
- Type.String({
201
- minLength: 3,
202
- maxLength: 20,
203
- pattern: "^[a-zA-Z0-9_]+$",
204
- })
176
+ Type.String({ minLength: 3, maxLength: 20, pattern: '^[a-zA-Z0-9_]+$' }),
177
+ { message: '用户名必须是3-20位字母、数字或下划线' },
205
178
  )
206
179
  username!: string;
207
180
 
208
- // 使用联合类型
181
+ // 联合类型验证
209
182
  @Custom(
210
183
  Type.Union([
211
- Type.Literal("admin"),
212
- Type.Literal("user"),
213
- Type.Literal("guest"),
214
- ])
184
+ Type.Literal('admin'),
185
+ Type.Literal('user'),
186
+ Type.Literal('guest'),
187
+ ]),
188
+ { message: '角色必须是 admin、user 或 guest' },
215
189
  )
216
- role!: "admin" | "user" | "guest";
190
+ role!: 'admin' | 'user' | 'guest';
217
191
 
218
- // 使用常用验证器
192
+ // UUID 验证
219
193
  @CommonValidators.UUID()
220
194
  userId!: string;
221
195
 
222
- // 使用便捷构建器
223
- @Custom(SchemaFactory.chinesePhoneNumber())
224
- phoneNumber!: string;
196
+ // 中国手机号验证
197
+ @Custom(SchemaFactory.chinesePhoneNumber(), { optional: true })
198
+ phoneNumber?: string;
225
199
 
226
- // 复杂对象验证
200
+ // 嵌套对象验证
227
201
  @Custom(
228
202
  Type.Object({
229
203
  lat: Type.Number({ minimum: -90, maximum: 90 }),
230
204
  lng: Type.Number({ minimum: -180, maximum: 180 }),
231
- })
205
+ }),
206
+ { optional: true },
232
207
  )
233
- location!: { lat: number; lng: number };
208
+ location?: { lat: number; lng: number };
234
209
  }
235
210
  ```
236
211
 
237
- ### 拦截器 (Interceptors)
238
-
239
- ```typescript
240
- import { Interceptor, ExecutionContext, CallHandler } from "@hestjs/core";
212
+ ## 🎯 架构特点
241
213
 
242
- export class LoggingInterceptor implements Interceptor {
243
- intercept(context: ExecutionContext, next: CallHandler) {
244
- console.log("Before...");
214
+ ### 1. NestJS 风格的目录结构
245
215
 
246
- const now = Date.now();
247
- return next.handle().then(() => {
248
- console.log(`After... ${Date.now() - now}ms`);
249
- });
250
- }
251
- }
216
+ - 模块化组织:每个功能模块独立管理
217
+ - 清晰的职责分离:控制器、服务、DTO、实体分离
218
+ - 可扩展性:易于添加新功能模块
252
219
 
253
- // 使用拦截器
254
- app.useGlobalInterceptors(new LoggingInterceptor());
255
- ```
220
+ ### 2. 现代 TypeScript 开发
256
221
 
257
- ### 异常处理 (Exception Handling)
222
+ - 严格的类型检查
223
+ - 装饰器模式
224
+ - 依赖注入
225
+ - 接口优先设计
258
226
 
259
- ```typescript
260
- import {
261
- HttpException,
262
- NotFoundException,
263
- BadRequestException,
264
- } from "@hestjs/core";
265
-
266
- @Controller("/users")
267
- export class UserController {
268
- @Get("/:id")
269
- findOne(@Param("id") id: string) {
270
- const user = this.findUserById(id);
271
- if (!user) {
272
- throw new NotFoundException(`User with id ${id} not found`);
273
- }
274
- return user;
275
- }
276
-
277
- @Post("/")
278
- create(@Body() userData: any) {
279
- if (!userData.email) {
280
- throw new BadRequestException("Email is required");
281
- }
282
- return this.createUser(userData);
283
- }
284
- }
285
- ```
227
+ ### 3. 高性能运行时
286
228
 
287
- ## 🔧 开发状态
229
+ - Bun 运行时支持
230
+ - Hono 高性能 Web 框架
231
+ - 端口复用优化
232
+ - 生产环境优化
288
233
 
289
- ### 已完成功能
234
+ ## 📦 部署
290
235
 
291
- - **Phase 1: 核心基础设施** ✅
292
- - 装饰器系统 (`@Controller`, `@Injectable`, `@Module`, 路由装饰器)
293
- - 依赖注入容器 (基于 TSyringe)
294
- - 应用工厂 (`HestFactory.create()`)
295
- - 路由系统和参数注入
236
+ ### Docker 部署
296
237
 
297
- - **Phase 2: 中间件和异常处理** ✅
298
- - 异常处理系统 (HttpException, 异常过滤器)
299
- - 拦截器系统 (Interceptor, ExecutionContext)
300
- - 全局拦截器和异常过滤器支持
238
+ ```dockerfile
239
+ FROM oven/bun:1 as base
240
+ WORKDIR /app
301
241
 
302
- - **Phase 3: 验证系统** ✅
303
- - 基于 TypeBox 的验证装饰器
304
- - @Custom() 装饰器支持完整 TypeBox API
305
- - ValidationInterceptor 自动验证
306
- - SchemaFactory 和 CommonValidators
307
- - 详细验证错误处理
242
+ # 复制依赖文件
243
+ COPY package.json bun.lock ./
244
+ RUN bun install --frozen-lockfile
308
245
 
309
- ### 🚧 开发中
246
+ # 复制源代码
247
+ COPY . .
310
248
 
311
- - **Phase 4: 配置和日志系统**
312
- - **Phase 5: 高级拦截器和管道**
313
- - **Phase 6: CLI 工具**
249
+ # 构建应用
250
+ RUN bun run build
314
251
 
315
- ## 📊 性能
252
+ # 运行应用
253
+ CMD ["bun", "run", "start:prod"]
254
+ EXPOSE 3002
255
+ ```
316
256
 
317
- 基于 Bun 运行时和 Hono 框架,HestJS 提供了卓越的性能:
257
+ ### 二进制部署
318
258
 
319
- - 🚀 **快速启动** - 得益于 Bun 的快速启动时间
320
- - ⚡ **高吞吐量** - Hono 的高效路由和中间件系统
321
- - 💾 **低内存占用** - 轻量级架构设计
322
- - 🔧 **编译时优化** - TypeScript 装饰器元数据预处理
259
+ ```bash
260
+ # 构建独立可执行文件
261
+ bun run build:binary
323
262
 
324
- ## 🛠️ 开发
263
+ # 部署单个文件
264
+ ./dist/hest-demo
265
+ ```
325
266
 
326
- ### 构建项目
267
+ ## 🧪 测试
327
268
 
328
269
  ```bash
329
- # 安装依赖
330
- bun install
331
-
332
- # 构建所有包
333
- bun run build
334
-
335
270
  # 运行测试
336
- bun run test
271
+ bun test
337
272
 
338
- # 运行示例应用
339
- cd apps/hest-demo
340
- bun run dev
273
+ # 覆盖率测试
274
+ bun test --coverage
341
275
  ```
342
276
 
343
- ### 测试验证功能
277
+ ## 📝 开发指南
344
278
 
345
- ```bash
346
- # 运行 Phase 3 验证测试
347
- bun test-phase3.ts
348
- ```
279
+ ### 添加新模块
349
280
 
350
- ## 📖 API 参考
281
+ 1. `src/modules/` 下创建新目录
282
+ 2. 创建 `*.module.ts`、`*.controller.ts`、`*.service.ts`
283
+ 3. 在 `app.module.ts` 中导入新模块
351
284
 
352
- ### 装饰器
285
+ ### 添加验证规则
353
286
 
354
- - `@Controller(path?)` - 定义控制器
355
- - `@Injectable()` - 标记可注入服务
356
- - `@Module(options)` - 定义模块
357
- - `@Get(path?)`, `@Post(path?)`, `@Put(path?)`, `@Delete(path?)` - HTTP 路由
358
- - `@Body(dtoClass?)`, `@Param(key?)`, `@Query(key?)` - 参数注入
359
- - `@IsString()`, `@IsEmail()`, `@IsNumber()` - 基础验证
360
- - `@Custom(schema, options?)` - 自定义 TypeBox 验证
287
+ 1. 在模块的 `dto/` 目录下创建 DTO 类
288
+ 2. 使用 `@Custom()` 装饰器定义验证规则
289
+ 3. 在控制器中使用 `@Body()` 装饰器应用验证
361
290
 
362
- ### 核心类
291
+ ### 环境配置
363
292
 
364
- - `HestFactory` - 应用工厂
365
- - `HttpException` - HTTP 异常基类
366
- - `ValidationInterceptor` - 验证拦截器
367
- - `Interceptor` - 拦截器接口
368
- - `ExecutionContext` - 执行上下文
293
+ ```bash
294
+ # .env 文件
295
+ PORT=3002
296
+ NODE_ENV=development
297
+ CORS_ORIGIN=*
298
+ ```
369
299
 
370
300
  ## 🤝 贡献
371
301
 
372
- 欢迎贡献代码!请查看 [贡献指南](CONTRIBUTING.md) 了解详情。
302
+ 欢迎提交 Issue 和 Pull Request!
373
303
 
374
304
  ## 📄 许可证
375
305
 
376
- [MIT](LICENSE)
377
-
378
- ## 🔗 相关链接
379
-
380
- - [Hono](https://hono.dev/) - 快速、轻量级的 Web 框架
381
- - [Bun](https://bun.sh/) - 快速的 JavaScript 运行时
382
- - [TSyringe](https://github.com/microsoft/tsyringe) - 依赖注入容器
383
- - [TypeBox](https://github.com/sinclairzx81/typebox) - JSON Schema 类型构建器
384
-
385
- ---
386
-
387
- ⭐ 如果这个项目对你有帮助,请给个 Star!
306
+ MIT License
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hestjs/demo",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "HestJS Demo Application - A demonstration of HestJS framework capabilities",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -10,9 +10,9 @@
10
10
  ],
11
11
  "scripts": {
12
12
  "dev": "bun run --hot src/index.ts",
13
- "build": "bun build src/index.ts --outdir=dist --target=bun --format=esm --splitting",
14
- "build:external": "bun build src/index.ts --outdir=dist --target=bun --format=esm --external reflect-metadata",
15
- "build:binary": "bun build src/index.ts --compile --outfile=dist/hest-demo",
13
+ "build": "bun build src/index.ts --outdir=dist --target=bun --format=esm --splitting --external pino --external pino-pretty --external sonic-boom --external thread-stream",
14
+ "build:external": "bun build src/index.ts --outdir=dist --target=bun --format=esm --external reflect-metadata --external pino --external pino-pretty --external sonic-boom --external thread-stream",
15
+ "build:binary": "bun build src/index.ts --compile --outfile=dist/hest-demo --external pino-pretty",
16
16
  "start": "bun run dist/index.js | pino-pretty",
17
17
  "start:binary": "./dist/hest-demo | pino-pretty",
18
18
  "start:prod": "NODE_ENV=production bun run dist/index.js | pino-pretty",
@@ -30,15 +30,15 @@
30
30
  "author": "aqz236",
31
31
  "license": "MIT",
32
32
  "dependencies": {
33
- "@hestjs/core": "^0.1.0",
34
- "@hestjs/eslint-config": "^0.1.1",
35
- "@hestjs/typescript-config": "^0.1.0",
36
- "@hestjs/validation": "^0.1.4",
33
+ "@hestjs/core": "^0.1.2",
34
+ "@hestjs/validation": "^0.1.5",
37
35
  "hono": "^4.8.9",
38
36
  "reflect-metadata": "^0.2.2"
39
37
  },
40
38
  "devDependencies": {
41
- "@types/bun": "latest",
39
+ "@hestjs/eslint-config": "^0.1.1",
40
+ "@hestjs/typescript-config": "^0.1.0",
41
+ "@types/bun": "^1.2.19",
42
42
  "jiti": "^2.5.1",
43
43
  "typescript": "5.8.3"
44
44
  },