@lark-apaas/fullstack-nestjs-core 1.1.4 → 1.1.6-alpha.0

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.
package/README.md CHANGED
@@ -5,6 +5,7 @@ FullStack NestJS Core 是一个为 NestJS 全栈应用提供核心功能的工
5
5
  ## 特性
6
6
 
7
7
  - **平台模块**: 一站式集成 Config、Logger、Database、Auth 等核心功能
8
+ - **HTTP 客户端**: 自动集成 @nestjs/axios,提供 HTTP 请求能力,自动打印请求日志
8
9
  - **CSRF 保护**: 提供完整的 CSRF Token 生成和验证机制
9
10
  - **用户上下文**: 自动从请求头中提取并注入用户上下文信息
10
11
  - **视图上下文**: 将用户信息和 CSRF Token 注入到模板渲染上下文
@@ -53,6 +54,7 @@ export class AppModule {}
53
54
  `PlatformModule` 自动集成:
54
55
  - ✅ ConfigModule (环境变量配置)
55
56
  - ✅ LoggerModule (日志系统)
57
+ - ✅ HttpModule (HTTP 客户端,自动打印请求日志)
56
58
  - ✅ DataPaasModule (数据库连接)
57
59
  - ✅ AuthNPaasModule (认证系统)
58
60
  - ✅ UserContextMiddleware (用户上下文)
@@ -237,6 +239,169 @@ await DevToolsModule.mount(app, {
237
239
  });
238
240
  ```
239
241
 
242
+ ## HTTP 客户端
243
+
244
+ PlatformModule 自动集成了 `@nestjs/axios`,提供开箱即用的 HTTP 请求能力。
245
+
246
+ ### 特性
247
+
248
+ - ✅ **自动集成**: 导入 PlatformModule 后即可直接使用,无需额外配置
249
+ - ✅ **自动日志**: 所有 HTTP 请求和响应自动打印到日志系统
250
+ - ✅ **标准 API**: 完全遵循 @nestjs/axios 的标准用法
251
+ - ✅ **默认配置**: 自动设置 5 秒超时和最多 5 次重定向
252
+
253
+ ### 基础使用
254
+
255
+ ```typescript
256
+ import { Injectable } from '@nestjs/common';
257
+ import { HttpService } from '@nestjs/axios';
258
+ import { firstValueFrom } from 'rxjs';
259
+
260
+ interface User {
261
+ id: string;
262
+ name: string;
263
+ email: string;
264
+ }
265
+
266
+ @Injectable()
267
+ export class UserService {
268
+ constructor(private readonly httpService: HttpService) {}
269
+
270
+ async getUserById(id: string): Promise<User> {
271
+ const { data } = await firstValueFrom(
272
+ this.httpService.get<User>(`https://api.example.com/users/${id}`)
273
+ );
274
+ return data;
275
+ }
276
+
277
+ async createUser(userData: Partial<User>): Promise<User> {
278
+ const { data } = await firstValueFrom(
279
+ this.httpService.post<User>('https://api.example.com/users', userData)
280
+ );
281
+ return data;
282
+ }
283
+
284
+ async updateUser(id: string, userData: Partial<User>): Promise<User> {
285
+ const { data } = await firstValueFrom(
286
+ this.httpService.put<User>(`https://api.example.com/users/${id}`, userData)
287
+ );
288
+ return data;
289
+ }
290
+
291
+ async deleteUser(id: string): Promise<void> {
292
+ await firstValueFrom(
293
+ this.httpService.delete(`https://api.example.com/users/${id}`)
294
+ );
295
+ }
296
+ }
297
+ ```
298
+
299
+ ### 带配置的请求
300
+
301
+ ```typescript
302
+ async getUserWithHeaders(id: string) {
303
+ const { data } = await firstValueFrom(
304
+ this.httpService.get(`https://api.example.com/users/${id}`, {
305
+ headers: {
306
+ 'Authorization': 'Bearer token',
307
+ 'X-Custom-Header': 'value',
308
+ },
309
+ params: {
310
+ include: 'profile',
311
+ },
312
+ timeout: 10000, // 10秒超时
313
+ })
314
+ );
315
+ return data;
316
+ }
317
+ ```
318
+
319
+ ### 自动日志输出
320
+
321
+ 所有 HTTP 请求会自动打印到日志系统:
322
+
323
+ ```
324
+ [HttpService] HTTP Request {
325
+ method: 'GET',
326
+ url: 'https://api.example.com/users/123',
327
+ headers: { ... },
328
+ params: { include: 'profile' },
329
+ data: undefined
330
+ }
331
+
332
+ [HttpService] HTTP Response {
333
+ method: 'GET',
334
+ url: 'https://api.example.com/users/123',
335
+ status: 200,
336
+ statusText: 'OK',
337
+ data: { id: '123', name: 'John', email: 'john@example.com' }
338
+ }
339
+ ```
340
+
341
+ 错误请求也会自动记录:
342
+
343
+ ```
344
+ [HttpService] HTTP Response Error {
345
+ method: 'GET',
346
+ url: 'https://api.example.com/users/999',
347
+ status: 404,
348
+ statusText: 'Not Found',
349
+ data: { message: 'User not found' },
350
+ message: 'Request failed with status code 404'
351
+ }
352
+ ```
353
+
354
+ ### 高级用法
355
+
356
+ #### 直接访问 Axios 实例
357
+
358
+ ```typescript
359
+ constructor(private readonly httpService: HttpService) {
360
+ // 访问底层的 axios 实例
361
+ const axiosInstance = this.httpService.axiosRef;
362
+
363
+ // 添加自定义拦截器
364
+ axiosInstance.interceptors.request.use((config) => {
365
+ config.headers['X-Custom'] = 'my-value';
366
+ return config;
367
+ });
368
+ }
369
+ ```
370
+
371
+ #### 使用 RxJS 操作符
372
+
373
+ ```typescript
374
+ import { map, catchError } from 'rxjs/operators';
375
+ import { of } from 'rxjs';
376
+
377
+ async getUsers() {
378
+ return this.httpService.get<User[]>('https://api.example.com/users').pipe(
379
+ map(response => response.data),
380
+ catchError(error => {
381
+ console.error('Error fetching users:', error);
382
+ return of([]);
383
+ })
384
+ );
385
+ }
386
+ ```
387
+
388
+ ### 默认配置
389
+
390
+ PlatformModule 注册 HttpModule 时使用以下默认配置:
391
+
392
+ ```typescript
393
+ HttpModule.register({
394
+ timeout: 5000, // 5 秒超时
395
+ maxRedirects: 5, // 最多 5 次重定向
396
+ })
397
+ ```
398
+
399
+ ### 注意事项
400
+
401
+ 1. **记得使用 firstValueFrom**: @nestjs/axios 返回的是 Observable,需要转换为 Promise
402
+ 2. **记得解构 data**: 响应数据在 `response.data` 中
403
+ 3. **类型安全**: 使用泛型指定响应数据类型 `httpService.get<User>(...)`
404
+
240
405
  ## 中间件
241
406
 
242
407
  ### CsrfTokenMiddleware