Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[typescript-axios] Add User-Agent Header to Default Axios #20067

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

ckoegel
Copy link
Contributor

@ckoegel ckoegel commented Nov 8, 2024

This PR adds a User-Agent header to the default axios instance created in base.ts. This conforms with other generators that set the user agent header based on the package version, i.e OpenAPI-Generator/1.0.0/typescript-axios

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package 
    ./bin/generate-samples.sh ./bin/configs/*.yaml
    ./bin/utils/export_docs_generators.sh
    
    (For Windows users, please run the script in Git BASH)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.x.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@TiFu (2017/07) @taxpon (2017/07) @sebastianhaas (2017/07) @kenisteward (2017/07) @Vrolijkx (2017/09) @macjohnny (2018/01) @topce (2018/10) @akehir (2019/07) @petejohansonxo (2019/11) @amakhrov (2020/02) @davidgamero (2022/03) @mkusaka (2022/04) @joscha (2024/10)

@ckoegel
Copy link
Contributor Author

ckoegel commented Nov 8, 2024

updated to make the mustache logic contained in one line
I couldn't think of a simple way to test this change, let me know if/what to do about that

@joscha
Copy link
Contributor

joscha commented Nov 8, 2024

updated to make the mustache logic contained in one line
I couldn't think of a simple way to test this change, let me know if/what to do about that

You can generate a new fixture where you pass the version in additionalProperties - have a look at the yamls we have in the repo already, some of them set other vars as well. You can change an existing one or add a new one.

@@ -10,6 +10,8 @@ import globalAxios from 'axios';

export const BASE_PATH = "{{{basePath}}}".replace(/\/+$/, "");

globalAxios.defaults.headers.common['User-Agent'] = "OpenAPI-Generator{{#npmVersion}}/{{npmVersion}}{{/npmVersion}}/typescript-axios";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't we rather set this inside the API, so it doesn't change other axios calls outside of the generated code?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think so. It also makes it impossible to provide an axios instance with a specific behavior as each time this code runs it will revert the default?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this globalAxios instance is used as the default when a new api instance is created. It shouldn't affect anything outside of this code afaik. In the tests (specifically here ), we create a custom axios instance and pass it into the test suite. This axios instance contains the default axios/1.6.1 User-Agent header and not the generated one. Only in the tests where an instance is not passed in does the OpenAPI-Generator/1.0.0/typescript-axios header appear.

I can try to add some asserts inside an interceptor to guarantee the User-Agent header remains the default axios header when using the custom instance in these tests, but like I said earlier in the thread I couldn't think of a way to intercept the requests coming from the default instance in BaseAPI and assert those.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, it would affect other code outside of this package that does import globalAxios from 'axios';, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, it would affect other code outside of this package that does import globalAxios from 'axios';, right?

Normally yes, I would expect this to behave like that, but in this case it doesn't seem to work that way. In the PetApi tests, I'm able to see the behavior you mention, where any import of the default axios export is the same instance of axios, but the instance that exists in the test file is not the same as the one created in base.ts. I honestly don't know how all of this works well enough to know why, so if you can explain more I'd appreciate it. My best guesses are:

  1. Since the globalAxios instance is created inside a node_module when the package is imported, maybe it creates a new instance when axios is imported in another module, in this case the test module?
  2. The built base.js file that comes from base.ts uses a require instead of import, and then references the .default of the required var (snippet below), perhaps this is why?
var axios_1 = require("axios");
exports.BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, "");
axios_1.default.defaults.headers.common['User-Agent'] = "OpenAPI-Generator/1.0.0/typescript-axios";

I also did some digging in the axios source, and it seems like at some points they do some omitting of the defaults.headers (here) I doubt this is related though.

Here's a snippet of the modified PetApi.ts test file where I verify that the two imported axios' in this file are in fact the same instance of axios, but the globalAxios does not have the assigned header that comes from base.ts.

import { expect } from "chai";
import { PetApi, Pet, PetStatusEnum, Category } from "@openapitools/typescript-axios-petstore";
import axios, {AxiosInstance, AxiosResponse} from "axios";
import globalAxios from "axios";

describe("PetApi", () => {
  function runSuite(description: string, requestOptions?: any, customAxiosInstance?: AxiosInstance): void {
    describe(description, () => {
      let api: PetApi;
      const fixture: Pet = createTestFixture();

      beforeEach(() => {
        api = new PetApi(undefined, undefined, customAxiosInstance);
      });

      it("should add and delete Pet", () => {
        return api.addPet(fixture, requestOptions).then(() => {});
      });
    });
  }

  globalAxios.interceptors.response.use(res => {
    console.log('globalAxios', res.request._header);
    return res;
  }, error => Promise.reject(error));

  console.log("same instance? ", axios === globalAxios);
  console.log("globalAxios headers: ", globalAxios.defaults.headers.common);

  runSuite("without custom axios instance");

  runSuite("with custom axios instance",{}, globalAxios);

});

function createTestFixture(ts = Date.now()) {
  const category: Category = {
    id: ts,
    name: `category${ts}`
  };

  const pet: Pet = {
    id: ts,
    name: `pet${ts}`,
    category: category,
    photoUrls: ["http://foo.bar.com/1", "http://foo.bar.com/2"],
    status: PetStatusEnum.Available,
    tags: []
  };

  return pet;
}

Console Output:

> [email protected] test
> mocha test/*.ts --require ts-node/register --timeout 10000

same instance?  true
globalAxios headers:  {
  Accept: 'application/json, text/plain, */*',
  'Content-Type': undefined
}


  PetApi
    without custom axios instance
      ✓ should add and delete Pet
    with custom axios instance
globalAxios POST /v2/pet HTTP/1.1
Accept: application/json, text/plain, */*
Content-Type: application/json
User-Agent: axios/1.6.1
Content-Length: 200
Accept-Encoding: gzip, compress, deflate, br
Host: petstore.swagger.io
Connection: close


      ✓ should add and delete Pet


  2 passing (36ms)

Notice how the interceptor does not log the response from the 'without custom axios instance' test suite since that instance does not have an interceptor. I was able to log the request headers by adding an interceptor to that globalAxios inside base.js in the with-npm-version build. That request does have my new header.

Sorry for the long response, but any insight you can provide here is appreciated, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants