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

Add support for multipart/form-data when file is present #1

Open
wants to merge 1 commit into
base: typescript-axios
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -28,22 +28,42 @@ export class {{classname}}Resource {
public {{nickname}}({{#allParams}}{{^isQueryParam}}{{paramName}}{{^required}}?{{/required}}: Partial<{{{dataType}}}>, {{/isQueryParam}}{{/allParams}}{{#hasQueryParams}}query?: { {{#queryParams}}{{paramName}}{{^required}}?{{/required}}: {{dataType}}{{^-last}},{{/-last}} {{/queryParams}}}, {{/hasQueryParams}}axiosConfig?: AxiosRequestConfig): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> {
const reqPath = '{{path}}'{{#pathParams}}
.replace('{' + '{{baseName}}}', String({{paramName}}{{#isDateTime}}.toISOString(){{/isDateTime}})){{/pathParams}};
{{#hasFormParams}}
{{#hasFormParams}}
let hasFile = false;
{{#formParams}}
{{#isFile}}hasFile = true;
{{/isFile}}
Copy link
Author

@jackjocross jackjocross Feb 11, 2019

Choose a reason for hiding this comment

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

This code is a little clunky, but comments in the PR I based these changes off of didn't offer alternative solutions: https://github.com/swagger-api/swagger-codegen/pull/4852/files#r104352794.

{{/formParams}}

let reqFormParams = {
{{#formParams}}
{{#formParams}}
{{baseName}}: {{paramName}}{{^-last}},{{/-last}}
{{/formParams}}
{{/formParams}}
};
{{/hasFormParams}}

let headers: any;
let data: any;

if (hasFile) {
headers = { 'Content-Type': 'multipart/form-data' };
data = new FormData();
Object.keys(reqFormParams).forEach((key) => {
data.append(key, reqFormParams[key]);
});
} else {
headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
data = stringify(reqFormParams);
}
{{/hasFormParams}}
let reqConfig = {
...axiosConfig,
method: '{{httpMethod}}',
url: reqPath{{#hasQueryParams}},
params: query{{/hasQueryParams}}{{#bodyParam}},
data: {{paramName}}{{/bodyParam}}{{#hasFormParams}},
headers: { 'Content-Type': 'application/x-www-form-urlencoded'},
data: stringify(reqFormParams)
{{/hasFormParams}}
headers: headers,
data: data
{{/hasFormParams}}

};
return axios.request(reqConfig)
Expand Down