GithubHelp home page GithubHelp logo

nestjs / axios Goto Github PK

View Code? Open in Web Editor NEW
202.0 202.0 46.0 4.48 MB

Axios module for Nest framework (node.js) 🗂

Home Page: https://docs.nestjs.com/techniques/http-module

License: MIT License

JavaScript 12.25% TypeScript 85.58% Shell 2.17%
axios http-module javascript nest nestjs nodejs typescript

axios's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

circleci
.circleci/config.yml
  • cimg/node 21.6
npm
package.json
  • @commitlint/cli 19.2.1
  • @commitlint/config-angular 19.1.0
  • @nestjs/common 10.3.7
  • @nestjs/core 10.3.7
  • @nestjs/platform-express 10.3.7
  • @nestjs/testing 10.3.7
  • @types/jest 29.5.12
  • @types/node 20.12.7
  • @typescript-eslint/eslint-plugin 7.6.0
  • @typescript-eslint/parser 7.6.0
  • axios 1.6.8
  • eslint 8.57.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-import 2.29.1
  • husky 9.0.11
  • jest 29.7.0
  • lint-staged 15.2.2
  • prettier 3.2.5
  • reflect-metadata 0.2.2
  • release-it 17.2.0
  • rimraf 5.0.5
  • rxjs 7.8.1
  • ts-jest 29.1.2
  • typescript 5.4.5
  • @nestjs/common ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0
  • axios ^1.3.1
  • rxjs ^6.0.0 || ^7.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

this library does not support Nestjs 10.0.0

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

this library does not support Nestjs 10.0.0

Minimum reproduction code

this library does not support Nestjs 10.0.0

Steps to reproduce

No response

Expected behavior

this library does not support Nestjs 10.0.0

Package version

2.0.0

NestJS version

10.0.0

Node.js version

18.16.0

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

this library does not support Nestjs 10.0.0

Publish a new version with newest axios

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

Latest published version of https://github.com/nestjs/axios still relies on axios 0.23.0.

Describe the solution you'd like

Publish a new version, since the master branch already supports 0.24.0.

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

Be able to update nestjs and axios.

Current axios version used 1.2.1 has Bug with Brotli, bump needed to 1.2.2

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

This could happen when you perform request to 3rd party service which supports Brotli compression axios/axios#5346

Minimum reproduction code

axios/axios#5346

Steps to reproduce

Any http request to 3rd party like instagram/facebook api will return Error: unexpected end of file

Expected behavior

Successful response

Package version

1.0.1

NestJS version

8.1.3

Node.js version

16.18.0

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

Add ability to add types for data object in HttpService

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

Currently all methods of the HttpService take a <T = any> generic parameter, but type data?; any. It would be nice to enforce types on the data object that gets passed to either AxiosRequestConfig or the data parameter, respectively. This also allow it to be compliant with the types that Axios themselves have in their library.

Describe the solution you'd like

Retype the HttpService as follows:

import { AxiosInstance, AxiosPromise, AxiosRequestConfig, AxiosResponse } from "axios";
import { Observable } from "rxjs";

export declare class HttpService {
  protected readonly instance: AxiosInstance;
  constructor(instance?: AxiosInstance);
  request<T = any, D = any>(config: AxiosRequestConfig<D>): Observable<AxiosResponse<T>>;

  get<T = any, D = any>(url: string, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T>>;

  delete<T = any, D = any>(url: string, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T>>;

  head<T = any, D = any>(url: string, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T>>;

  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
  post<T extends any, D extends any>(url: string, data: D, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T>>;

  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
  put<T extends any, D extends any>(url: string, data: D, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T>>;

  patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Observable<AxiosResponse<T>>;
  patch<T extends any, D extends any>(url: string, data: D, config?: AxiosRequestConfig<D>): Observable<AxiosResponse<T>>;

  get axiosRef(): AxiosInstance;
  protected makeObservable<T>(axios: (...args: any[]) => AxiosPromise<T>, ...args: any[]): Observable<AxiosResponse<T, any>>;
}

This way with overloading, if we provide the type then data becomes required.

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

Just allowing the option to enforce stricter typing.

Support for Axios 1.3.0

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

The issue appears when the axios 1.2.3+ is explicitly installed in the project. Then, code like this isn't working:

import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { AxiosInstance } from 'axios';

@Injectable()
export class MyService {
  private http: AxiosInstance;

  constructor(private readonly httpService: HttpService) {
    this.http = httpService.axiosRef;
  }
}

The reason is that typings and structure for AxiosInstance starting from 1.2.3 and higher is different from what goes with @nestjs/axios right now.

Describe the solution you'd like

The internal dependency for Axios is 1.3.0

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

Typically you grab instances from Axios directly - not from sub-dependences of install packages (@nestjs/axios in this case).

Align Version Number with other NestJS packages (8.x.x) instead of (0.0.3)

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

It is not really a big issue but, as you give already deprecation warnings for the old version
DEPRECATED! "HttpModule" (from the "@nestjs/common" package) is deprecated and will be removed in the next major release. Please, use the "@nestjs/axios" package instead.
I think it would be best to align version numbers to the other nestjs packages

  1. because 0.0.X -> always looks a little bit like not "fully" ready
  2. because ther packages of nestjs always align with major version number.

Describe the solution you'd like

bump the version to 8.x.x

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

.

Upgrade to Axios major 1.x

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

Hello! Is there any plan of supporting axios 1.x soon? People are discussing here that updating axios from 0.27.2 to latest 1.x is breaking: axios/axios#5100

Describe the solution you'd like

Migrate to axios 1.x

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

NestJS projects will be stuck on 0.x as long as 1.x is not properly supported here

Add AxiosError Interface to package export

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

I will be easier to expose AxiosError type (like for AxiosResponse #100), it will avoid installing axios package

Describe the solution you'd like

Add AxiosError in

import Axios, {
  AxiosInstance,
  AxiosPromise,
  AxiosRequestConfig,
  AxiosResponse,
  CancelTokenSource,
} from 'axios';

in this httpservice file https://github.com/nestjs/axios/blob/master/lib/http.service.ts
And export it, or in interfaces/HttpModule.interface

Teachability, documentation, adoption, migration strategy

After this part AxiosResponse is an interface exported from the axios package ($ npm i axios). in https://docs.nestjs.com/techniques/http-module whe cousl add this : We also expose AxiosError to ease error type handling

We may also remove the fact that we need to install axios package as it's a dependency, and already installed

What is the motivation / use case for changing the behavior?

We handle error on dependency service calls, and depending on response we handle it with a try / cacth and with TS 4.4 changes, we would like to do something like

catch(error: unknown) {
  if (error  instanceOf AxiosError) {
       switch (error?.response?.status) {
          case 404:
             return []
           case 400:
              throw new CompanyIdInvalid('Company not found', path);
     }
  }
}

Nest v8 Support - Update of axios dependency to at least v1.2.2

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

Like explained in axios/axios#5346 and also in #641 there is a problem with v1.2.1 of the axios package. Unfortunately there hasn't been a version bump that's usable for projects that still use Nest v8.
We can't currently upgrade to Nest v9, so it would be fantastic, if there was a bump in the dependency version.

Minimum reproduction code

Steps to reproduce

No response

Expected behavior

Should be able to use the httpService without the above mentioned bug.

Package version

1.0.1

NestJS version

8.4.7

Node.js version

16.16.0

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

Support for axios interceptors

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

Since the axios instance is inside the module there is no easy way to add axios interceptors on the instance. Many workarounds suggested rely on the use of onModuleInit of the module which imports the HttpModule, but this aprouch breaks when the service is used on a injectable with scope REQUEST, because onModuleInit only add the interceptor on the first instance generated and not the others instances generated by scope Request.

Describe the solution you'd like

Expand HttpModuleOptions to add interceptors on the config of the module and add it to the axios instance generated by the module.

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

Allowing the configuration of interceptors on the axios instance of the http module, i can generate interceptors to add authorization headers, add logging, add metrics, etc. This reduces the amount of times that i had to make wrappers around the module and the service in other to achieve desired behaviors which comes with axios.

Npm package 0.0.7 contains no dist folder, no code

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

Update

Minimum reproduction code

npm install @nestjs/axios

Steps to reproduce

npm install @nestjs/axios

//TS2305: Module '"@nestjs/axios"' has no exported member 'HttpModule'.
import { HttpModule } from '@nestjs/axios';

Expected behavior

To work like 0.0.6

Package version

0.0.7

NestJS version

8.0.0

Node.js version

14.17.6

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

出现tcp connect时间过长的问题,导致接口响应缓慢

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

1655688246653

Minimum reproduction code

no

Steps to reproduce

No response

Expected behavior

服务运行一段时间之后会出现该问题,接口响应时间随运行时间而变长
1655688606698

Package version

0.0.7

NestJS version

8.0.0

Node.js version

14.17.3

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

Enable default axios mode with promises instead of observables

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

I'm trying to use axios as explained in axios documentation but instead I'm getting Observables instead of plain old promises from HttpService.

Describe the solution you'd like

I would like to have the choice whether I want to use promise or observable based API for axios.

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

I don't think I should be forced to use axios with only observables, because that is not how axios was built and not how it operates. Maybe there should be separate packages for axios with observables and with promises?

Not sure if you're aware but there is a package axios-observable that does a similar thing with its createObservable vs your implementation of makeObservable.

Axios v0.25.0 update

Axios has been updated to v0.25.0. Among other things, it includes a fix for a vulnerable dependency (follow-redirects).

Can we get an update to @nestjs/axios with the latest version of Axios? Thanks!

Set [email protected] as minimum required version

Did you read the migration guide?

  • I have read the whole migration guide

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Potential Commit/PR that introduced the regression

No response

Versions

0.0.1 -> 0.0.5

Describe the regression

[email protected] is recommended version only.

Another package (@keycloak/[email protected]) uses axios@^0.24.0 as minimum minor required version.
In result i've had @nestjs/[email protected] and [email protected] installed. But it raises TypeScript compilation error:

Type 'Promise<import(".../node_modules/@nestjs/axios/node_modules/axios/index").AxiosResponse<any, any>>' is not assignable to type 'Promise<import(".../node_modules/axios/index").AxiosResponse<any, any>>'
(bla-bla-bla)

Minimum reproduction code

get(url: string): Promise<AxiosResponse> {
    return lastValueFrom(
      this.httpService.get(url)
    );
  }

Expected behavior

Minimum [email protected] installes by default with npm install command

Other

No response

Duplicated interceptors

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

  1. I have an HttpClient service that "wraps" HttpService by initializing axiosRef with some interceptors to add some logging.
  2. This HttpClientService is imported by several modules that have to do API requests or have their own client.

The result of this is that a single request is logged as many dependencies on HttpClient I have.

How can I avoid this duplication?

Minimum reproduction code

https://gist.github.com/matiasgarcia/53d2aa20acecec511b285efd86525279

Steps to reproduce

No response

Expected behavior

Single interceptor added

Package version

0.1.0

NestJS version

9.0.11

Node.js version

v16.17.0

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

Allow the HttpModule to register headers with the HeadersDefaults type

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

Axios allows to define "common" headers. It is not possible to register common headers through the HttpModule.register method.

For instance :

When invoking the httpService, it is possible to add a value to the common headers such as :

this.httpService.axiosRef.defaults.headers.common['Authorization'] = axiosResponse.headers.authorization ?? '';

But it is not possible to register the same kind of headers through the HttpModule.register method :

HttpModule.register({
  headers: {
    common: { 'Content-Type': 'application/json', Accept: 'application/json' },  // => TS Error
    // 'Content-Type': 'application/json',
    // Accept: 'application/json',
  },
}),

By removing the comments it works though, Axios seems to pick them up. But it seems to be less granular.

Describe the solution you'd like

Updating the AxiosRequestConfig such as

export interface AxiosRequestConfig<D = any> {
  //Removed code
  headers?: AxiosRequestHeaders | Partial<HeadersDefaults>;
}

It would allow the flexibility to set up the headers how we see fit while keeping the the actual way of doing things.

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

A more granular declaration of the headers through the register method that follow the AxiosDefaults deinition

Use class-transformer for json deserialization

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

Instead of a plain json type, I'd like to have an object instance from the http response.

Describe the solution you'd like

Just integrate plainToInstance before returning the response observable.

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

The usecase is everywhere you want logic into classes.

Error: self signed certificate in certificate chain

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

[Nest] 13372 - 12/10/2022 03:21:02 ERROR [ExceptionsHandler] self signed certificate in certificate chain
Error: self signed certificate in certificate chain
at TLSSocket.onConnectSecure (node:_tls_wrap:1530:34)
at TLSSocket.emit (node:events:520:28)
at TLSSocket._finishInit (node:_tls_wrap:944:8)
at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:725:12)

Minimum reproduction code

none

Steps to reproduce

async getPdfBase64(fileData: string, fileJasper: string, parameters: string) {
const url = "https://localhost:3014/jasper/";
const data = JSON.stringify({ "fileData": fileData, "fileJasper": fileJasper, "parameters": parameters });
console.log(data)
var value = await lastValueFrom(
this.httpService.post(url, data).pipe(map((resp) => resp.data))
);
return value;
}

Expected behavior

i want to consume an https api using nestjs/axios

Package version

0.1.0

NestJS version

8

Node.js version

16.14.0

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

Dependency issue of HttpService

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

By adding HttpModule in imports array gives issue of dependency for httpservice in v 0.0.5 by downgrading to v 0.0.4
the issue was resolved.

"dependencies": {
"@nestjs/axios": "^0.0.5",
"@nestjs/common": "^8.0.0",
"@nestjs/config": "^1.1.6",
"@nestjs/core": "^8.0.0",
"@nestjs/passport": "^8.1.0",
"@nestjs/platform-express": "^8.0.0",
"@nestjs/typeorm": "^8.0.3",
}

ERROR [ExceptionHandler] Nest can't resolve dependencies of the HttpService (?). Please make sure that the argument AXIOS_INSTANCE_TOKEN at index [
0] is available in the AuthModule context.

Potential solutions:

  • If AXIOS_INSTANCE_TOKEN is a provider, is it part of the current AuthModule?
  • If AXIOS_INSTANCE_TOKEN is exported from a separate @module, is that module imported within AuthModule?
    @module({
    imports: [ /* the Module containing AXIOS_INSTANCE_TOKEN */ ]
    })

Minimum reproduction code

https://github.com/nestjs/axios

Steps to reproduce

No response

Expected behavior

Adding httpservice normally as it was happening in v0.0.4

Package version

0.0.5

NestJS version

8.2.0

Node.js version

14.17.0

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

axiosRef does not play nicely with axiosCookieJarSupport

I'm submitting a...


[ ] Regression
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Due to a server that requires a cookie (will attempt to set the cookie and redirect, resulting in an infinite loop), I need to add cookies support to Axios. The consensus appears to be that this is best accomplished through the axios-cookiejar-support package at https://github.com/3846masa/axios-cookiejar-support

This is done by pushing the Axios instance through an axiosCookieJarSupport() wrapper.

All requests to this.httpService.get() fail, with the message "TypeError: Cannot read property 'request' of undefined"

Expected behavior

Would expect this.httpService.get() to work.

Actual behavior

It does not.

Minimal reproduction of the problem with instructions

import { Process, Processor } from '@nestjs/bull'
import { HttpService } from '@nestjs/axios'
import { Job } from 'bull'
import axiosCookieJarSupport from 'axios-cookiejar-support'
import { CookieJar } from 'tough-cookie'


@Processor('scrapeBot')
export class ScrapeBot {
  constructor(
    private readonly httpService: HttpService,
  ) {}  
  
  @Process('getPage')
  async handleGetPage(job: Job) {
    axiosCookieJarSupport(this.httpService.axiosRef)
    const jar = new CookieJar()
    const query = this.httpService.get(job.data.url, { withCredentials: true, jar })
    // fails at this point
  }
}

Environment


Nest version: 8.0.6
 
For Tooling issues:
- Node version: 16.4.0
- Platform:  Mac

Other notes

  • This still fails when the options are omitted from the .get() request.
  • This affects HttpService globally; Axios crashes in other modules after this is run.
  • The "wrapping" appears to happen here: https://github.com/3846masa/axios-cookiejar-support/blob/master/lib/index.mjs#L70
  • I think it's possible (even likely) that I should be passing something other than this.httpService.axiosRef, but I can't guess what.

How do I register the axios httpmodule module globally?

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

How do I register the axios httpmodule module globally?

Describe the solution you'd like

@Module({
  imports: [
    HttpModule.register({
      timeout: 5000,
      maxRedirects: 5,
      httpsAgent: new Agent({
        rejectUnauthorized: false
      }),
      transformResponse: [
        function (data) {
          // Dols whatever you want to transform the data
          return _json.parse(data);
        }
      ]
    })
  ],
  providers: [RequestService],
  exports: [RedisService]
})
expor

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

Easy to call

toPromise() Marked as deprecated

Did you read the migration guide?

  • I have read the whole migration guide

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Potential Commit/PR that introduced the regression

No response

Versions

Nest 7 > 8

Describe the regression

No Changes Promise

We have recently bumped NestJS from 7 to 8.

The migration guide states:

The HttpModule exported from the @nestjs/common package has been deprecated and will be removed in the next major release. Instead, please use the @nestjs/axios package (otherwise, there are no API differences).

Note:

(otherwise, there are no API differences)

Deprecation Warning

However, with @nestjs/axios we get a deprecation warning for toPromise():

image

Note that this deprecation is due to changes to the RxJS API - not NestJS.

Issues

Quite an API change

Our code is promise based.

With toPromise() being deprecated, we are left with an Observable - this is quite a big API change!

Conceptually Dubious

Although I'm sure there's a good reason for this, I'm not sure why methods like get or post will have an Observable API - these operations seem to me, for the consumer at least, more of a success or failure case, rather than a stream case.

Axios is a Promise Based Framework

From their About:

Promise based HTTP client for the browser and node.js

It's odd to have an Observable API from @nestjs/axios where axios is promise based.

Not Clear how to Act

Other than having to change a lot of instances of toPromise(), it is not clear what is the recommended solution here.

As the RxJS docs state you need to choose between lastValueFrom or firstValueFrom. But which one? The model is broken here, we just want to send a request and await the response - no streams involved.

Alternatively, some SO answers suggest the following (which doesn't seem to work, by the way):

    return this.http.get(this.DATA_URL).pipe(
      map((axiosResponse: AxiosResponse) => {
        return axiosResponse.data;
      })
    );

Conclusion

To summarise:

  • Migration guide says "no API differences" but there are.
  • Not clear how to migrate.
  • Questionable API.
  • Large changes to codebase (or we need to use a decorated HttpModule to maintain backward compatibility).

Minimum reproduction code

Bump to NestJS 8 per migrate guide. See warning in IDE.

this.httpService.get(serviceUrl).toPromise();

Expected behavior

@nestjs/axios should provide promise-based API.

Other

No response

Still using old 0.21.1 axios version

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

This package locks on "axios": "0.21.1", while there are open CVEs for below 0.21.4.

Expected behavior

Either using latest, using axios as a peer dependency or upgrading to the latest non-vuln version.

Minimal reproduction of the problem with instructions

https://snyk.io/vuln/SNYK-JS-AXIOS-1579269

What is the motivation / use case for changing the behavior?

Environment


Nest version: X.Y.Z

 
this issue occurs with the latest version of this package at 0.0.1

For Tooling issues:
- Node version: XX  
- Platform:  

Others:

Upgrading from an older nest 7 to nest 8 system, I saw HttpModule was deprecated and followed the update instructions. But this package is below 1.0 and is using a locked dep too.

Make it easier to use axios types

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

Axios frequently updates its types, which can make upgrades difficult. Even the types between patch versions can be incompatible (the AxiosRequestConfig interfaces are not compatible between versions 1.2.1 and 1.2.2, for example). If you have another library that depends on axios, you can easily end up with a version in the root of node_modules that is incompatible with @nestjs/axios. Given how many of the axios types are exposed by @nestjs/axios, this can lead to confusing error messages.

The best way to mitigate this issue is to explicitly install axios in your project, but that doesn't completely solve the issue because you have to ensure that the version that you install is compatible with the one in @nestjs/axios.

Describe the solution you'd like

There are two solutions that I can think of:

  1. Set axios as a peer dependency. Since you need axios in the root of your node_modules to use the many types exposed by @nestjs/axios (e.g. AxiosResponse, AxiosRequestConfig, etc.) and you can't use this package without using the axios types (unless your Typescript config is relatively loose), this seems fair to me. It will also ensure that the axios version in the root is the correct one. I don't believe that there are any drawbacks to this because you can't install an incompatible version of axios right now anyway unless you ignore the type incompatibilities. Since npm also installs peer dependencies automatically now, consumers of this package wouldn't need to explicitly specify an axios version in their package.json file.
  2. Expos the axios types in this package. While this would work and potentially be less intrusive than the peer dependency, it's a bit clunky and would significantly increase the number of exports from this package. Re-exporting could be limited to just the types exposed by @nestjs/axios, but it might be difficult to determine which types are exposed and to maintain those exports. This is similar to #100 and #405

Teachability, documentation, adoption, migration strategy

For option 1, no changes would be required for use - imports would come from axios as they do today. For a few cases, users might be confused on installation when they have a version of axios that is not compatible. However, I think that npm explicitly informing users of an incompatible peer dependency is a better solution than the cryptic type errors that you receive at the moment (e.g. "AxiosRequestConfig is not compatible with AxiosRequestConfig").

For option 2, users would need to change all imports of axios types to come from this package. For example, import { AxiosResponse } from 'axios' would become something like import { AxiosResponse } from '@nestjs/axios'. A note should also be added to the documentation if this is the chosen option.

What is the motivation / use case for changing the behavior?

The current behavior is confusing and occasionally frustrating and the TypeScript error messages aren't very helpful. This would reduce friction when upgrading packages and would prevent confusing error messages.

axios has a bug that was resolved in axios 1.2.0

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

Axios package version 1.0 and 1.1 has a bug that was resolved in latest version of axios.
Using a retry incerceptor causes axios to fail. See softonic/axios-retry#212
Can you update @nestjs/axios to the latest version of axios?

Minimum reproduction code

N/A

Steps to reproduce

Use a retry interceptor like axios-retry with the current version shipped with @nestjs/axios
See softonic/axios-retry#212
See the pull request that fixed the issue: axios/axios#5224

Expected behavior

Latest version of axios included in @nestjs/axios that does not suffer from the bug mentioned in softonic/axios-retry#212

Package version

1.0.0

NestJS version

9.2.0

Node.js version

16.18.1

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

Axios needs to be updated to 1.2.x

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

Right now axios.isAxiosError will return the following error:

TypeError: Cannot read properties of undefined (reading 'isAxiosError')

There is a ticket around this in the axios repository here:

The problem is fixed by updating axios to 1.2.x

Currently if I update and include axios by hand then I get version missmatching on my typing as explained here:

Argument of type 'import("./node_modules/axios/index").AxiosRequestConfig<any>' is not assignable to parameter of type 'import("./node_modules/@nestjs/axios/node_modules/axios/index").AxiosRequestConfig<any>'.

Minimum reproduction code

axios/axios#5011

Steps to reproduce

No response

Expected behavior

I should be able to call axios.isAxiosError without it saying that axios is undefined.

This is a known bug for axios v1.1.3, and thus axios should be updated to 1.2.x

Package version

1.0.0

NestJS version

9.2.1

Node.js version

16.15.1

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

Publish a new version with the latest Axios

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

The latest release of nestjs/axios depends on axios 0.25.0. The latest Axios version is 0.26.0.

Describe the solution you'd like

Publish a new version, since the master branch already depends on 0.26.0.

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

I want to use the latest version of Axios.

Apply Parameters specified in HttpModule registration to all requests

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

I would like parameters applied to all requests. When I setup my HttpModule I want to register with parameters

HttpModule.registerAsync({
      useFactory: () => ({
        params: {
          version: '1.3.5',
        },
      }),
    }),

I would like this parameters to be applied on every request. However, there are other parameters I need to apply specific to a request. For those requests I specify a new parameters object and the ones from the registration get overwritten.

this.httpService.get(`/url`,
      {
        baseURL: this.appConfigService.host,
        params:
          ids: ids.join(','),
        },
        

To get around this I can do spread the default parameters, but that feels like the equivalent of just adding the parameters manually to every request.

this.httpService.get(`/url`,
      {
        baseURL: this.appConfigService.host,
        params:
          ...this.httpService.axiosRef.defaults.params,
          ids: ids.join(','),
        },

Describe the solution you'd like

I would like HttpService to either merge the params object specified during module registration, or have some sort of config option to indicate that params need to be merged.

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

Have the ability to have parameters in one place that will apply to all requests in a particular service. This makes it easy so that if a parameter needs to be added for all requests, it can be done in one place instead of updating each request in a service.

Turns this:

this.httpService.get(`/url`,
      {
        baseURL: this.appConfigService.host,
        params:
          ids: ids.join(','),
          version: "1.2.3"
        },
        
this.httpService.get(`/url/123`,
      {
        baseURL: this.appConfigService.host,
        params:
          ids: ids.join(','),
          otherParam: 2,
        },
        

into:

this.httpService.get(`/url`,
      {
        baseURL: this.appConfigService.host,
        params:
          ids: ids.join(','),
        },
        
this.httpService.get(`/url/123`,
      {
        baseURL: this.appConfigService.host,
        params:
          ids: ids.join(','),
          otherParam: 2,
        },
        

Typescript error in dist/http.service.d.ts in "@nestjs/axios": "^2.0.0"

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

When run nest build with "@nestjs/axios": "^2.0.0" in package.json, I get this Typescript error:

backend2>nest build
node_modules/@nestjs/axios/dist/http.service.d.ts:14:105 - error TS2707: Generic type 'AxiosResponse<T>' requires between 0 and 1 type arguments.

14     protected makeObservable<T>(axios: (...args: any[]) => AxiosPromise<T>, ...args: any[]): Observable<AxiosResponse<T, any>>;
                                                                                                           ~~~~~~~~~~~~~~~~~~~~~

Found 1 error(s).

If I'll manually change type in node_modules/@nestjs/axios/dist/http.service.d.ts
from
protected makeObservable<T>(axios: (...args: any[]) => AxiosPromise<T>, ...args: any[]): Observable<AxiosResponse<T, any>>;
to
protected makeObservable<T>(axios: (...args: any[]) => AxiosPromise<T>, ...args: any[]): Observable<AxiosResponse<T>>;
nest build will run without errors.

Looks like a bug, because we expect to receive Observable with type.

Minimum reproduction code

https://github.com/vladimirverh/repro-nestjs-2.0.0-TS-issue/blob/main/package.json

Steps to reproduce

  1. yarn install
yarn install v1.22.10
[1/5] Validating package.json...
[2/5] Resolving packages...
success Already up-to-date.
  1. nest build
  2. See error
node_modules/@nestjs/axios/dist/http.service.d.ts:14:105 - error TS2707: Generic type 'AxiosResponse<T>' requires between 0 and 1 type arguments.

14     protected makeObservable<T>(axios: (...args: any[]) => AxiosPromise<T>, ...args: any[]): Observable<AxiosResponse<T, any>>;
                                                                                                           ~~~~~~~~~~~~~~~~~~~~~

Found 1 error(s).

Expected behavior

nest build should run without Typescript errors.

Package version

9.3.6

NestJS version

9.3.6

Node.js version

16.13.1

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

package.json (in case GitHub url not working):
{
"name": "backend",
"version": "1.0.0",
"engines": {
"node": ">=16.0.0",
"npm": ">=7.0.0"
},
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"start": "nest start",
"start:dev": "nest start --watch",
"test": "mocha --timeout 90000 --exit"
},
"dependencies": {
"@nestjs/axios": "^2.0.0",
"@nestjs/common": "^9.3.6",
"@nestjs/config": "^2.3.0",
"@nestjs/core": "^9.3.6",
"@nestjs/platform-express": "^9.3.6",
"@nestjs/schedule": "^2.2.0",
"@nestjs/typeorm": "^9.0.1",
"bcrypt": "^5.0.1",
"cache-manager": "^3.4.4",
"cache-manager-redis-store": "^2.0.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"cookie-parser": "^1.4.5",
"lodash": "^4.17.21",
"pg": "^8.9.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.8.0",
"typeorm": "^0.3.11",
"winston": "^3.7.2",
"yarn": "^1.22.10"
},
"devDependencies": {
"@nestjs/cli": "^9.2.0",
"@nestjs/schematics": "^9.0.4",
"@nestjs/testing": "^9.3.2",
"@types/bcrypt": "^5.0.0",
"@types/cache-manager": "^3.4.2",
"@types/chai": "^4.2.21",
"@types/chai-as-promised": "^7.1.4",
"@types/cron": "^1.7.3",
"@types/express": "^4.17.17",
"@types/body-parser": "^1.19.2",
"@types/faker": "^5.5.8",
"@types/lodash": "^4.14.171",
"@types/mocha": "^9.0.0",
"@types/multer": "^1.4.7",
"@types/newrelic": "^7.0.3",
"@types/node": "^16.18.12",
"@types/sinon": "^10.0.2",
"@typescript-eslint/eslint-plugin": "^4.19.0",
"@typescript-eslint/parser": "^4.19.0",
"chai": "^4.3.4",
"chai-as-promised": "^7.1.1",
"eslint": "^7.22.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.3.1",
"faker": "^5.5.3",
"mocha": "^9.0.3",
"nodemon": "^2.0.20",
"prettier": "^2.2.1",
"sinon": "^11.1.2",
"ts-loader": "^8.0.18",
"ts-node": "^9.1.1",
"tsconfig-paths": "^3.9.0",
"typeorm-fixtures-cli": "^1.9.1",
"typescript": "^4.9.5"
}
}

Provide optional payload in delete request

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

HTTP Wiki states that the DELETE method should have an optional payload. Why is this not the case?

Describe the solution you'd like

add data: {}` as a optional argument to delete method.

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

Write now, i cannot use this library to delete a resource from the api.

Upgrade axios to next major release

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

axios package is outdated.

Describe the solution you'd like

update axios to the latest release (v1.1.3 by now)

Teachability, documentation, adoption, migration strategy

https://github.com/axios/axios/blob/v1.x/MIGRATION_GUIDE.md

There's no migration guide, IG, perhaps because axios has no breaking changes.

What is the motivation / use case for changing the behavior?

We should keep up with updates, especially with HTTP clients, IMO.

Update version Axios for 1.6.0 version

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

Currently axios has a moderate level vulnerability that without updating the lib @nestjs/axios we can only resolve it with npm audit fix --force, which is not a good practice

axios 1.0.0 - 1.5.1
Severity: moderate
Axios Cross-Site Request Forgery Vulnerability - GHSA-wf5p-g6vw-rhxx
fix available via npm audit fix --force
Will install [email protected], which is outside the stated dependency range
node_modules/axios

image

Describe the solution you'd like

Update axios for version 1.6.0

Teachability, documentation, adoption, migration strategy

GHSA-wf5p-g6vw-rhxx

What is the motivation / use case for changing the behavior?

This modification is necessary because without it many applications are left with vulnerabilities, this affects all teams that use these libs

Add new Multipart Bodies methods from Axios

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

Axios currently has new Multipart Bodies methods. Would be nice if the HttpService was able to access these.

Describe the solution you'd like

Add the following functions from the axios library.

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

Keeping up to date with the capabilities of the Axios library while still allowing for Observables.

Сonfigurable axios instance with retrays and interceptors.

Is there an existing issue that is already proposing this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

Hi!

When using the package, I constantly encounter problems:

  1. There is no possibility to set a retry. To do this, you need to do some utility functions in the services, or connect third-party libraries. Since you can not trust third-party services and it is better to do a retry if the request is unsuccessful (For example, status 503).
  2. There is no possibility to additionally configure axios instance. For example, I almost always need to specify an interceptor that would transform the error by deleting sensitive data (for example, auth token).

Therefore, I constantly need to do some actions when using methods from HTTPService.

Describe the solution you'd like

I would like to be able to pass options for the retry and interceptors at once when initializing HttpModule.

Example with retries:

export type RetryOptions = {
    retryableStatuses: number[]; // statuses under which the retry will be made
    retryableCodes: string[]; // codes under which the retry will be made
    limit: number; // limit of retries
    delay: number; // delay for retry
}

export type HttpModuleOptions = {
    axiosConfig: AxiosRequestConfig;
    retryOptions?: RetryOptions;
};


export class HttpService {
    constructor(@Inject(RETRY_OPTIONS) private readonly retryOptions: RetryOptions | undefined) {}

    request<T = any>(config: AxiosRequestConfig): Observable<AxiosResponse<T>> {
        const obs = this.makeObservable<T>(this.instance.request, config);

        return this.makeRetryableRequest(obs);
    }

    protected makeRetryableRequest<TResponseData = unknown>(
        response: Observable<AxiosResponse<TResponseData>>
    ): Observable<AxiosResponse<TResponseData>> {
        if (this.retryOptions === undefined) {
            return response;
        }

        return response.pipe(rxjs.retry({ delay: ..., count: ... })).
    }
}

Example with interceptors:

export type Interceptor = {
    onFulfilled: (value: any) => any;
    onRejected: (error: any) => any;
    options?: AxiosInterceptorOptions;
}

export type HttpModuleOptions = {
    axiosConfig: AxiosRequestConfig;
    axiosInstanceInterceptors?: { response: Interceptor[] };
};

export class HttpService {
    constructor(
        @Inject(AXIOS_INSTANCE_TOKEN)
        protected readonly instance: AxiosInstance = Axios,
        @Inject(AXIOS_INSTANCE_INTERCEPTORS)
        private readonly interceptors: Interceptor[],
    ) {
        this.interceptors.forEach(interceptor => {
            instance.response.use(interceptor.onFulfilled, interceptor.onRejected, interceptor.options);
        });
    }
}

Teachability, documentation, adoption, migration strategy

No response

What is the motivation / use case for changing the behavior?

When initializing the module, I want to immediately set everything that is necessary to work with axios :)

I specified the use cases in the problems.

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.