Giter Site home page Giter Site logo

pmg1989 / nest-axios-interceptor Goto Github PK

View Code? Open in Web Editor NEW

This project forked from narando/nest-axios-interceptor

0.0 0.0 0.0 1.58 MB

Easily manage Interceptors for your Nestjs HttpServices

Home Page: https://npmjs.com/package/@narando/nest-axios-interceptor

License: MIT License

JavaScript 1.75% TypeScript 98.25%

nest-axios-interceptor's Introduction

@narando/nest-axios-interceptor

Easily build and configure axios interceptors for the NestJS HttpModule/HttpService.

NPM Version Package License NPM Downloads Travis

Features

  • Define axios interceptors
  • Register interceptor on HttpService.axiosRef
  • Type-safe handling of custom options in request config

Usage

โš ๏ธ If you want to use @narando/nest-axios-interceptor with NestJS Version 6 or 7, please use the v1 release.

The v2 release is only compatible with NestJS Versions 8 and 9 and @nestjs/axios package.

Installation

Install this module:

$ npm i @narando/nest-axios-interceptor

Creating an AxiosInterceptor

Create a new module and import the HttpModule:

// cats.module.ts
import { HttpModule, HttpService } from "@nestjs/axios";

@Module({
  imports: [HttpModule],
  providers: [CatsService],
})
export class CatsModule {}

Bootstrap your new interceptor with this boilerplate:

// logging.axios-interceptor.ts
import { Injectable } from "@nestjs/common";
import { HttpService } from "@nestjs/axios";
import type { AxiosRequestConfig, AxiosResponse } from "axios";
import {
  AxiosInterceptor,
  AxiosFulfilledInterceptor,
  AxiosRejectedInterceptor,
} from "@narando/nest-axios-interceptor";

@Injectable()
export class LoggingAxiosInterceptor extends AxiosInterceptor {
  constructor(httpService: HttpService) {
    super(httpService);
  }

  // requestFulfilled(): AxiosFulfilledInterceptor<AxiosRequestConfig> {}
  // requestRejected(): AxiosRejectedInterceptor {}
  // responseFulfilled(): AxiosFulfilledInterceptor<AxiosResponse> {}
  // responseRejected(): AxiosRejectedInterceptor {}
}

By default, the interceptor uses identity functions (no-op) for all 4 possible events.

To add your behaviour, override the class methods for the events you want to handle and return a function that will be used in the interceptor.

// logging.axios-interceptor.ts
@Injectable()
export class LoggingAxiosInterceptor extends AxiosInterceptor {
  constructor(httpService: HttpService) {
    super(httpService);
  }

  requestFulfilled(): AxiosFulfilledInterceptor<AxiosRequestConfig> {
    return (config) => {
      // Log outgoing request
      console.log(`Request: ${config.method} ${config.path}`);

      return config;
    };
  }

  // requestRejected(): AxiosRejectedInterceptor {}
  // responseFulfilled(): AxiosFulfilledInterceptor<AxiosResponse> {}
  // responseRejected(): AxiosRejectedInterceptor {}
}

Setting custom options to the request config

If you want to pass-through data from on interceptor function to another, add it to the request config object.

First, define your new request config type. To avoid conflicts with other interceptors, we will define a Symbol and use it as the object key:

// logging.axios-interceptor.ts
const LOGGING_CONFIG_KEY = Symbol("kLoggingAxiosInterceptor");

// Merging our custom properties with the base config
interface LoggingConfig extends AxiosRequestConfig {
  [LOGGING_CONFIG_KEY]: {
    id: number;
  };
}

Now we have to update the interceptor to use this new config:

  // logging.axios-interceptor.ts
  @Injectable()
- export class LoggingAxiosInterceptor extends AxiosInterceptor {
+ export class LoggingAxiosInterceptor extends AxiosInterceptor<LoggingConfig> {
    constructor(httpService: HttpService) {
      super(httpService);
    }

-   requestFulfilled(): AxiosFulfilledInterceptor<AxiosRequestConfig> {
+   requestFulfilled(): AxiosFulfilledInterceptor<LoggingConfig> {
      return (config) => {
        // Log outgoing request
        console.log(`Request: ${config.method} ${config.path}`);

        return config;
      };
    }

    // requestRejected(): AxiosRejectedInterceptor {}
-   // responseFulfilled(): AxiosFulfilledInterceptor<AxiosResponse> {}
+   // responseFulfilled(): AxiosFulfilledInterceptor<AxiosResponseCustomConfig<LoggingConfig>> {}
    // responseRejected(): AxiosRejectedInterceptor {}
  }

With the updated typing, you can now use the extend configuration:

// logging.axios-interceptor.ts
const LOGGING_CONFIG_KEY = Symbol("kLoggingAxiosInterceptor");

@Injectable()
export class LoggingAxiosInterceptor extends AxiosInterceptor<LoggingConfig> {
  constructor(httpService: HttpService) {
    super(httpService);
  }

  requestFulfilled(): AxiosFulfilledInterceptor<LoggingConfig> {
    return (config) => {
      const requestId = 1234;

      config[LOGGING_CONFIG_KEY] = {
        id: requestId,
      };
      // Log outgoing request
      console.log(`Request(ID=${requestId}): ${config.method} ${config.path}`);

      return config;
    };
  }

  // requestRejected(): AxiosRejectedInterceptor {}

  responseFulfilled(): AxiosFulfilledInterceptor<
    AxiosResponseCustomConfig<LoggingConfig>
  > {
    return (response) => {
      const requestId = response.config[LOGGING_CONFIG_KEY].id;
      // Log response
      console.log(`Response(ID=${requestId}): ${response.status}`);

      return response;
    };
  }

  // responseRejected(): AxiosRejectedInterceptor {}
}

Handling Errors

By default, the axios error (rejected) interceptors pass the error with type any. This is not really helpful as we can't do anything with it.

Internally, axios wraps all errors in a custom object AxiosError. We can use the class method isAxiosError to assert that the passed error is indeed of type AxiosError, and then process it how we want:

// logging.axios-interceptor.ts

@Injectable()
export class LoggingAxiosInterceptor extends AxiosInterceptor {
  constructor(httpService: HttpService) {
    super(httpService);
  }

  // requestFulfilled(): AxiosFulfilledInterceptor<AxiosRequestConfig> {}
  // requestRejected(): AxiosRejectedInterceptor {}
  // responseFulfilled(): AxiosFulfilledInterceptor<AxiosResponse> {}

  responseRejected(): AxiosRejectedInterceptor {
    return (err) => {
      if (this.isAxiosError(err)) {
        const { config, response } = err;

        console.log(
          `Error ${response.status} in request "${config.method} ${config.path}`
        );
      } else {
        console.error("Unexpected generic error", err);
      }

      throw err;
    };
  }
}

License

This repository is published under the MIT License.

nest-axios-interceptor's People

Contributors

apricote avatar marcmogdanz avatar renovate-bot avatar renovate[bot] avatar semantic-release-bot avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.