[typescript-axios] Fix Explode Query Parameters (#16898)

* [typescript-axios] Fix Explode Query Parameters

* use `paramName` instead of `baseName`

* add config, workflow and tests for echo api

* generate echo api sample

* update test dependencies and add gitignore

* update space in package json and regenerate samples

* remove tsc in test package

* update samples

* undo samples

* regenerate samples

* regenerate samples again
This commit is contained in:
Cameron Koegel 2023-10-31 21:41:06 -04:00 committed by GitHub
parent 739390a682
commit c2a4163bdb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 4098 additions and 5 deletions

View File

@ -0,0 +1,42 @@
name: TypeScript Axios Client (Echo API)
on:
pull_request:
paths:
- samples/client/echo_api/typescript-axios/**
- .github/workflows/samples-typescript-axios-echo-api.yaml
jobs:
build:
name: Test TypeScript Axios client
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
sample:
# clients
- samples/client/echo_api/typescript-axios/test
node-version:
- 16
- 18
- 20
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- name: Run echo server
run: |
git clone https://github.com/wing328/http-echo-server -b openapi-generator-test-server
(cd http-echo-server && npm install && npm start &)
- name: Install
working-directory: ${{ matrix.sample }}
run: |
npm run preinstall
npm i
- name: Test
working-directory: ${{ matrix.sample }}
run: npm test

View File

@ -0,0 +1,9 @@
generatorName: typescript-axios
outputDir: samples/client/echo_api/typescript-axios/build
inputSpec: modules/openapi-generator/src/test/resources/3_0/echo_api.yaml
templateDir: modules/openapi-generator/src/main/resources/typescript-axios
additionalProperties:
artifactId: echo-api-typescript-axios
hideGenerationTimestamp: "true"
npmVersion: 1.0.0
npmName: '@openapitools/typescript-axios-echo-api'

View File

@ -132,9 +132,19 @@ export const {{classname}}AxiosParamCreator = function (configuration?: Configur
localVarQueryParameter['{{baseName}}'] = {{paramName}};
{{/isPrimitiveType}}
{{^isPrimitiveType}}
for (let param of Object.keys({{baseName}})) {
localVarQueryParameter[param] = {{baseName}}?.[param];
{{^isEnumRef}}
{{^isEnum}}
for (const [key, value] of Object.entries({{paramName}})) {
localVarQueryParameter[key] = value;
}
{{/isEnum}}
{{/isEnumRef}}
{{#isEnum}}
localVarQueryParameter['{{baseName}}'] = {{paramName}};
{{/isEnum}}
{{#isEnumRef}}
localVarQueryParameter['{{baseName}}'] = {{paramName}};
{{/isEnumRef}}
{{/isPrimitiveType}}
{{/isExplode}}
{{^isExplode}}

View File

@ -22,7 +22,7 @@
"sideEffects": false,
{{/supportsES6}}
"scripts": {
"build": "tsc {{#supportsES6}}&& tsc -p tsconfig.esm.json{{/supportsES6}}",
"build": "tsc{{#supportsES6}} && tsc -p tsconfig.esm.json{{/supportsES6}}",
"prepare": "npm run build"
},
"dependencies": {

View File

@ -0,0 +1,4 @@
wwwroot/*.js
node_modules
typings
dist

View File

@ -0,0 +1 @@
# empty npmignore to ensure all required files (e.g., in the dist folder) are published by npm

View File

@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -0,0 +1,11 @@
.gitignore
.npmignore
README.md
api.ts
base.ts
common.ts
configuration.ts
git_push.sh
index.ts
package.json
tsconfig.json

View File

@ -0,0 +1 @@
7.1.0-SNAPSHOT

View File

@ -0,0 +1,45 @@
## @openapitools/typescript-axios-echo-api@1.0.0
This generator creates TypeScript/JavaScript client that utilizes [axios](https://github.com/axios/axios). The generated Node module can be used in the following environments:
Environment
* Node.js
* Webpack
* Browserify
Language level
* ES5 - you must have a Promises/A+ library installed
* ES6
Module system
* CommonJS
* ES6 module system
It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
### Building
To build and compile the typescript sources to javascript use:
```
npm install
npm run build
```
### Publishing
First build the package then run ```npm publish```
### Consuming
navigate to the folder of your consuming project and run one of the following commands.
_published:_
```
npm install @openapitools/typescript-axios-echo-api@1.0.0 --save
```
_unPublished (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE --save

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,86 @@
/* tslint:disable */
/* eslint-disable */
/**
* Echo Server API
* Echo Server API
*
* The version of the OpenAPI document: 0.1.0
* Contact: team@openapitools.org
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import type { Configuration } from './configuration';
// Some imports not used depending on template conditions
// @ts-ignore
import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios';
import globalAxios from 'axios';
export const BASE_PATH = "http://localhost:3000".replace(/\/+$/, "");
/**
*
* @export
*/
export const COLLECTION_FORMATS = {
csv: ",",
ssv: " ",
tsv: "\t",
pipes: "|",
};
/**
*
* @export
* @interface RequestArgs
*/
export interface RequestArgs {
url: string;
options: AxiosRequestConfig;
}
/**
*
* @export
* @class BaseAPI
*/
export class BaseAPI {
protected configuration: Configuration | undefined;
constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) {
if (configuration) {
this.configuration = configuration;
this.basePath = configuration.basePath || this.basePath;
}
}
};
/**
*
* @export
* @class RequiredError
* @extends {Error}
*/
export class RequiredError extends Error {
constructor(public field: string, msg?: string) {
super(msg);
this.name = "RequiredError"
}
}
interface ServerMap {
[key: string]: {
url: string,
description: string,
}[];
}
/**
*
* @export
*/
export const operationServerMap: ServerMap = {
}

View File

@ -0,0 +1,150 @@
/* tslint:disable */
/* eslint-disable */
/**
* Echo Server API
* Echo Server API
*
* The version of the OpenAPI document: 0.1.0
* Contact: team@openapitools.org
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import type { Configuration } from "./configuration";
import type { RequestArgs } from "./base";
import type { AxiosInstance, AxiosResponse } from 'axios';
import { RequiredError } from "./base";
/**
*
* @export
*/
export const DUMMY_BASE_URL = 'https://example.com'
/**
*
* @throws {RequiredError}
* @export
*/
export const assertParamExists = function (functionName: string, paramName: string, paramValue: unknown) {
if (paramValue === null || paramValue === undefined) {
throw new RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`);
}
}
/**
*
* @export
*/
export const setApiKeyToObject = async function (object: any, keyParamName: string, configuration?: Configuration) {
if (configuration && configuration.apiKey) {
const localVarApiKeyValue = typeof configuration.apiKey === 'function'
? await configuration.apiKey(keyParamName)
: await configuration.apiKey;
object[keyParamName] = localVarApiKeyValue;
}
}
/**
*
* @export
*/
export const setBasicAuthToObject = function (object: any, configuration?: Configuration) {
if (configuration && (configuration.username || configuration.password)) {
object["auth"] = { username: configuration.username, password: configuration.password };
}
}
/**
*
* @export
*/
export const setBearerAuthToObject = async function (object: any, configuration?: Configuration) {
if (configuration && configuration.accessToken) {
const accessToken = typeof configuration.accessToken === 'function'
? await configuration.accessToken()
: await configuration.accessToken;
object["Authorization"] = "Bearer " + accessToken;
}
}
/**
*
* @export
*/
export const setOAuthToObject = async function (object: any, name: string, scopes: string[], configuration?: Configuration) {
if (configuration && configuration.accessToken) {
const localVarAccessTokenValue = typeof configuration.accessToken === 'function'
? await configuration.accessToken(name, scopes)
: await configuration.accessToken;
object["Authorization"] = "Bearer " + localVarAccessTokenValue;
}
}
function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void {
if (parameter == null) return;
if (typeof parameter === "object") {
if (Array.isArray(parameter)) {
(parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key));
}
else {
Object.keys(parameter).forEach(currentKey =>
setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`)
);
}
}
else {
if (urlSearchParams.has(key)) {
urlSearchParams.append(key, parameter);
}
else {
urlSearchParams.set(key, parameter);
}
}
}
/**
*
* @export
*/
export const setSearchParams = function (url: URL, ...objects: any[]) {
const searchParams = new URLSearchParams(url.search);
setFlattenedQueryParams(searchParams, objects);
url.search = searchParams.toString();
}
/**
*
* @export
*/
export const serializeDataIfNeeded = function (value: any, requestOptions: any, configuration?: Configuration) {
const nonString = typeof value !== 'string';
const needsSerialization = nonString && configuration && configuration.isJsonMime
? configuration.isJsonMime(requestOptions.headers['Content-Type'])
: nonString;
return needsSerialization
? JSON.stringify(value !== undefined ? value : {})
: (value || "");
}
/**
*
* @export
*/
export const toPathString = function (url: URL) {
return url.pathname + url.search + url.hash
}
/**
*
* @export
*/
export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) {
return <T = unknown, R = AxiosResponse<T>>(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => {
const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url};
return axios.request<T, R>(axiosRequestArgs);
};
}

View File

@ -0,0 +1,110 @@
/* tslint:disable */
/* eslint-disable */
/**
* Echo Server API
* Echo Server API
*
* The version of the OpenAPI document: 0.1.0
* Contact: team@openapitools.org
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface ConfigurationParameters {
apiKey?: string | Promise<string> | ((name: string) => string) | ((name: string) => Promise<string>);
username?: string;
password?: string;
accessToken?: string | Promise<string> | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise<string>);
basePath?: string;
serverIndex?: number;
baseOptions?: any;
formDataCtor?: new () => any;
}
export class Configuration {
/**
* parameter for apiKey security
* @param name security name
* @memberof Configuration
*/
apiKey?: string | Promise<string> | ((name: string) => string) | ((name: string) => Promise<string>);
/**
* parameter for basic security
*
* @type {string}
* @memberof Configuration
*/
username?: string;
/**
* parameter for basic security
*
* @type {string}
* @memberof Configuration
*/
password?: string;
/**
* parameter for oauth2 security
* @param name security name
* @param scopes oauth2 scope
* @memberof Configuration
*/
accessToken?: string | Promise<string> | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise<string>);
/**
* override base path
*
* @type {string}
* @memberof Configuration
*/
basePath?: string;
/**
* override server index
*
* @type {number}
* @memberof Configuration
*/
serverIndex?: number;
/**
* base options for axios calls
*
* @type {any}
* @memberof Configuration
*/
baseOptions?: any;
/**
* The FormData constructor that will be used to create multipart form data
* requests. You can inject this here so that execution environments that
* do not support the FormData class can still run the generated client.
*
* @type {new () => FormData}
*/
formDataCtor?: new () => any;
constructor(param: ConfigurationParameters = {}) {
this.apiKey = param.apiKey;
this.username = param.username;
this.password = param.password;
this.accessToken = param.accessToken;
this.basePath = param.basePath;
this.serverIndex = param.serverIndex;
this.baseOptions = param.baseOptions;
this.formDataCtor = param.formDataCtor;
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
public isJsonMime(mime: string): boolean {
const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
}
}

View File

@ -0,0 +1,57 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host="github.com"
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id="GIT_USER_ID"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="GIT_REPO_ID"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="Minor update"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=$(git remote)
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -0,0 +1,18 @@
/* tslint:disable */
/* eslint-disable */
/**
* Echo Server API
* Echo Server API
*
* The version of the OpenAPI document: 0.1.0
* Contact: team@openapitools.org
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export * from "./api";
export * from "./configuration";

View File

@ -0,0 +1,31 @@
{
"name": "@openapitools/typescript-axios-echo-api",
"version": "1.0.0",
"description": "OpenAPI client for @openapitools/typescript-axios-echo-api",
"author": "OpenAPI-Generator Contributors",
"repository": {
"type": "git",
"url": "https://github.com/GIT_USER_ID/GIT_REPO_ID.git"
},
"keywords": [
"axios",
"typescript",
"openapi-client",
"openapi-generator",
"@openapitools/typescript-axios-echo-api"
],
"license": "Unlicense",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"scripts": {
"build": "tsc",
"prepare": "npm run build"
},
"dependencies": {
"axios": "^0.27.2"
},
"devDependencies": {
"@types/node": "^12.11.5",
"typescript": "^4.0"
}
}

View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"declaration": true,
"target": "ES5",
"module": "commonjs",
"noImplicitAny": true,
"outDir": "dist",
"rootDir": ".",
"lib": [
"es6",
"dom"
],
"typeRoots": [
"node_modules/@types"
]
},
"exclude": [
"dist",
"node_modules"
]
}

View File

@ -0,0 +1,2 @@
dist
node_modules

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,26 @@
{
"private": true,
"dependencies": {
"@openapitools/typescript-axios-echo-api": "file:../build",
"@types/chai": "^4.3.0",
"@types/mocha": "^10.0.0",
"@types/node": "^16.6.2",
"chai": "^4.3.0",
"mocha": "^10.2.0",
"ts-node": "^10.9.0",
"typescript": "^5.2.2"
},
"scripts": {
"preinstall": "npm --prefix ../build install && npm run build",
"test": "mocha test/*.ts --require ts-node/register --timeout 10000",
"build": ""
},
"name": "typescript-axios-echo-api-test",
"version": "1.0.0",
"directories": {
"test": "test"
},
"author": "",
"license": "ISC",
"description": ""
}

View File

@ -0,0 +1,61 @@
import {
QueryApi,
Pet,
StringEnumRef,
TestEnumRefStringEnumNonrefStringQueryEnum,
TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter
} from '@openapitools/typescript-axios-echo-api';
import { expect } from 'chai';
describe('QueryApi', () => {
const api = new QueryApi();
it('testEnumRefString', async () => {
const enumNonrefStringQuery = TestEnumRefStringEnumNonrefStringQueryEnum.Success;
const enumRefStringQuery = StringEnumRef.Unclassified;
const { request } = await api.testEnumRefString(enumNonrefStringQuery, enumRefStringQuery);
expect(request.path).to.equal('/query/enum_ref_string?enum_nonref_string_query=success&enum_ref_string_query=unclassified');
});
it('testQueryDatetimeDateString', async () => {
const dateTime = new Date('2023-10-30T10:11:12.000Z');
const datetimeQuery = dateTime.toISOString();
const dateQuery = `${dateTime.getFullYear()}-${dateTime.getMonth() + 1}-${dateTime.getDate()}`;
const stringQuery = 'Hello World';
const { request } = await api.testQueryDatetimeDateString(datetimeQuery, dateQuery, stringQuery);
expect(request.path).to.equal('/query/datetime/date/string?datetime_query=2023-10-30T10%3A11%3A12.000Z&date_query=2023-10-30&string_query=Hello+World');
});
it('testQueryIntegerBooleanString', async () => {
const integerQuery = 12345;
const booleanQuery = true;
const stringQuery = 'Hello World';
const { request } = await api.testQueryIntegerBooleanString(integerQuery, booleanQuery, stringQuery);
expect(request.path).to.equal('/query/integer/boolean/string?integer_query=12345&boolean_query=true&string_query=Hello+World');
});
it('testQueryStyleFormExplodeTrueArrayString', async () => {
const arrayStringQuery: TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter = {
values: ['hello world 1', 'hello world 2']
};
const { request } = await api.testQueryStyleFormExplodeTrueArrayString(arrayStringQuery);
expect(request.path).to.equal('/query/style_form/explode_true/array_string?values=hello+world+1&values=hello+world+2');
});
it('testQueryStyleFormExplodeTrueObject', async () => {
const queryObject: Pet = {
id: 12345,
name: 'Hello World',
photoUrls: ['http://a.com', 'http://b.com']
};
const { request } = await api.testQueryStyleFormExplodeTrueObject(queryObject);
expect(request.path).to.equal('/query/style_form/explode_true/object?id=12345&name=Hello+World&photoUrls=http%3A%2F%2Fa.com&photoUrls=http%3A%2F%2Fb.com');
});
});
1

View File

@ -0,0 +1 @@
import './api'

View File

@ -0,0 +1,20 @@
{
"compilerOptions": {
"moduleResolution": "node",
"module": "CommonJS",
"target": "ES5",
"noImplicitAny": true,
"sourceMap": false,
"outDir": "dist",
"types": [
"mocha"
],
"lib": [
"es6",
"dom"
]
},
"exclude": [
"node_modules"
]
}

View File

@ -18,7 +18,7 @@
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"scripts": {
"build": "tsc ",
"build": "tsc",
"prepare": "npm run build"
},
"dependencies": {

View File

@ -18,7 +18,7 @@
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"scripts": {
"build": "tsc ",
"build": "tsc",
"prepare": "npm run build"
},
"dependencies": {