swagger-api / swagger-codegen

swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.
http://swagger.io
Apache License 2.0
16.88k stars 6.03k forks source link

[typescript-nodejs] Dynamically setting basepath #3817

Open jmls opened 7 years ago

jmls commented 7 years ago
Description

I want to be able to pass the basePath as a parameter to the sdk/api. At the moment, it seems to be hardcoded as a variable called var defaultBasePath = "https://localhost/api"

If you want to override it currently, you have to pass a parameter to each model constructor

I would like to be able to call a function / method / property in order to modify it

Command line used for generation

java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate -i ./spec.json -l typescript-node

Steps to reproduce

probably need to modify the typescript templates to add the missing functionality

wing328 commented 7 years ago

@jmls do you mean making the basePath property public instead of protected?

https://github.com/swagger-api/swagger-codegen/blob/master/samples/client/petstore/typescript-node/npm/api.ts#L153

wing328 commented 7 years ago

cc @Vrolijkx

jmls commented 7 years ago

@wing328 : indeed I do ;)

Much better than the way I was trying to do it. Keep forgetting about protected / private / public ;)

wing328 commented 7 years ago

@jmls may I know if you've time to submit a PR for the enhancement?

Personally I would also make defaultHeaders public: https://github.com/swagger-api/swagger-codegen/blob/master/samples/client/petstore/typescript-node/npm/api.ts#L154

jmls commented 7 years ago

Actually - looking at the proposed solution, this would mean that I would have to set the basepath for every api : rather than just changing defaultBasePath, so that every api would use that by default.

jmls commented 7 years ago

@wing328 : sure, I could create a PR : I just want to ensure that the way it's implemented is appropriate :)

wing328 commented 7 years ago

cc @Vrolijkx

jmls commented 7 years ago

my initial thought was to add

let defaultHeaders = {};
export let config = (options) => {
    defaultBasePath = options.basePath || defaultBasePath;
    defaultHeaders = options.headers || defaultHeaders;
};

and then change the template to remove

protected defaultHeaders : any = {};

and change

let headerParams: any = this.extendObj({}, this.defaultHeaders);

to

let headerParams: any = this.extendObj({}, defaultHeaders);

It seems to work ok - how does that look to you guys ?

Vrolijkx commented 7 years ago

@jmls looks like a perfect solution. We are doing almost the same in the angular2 version.

jmls commented 7 years ago

cool, I'll get onto it