AI Briefing
KO

Building an HTTP Client That's Flexible to Change

·2023.07.23 22:00

Key point

Shares the experience of designing a WebClientModule for Nest.js that minimizes external library dependency and improves testability.

Details

Nest.js's default HTTP Module has drawbacks: it returns an Observable, which is inconvenient for one-off requests, and it directly returns AxiosResponse, which increases dependency on a specific library. This causes a violation of the OCP (Open-Closed Principle), requiring the entire service code to be modified when the library is replaced.

To solve this, we designed and use our own WebClientModule, which hides the internal implementation and exposes only the core interface. This module consists of the following key components:

  • WebClient: An interface that applies the Builder pattern to configure HTTP methods and perform requests
  • BodyInserter: A class that supports creating various forms of Body—JSON, Form Data, Text, etc.—according to Content-Type
  • ResponseSpec: A class that provides the HTTP status code and response body, and includes a toEntity method that converts the response into a specific class instance

Through this structure, we can flexibly respond to changes in external libraries while designing the business logic so that it does not depend on the specs of external tools.

This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.

Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.