{"library":"nestjs-http-promise","title":"NestJS HTTP Promise Module with Retries","description":"nestjs-http-promise is a NestJS module that extends the framework's official HTTP capabilities by providing a promise-based API for Axios-powered requests. This library, currently at version 4.0.0, aims to simplify HTTP client interactions by eliminating the need for explicit `.toPromise()` calls on RxJS Observables, which are typically returned by NestJS's default HttpModule. A key differentiator is its out-of-the-box integration of automatic request retries using `axios-retry` and enhanced Axios stack traces for improved debugging. The package generally follows major NestJS and Axios version updates, ensuring compatibility with the latest ecosystem features. It offers both static and asynchronous configuration options, allowing for flexible setup within various NestJS architectural patterns. Its primary function is to provide a more imperative, promise-centric approach to HTTP requests within a declarative NestJS module structure, contrasting with the Observable-first approach of the base NestJS HTTP module.","language":"javascript","status":"active","last_verified":"Wed Apr 22","install":{"commands":["npm install nestjs-http-promise"],"cli":null},"imports":["import { HttpModule } from 'nestjs-http-promise'","import { HttpService } from 'nestjs-http-promise'","import { HttpModuleOptionsFactory } from 'nestjs-http-promise'"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import { Module, Injectable, INestApplication } from '@nestjs/common';\nimport { HttpModule, HttpService, HttpModuleOptionsFactory, HttpModuleOptions } from 'nestjs-http-promise';\nimport { NestFactory } from '@nestjs/core';\n\n// Example of an async configuration service\n@Injectable()\nclass HttpConfigService implements HttpModuleOptionsFactory {\n  async createHttpOptions(): Promise<HttpModuleOptions> {\n    // Simulate fetching configuration data asynchronously, e.g., from a config service or environment variables\n    const configurationData = await Promise.resolve({\n      baseURL: 'https://jsonplaceholder.typicode.com',\n      timeout: 5000,\n      maxRetries: 3,\n      isBetterStackTraceEnabled: true // Enable improved stack traces by default\n    });\n\n    return {\n      baseURL: configurationData.baseURL,\n      timeout: configurationData.timeout,\n      retries: configurationData.maxRetries,\n      isBetterStackTraceEnabled: configurationData.isBetterStackTraceEnabled,\n    };\n  }\n}\n\n@Injectable()\nclass MyApiService {\n  constructor(private readonly httpService: HttpService) {}\n\n  /**\n   * Fetches a post by ID. This call benefits from the module's configured retries.\n   */\n  async fetchPost(id: number): Promise<any> {\n    console.log(`Attempting to fetch post ${id}...`);\n    // The HttpService methods return Promises directly\n    const response = await this.httpService.get(`/posts/${id}`);\n    return response.data;\n  }\n\n  /**\n   * Creates a new post. Retries can be overridden per request.\n   */\n  async createPost(title: string, body: string): Promise<any> {\n    console.log('Attempting to create a new post...');\n    const response = await this.httpService.post('/posts', { title, body, userId: 1 }, {\n      retries: 0 // No retries for create operations for this specific request\n    });\n    return response.data;\n  }\n}\n\n@Module({\n  imports: [\n    // Asynchronously configure HttpModule using a factory class\n    HttpModule.registerAsync({\n      useClass: HttpConfigService,\n    }),\n  ],\n  providers: [MyApiService, HttpConfigService], // HttpConfigService must be provided if used with useClass\n  exports: [MyApiService], // Export the service if it's used by other modules\n})\nclass ApiIntegrationModule {}\n\nasync function bootstrap() {\n  const app: INestApplication = await NestFactory.create(ApiIntegrationModule);\n  await app.listen(3000, () => {\n    console.log('NestJS Application listening on port 3000');\n  });\n\n  const apiService = app.get(MyApiService);\n\n  try {\n    const post = await apiService.fetchPost(1);\n    console.log('\\nFetched Post 1:', post);\n\n    const newPost = await apiService.createPost('Hello Registry', 'This is a test post from the registry quickstart.');\n    console.log('\\nCreated New Post:', newPost);\n  } catch (error: any) {\n    console.error('\\nAn error occurred during API calls:');\n    console.error('Error message:', error.message);\n    if (error.response) {\n      console.error('Response status:', error.response.status);\n      console.error('Response data:', error.response.data);\n    } else if (error.code === 'ECONNABORTED') {\n      console.error('Request timed out or cancelled.');\n    }\n  } finally {\n    await app.close();\n    console.log('\\nApplication closed.');\n  }\n}\n\n// To run this quickstart, save it as a .ts file in a NestJS project and execute with `ts-node` or compile.\n// In a real application, `bootstrap()` would be called from `main.ts`.\nbootstrap();","lang":"typescript","description":"This quickstart demonstrates how to install, configure (asynchronously), inject, and use `nestjs-http-promise` to perform promise-based HTTP requests with built-in retries, fetching and creating a test post.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}