Skip to content

Release 9.2.0 #278

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

Merged
merged 4 commits into from
Jul 14, 2021
Merged
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# next release

# 9.2.0

Features:
- full response typing for status code, data and headers. (#272, thanks @rustyconover)
- --unwrap-response-data to unwrap the data item from the response (#268, thanks @laktak)

Fixes:
- fix: formdata in axios template (#277, thanks @tiagoskaneta)

# 9.1.2

Fixes:
Expand Down
3 changes: 3 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ program
.option("--disableStrictSSL", "disabled strict SSL", false)
.option("--disableProxy", "disabled proxy", false)
.option("--axios", "generate axios http client", false)
.option("--unwrap-response-data", "unwrap the data item from the response", false)
.option("--single-http-client", "Ability to send HttpClient instance to Api constructor", false)
.option("--silent", "Output only errors to console", false)
.option("--default-response <type>", "default type for empty response schema", TS_KEYWORDS.VOID)
Expand Down Expand Up @@ -100,6 +101,7 @@ const {
disableProxy,
cleanOutput,
defaultResponse,
unwrapResponseData,
singleHttpClient,
axios,
silent,
Expand All @@ -115,6 +117,7 @@ generateApi({
httpClientType: axios ? HTTP_CLIENT.AXIOS : HTTP_CLIENT.FETCH,
defaultResponseAsSuccess: defaultAsSuccess,
defaultResponseType: defaultResponse,
unwrapResponseData: unwrapResponseData,
generateUnionEnums: unionEnums,
generateResponses: responses,
extractRequestParams: !!extractRequestParams,
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "swagger-typescript-api",
"version": "9.1.2",
"version": "9.2.0",
"description": "Generate typescript/javascript api from swagger schema",
"scripts": {
"cli:json": "node index.js -r -d -p ./swagger-test-cli.json -n swagger-test-cli.ts",
Expand Down
1 change: 1 addition & 0 deletions src/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ const config = {
defaultResponseType: TS_KEYWORDS.VOID,
singleHttpClient: false,
httpClientType: HTTP_CLIENT.FETCH,
unwrapResponseData: false,
templatePaths: {
/** `templates/base` */
base: "",
Expand Down
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ module.exports = {
extractRequestParams = config.extractRequestParams,
extractRequestBody = config.extractRequestBody,
defaultResponseType = config.defaultResponseType,
unwrapResponseData = config.unwrapResponseData,
singleHttpClient = config.singleHttpClient,
prettier: prettierOptions = constants.PRETTIER_OPTIONS,
hooks: rawHooks,
Expand Down Expand Up @@ -77,6 +78,7 @@ module.exports = {
disableProxy,
cleanOutput,
defaultResponseType,
unwrapResponseData,
singleHttpClient,
constants,
silent,
Expand Down
30 changes: 30 additions & 0 deletions src/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const _ = require("lodash");
const {
types,
parseSchema,
getType,
getRefType,
getInlineParseContent,
checkAndAddNull,
Expand Down Expand Up @@ -475,6 +476,21 @@ const getResponseBodyInfo = (routeInfo, routeParams, parsedSchemas) => {
(response) => !response.isSuccess && response.type !== TS_KEYWORDS.ANY,
);

const handleResponseHeaders = (src) => {
if (!src) {
return "headers: {},";
}
const headerTypes = Object.fromEntries(
Object.entries(src).map(([k, v]) => {
return [k, getType(v)];
}),
);
const r = `headers: { ${Object.entries(headerTypes)
.map(([k, v]) => `"${k}": ${v}`)
.join(",")} },`;
return r;
};

return {
contentTypes,
responses: responseInfos,
Expand All @@ -486,6 +502,19 @@ const getResponseBodyInfo = (routeInfo, routeParams, parsedSchemas) => {
schemas: errorResponses,
type: _.uniq(errorResponses.map((response) => response.type)).join(" | ") || TS_KEYWORDS.ANY,
},
full: {
types:
responseInfos
.map(
(response) => `{
data: ${response.type}, status: ${response.status}, statusCode: ${
response.status
}, statusText: "${response.description}", ${handleResponseHeaders(
response.headers,
)} config: {} }`,
)
.join(" | ") || TS_KEYWORDS.ANY,
},
};
};

Expand Down Expand Up @@ -685,6 +714,7 @@ const parseRoutes = ({
contentTypes: responseBodyInfo.contentTypes,
type: responseBodyInfo.success.type,
errorType: responseBodyInfo.error.type,
fullTypes: responseBodyInfo.full.types,
},
raw: rawRouteInfo,
};
Expand Down
12 changes: 10 additions & 2 deletions templates/base/http-clients/axios-http-client.eta
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<%
const { apiConfig, generateResponses } = it;
const { apiConfig, generateResponses, config } = it;
%>

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, ResponseType } from "axios";
Expand Down Expand Up @@ -89,7 +89,11 @@ export class HttpClient<SecurityDataType = unknown> {
format,
body,
...params
<% if (config.unwrapResponseData) { %>
}: FullRequestParams): Promise<T> => {
<% } else { %>
}: FullRequestParams): Promise<AxiosResponse<T>> => {
<% } %>
const secureParams = ((typeof secure === 'boolean' ? secure : this.secure) && this.securityWorker && (await this.securityWorker(this.securityData))) || {};
const requestParams = this.mergeRequestParams(params, secureParams);
const responseFormat = (format && this.format) || void 0;
Expand All @@ -99,7 +103,7 @@ export class HttpClient<SecurityDataType = unknown> {
requestParams.headers.post = {};
requestParams.headers.put = {};

const formData = this.createFormData(body as Record<string, unknown>);
body = this.createFormData(body as Record<string, unknown>);
}

return this.instance.request({
Expand All @@ -112,6 +116,10 @@ export class HttpClient<SecurityDataType = unknown> {
responseType: responseFormat,
data: body,
url: path,
<% if (config.unwrapResponseData) { %>
}).then(response => response.data);
<% } else { %>
});
<% } %>
};
}
10 changes: 9 additions & 1 deletion templates/base/http-clients/fetch-http-client.eta
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<%
const { apiConfig, generateResponses } = it;
const { apiConfig, generateResponses, config } = it;
%>

export type QueryParamsType = Record<string | number, any>;
Expand Down Expand Up @@ -164,7 +164,11 @@ export class HttpClient<SecurityDataType = unknown> {
baseUrl,
cancelToken,
...params
<% if (config.unwrapResponseData) { %>
}: FullRequestParams): Promise<T> => {
<% } else { %>
}: FullRequestParams): Promise<HttpResponse<T, E>> => {
<% } %>
const secureParams = ((typeof secure === 'boolean' ? secure : this.baseApiParams.secure) && this.securityWorker && await this.securityWorker(this.securityData)) || {};
const requestParams = this.mergeRequestParams(params, secureParams);
const queryString = query && this.toQueryString(query);
Expand Down Expand Up @@ -206,7 +210,11 @@ export class HttpClient<SecurityDataType = unknown> {
}

if (!response.ok) throw data;
<% if (config.unwrapResponseData) { %>
return data.data;
<% } else { %>
return data;
<% } %>
});
};
}
2 changes: 1 addition & 1 deletion tests/spec/axios/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1547,7 +1547,7 @@ export class HttpClient<SecurityDataType = unknown> {
requestParams.headers.post = {};
requestParams.headers.put = {};

const formData = this.createFormData(body as Record<string, unknown>);
body = this.createFormData(body as Record<string, unknown>);
}

return this.instance.request({
Expand Down
2 changes: 1 addition & 1 deletion tests/spec/axiosSingleHttpClient/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1547,7 +1547,7 @@ export class HttpClient<SecurityDataType = unknown> {
requestParams.headers.post = {};
requestParams.headers.put = {};

const formData = this.createFormData(body as Record<string, unknown>);
body = this.createFormData(body as Record<string, unknown>);
}

return this.instance.request({
Expand Down
2 changes: 1 addition & 1 deletion tests/spec/jsAxios/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class HttpClient {
requestParams.headers.common = { Accept: "*/*" };
requestParams.headers.post = {};
requestParams.headers.put = {};
const formData = this.createFormData(body);
body = this.createFormData(body);
}
return this.instance.request({
...requestParams,
Expand Down