Generator for JavaScript/Apollo Client (#5645)

Co-authored-by: William Cheng <wing328hk@gmail.com>
This commit is contained in:
Erica Kastner
2020-03-26 04:02:44 -05:00
committed by GitHub
parent 527d5e4248
commit ce49fe587f
27 changed files with 2678 additions and 1 deletions

View File

@@ -0,0 +1,33 @@
{
"presets": [
"@babel/preset-env"
],
"plugins": [
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-syntax-import-meta",
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-json-strings",
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
"@babel/plugin-proposal-function-sent",
"@babel/plugin-proposal-export-namespace-from",
"@babel/plugin-proposal-numeric-separator",
"@babel/plugin-proposal-throw-expressions",
"@babel/plugin-proposal-export-default-from",
"@babel/plugin-proposal-logical-assignment-operators",
"@babel/plugin-proposal-optional-chaining",
[
"@babel/plugin-proposal-pipeline-operator",
{
"proposal": "minimal"
}
],
"@babel/plugin-proposal-nullish-coalescing-operator",
"@babel/plugin-proposal-do-expressions",
"@babel/plugin-proposal-function-bind"
]
}

View File

@@ -0,0 +1,299 @@
{{>licenseInfo}}
import RESTDataSource from 'apollo-datasource-rest';
{{#emitJSDoc}}/**
* @module {{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient
* @version {{projectVersion}}
*/
/**
* Manages low level client-server communications, parameter marshalling, etc. There should not be any need for an
* application to use this class directly - the *Api and model classes provide the public API for the service.
* @alias module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}ApiClient
* @class
*/{{/emitJSDoc}}
export default class ApiClient extends RESTDataSource {
constructor() {
super()
{{#emitJSDoc}}/**
* The authentication methods to be included for all API calls.
* @type {Array.<String>}
*/{{/emitJSDoc}}{{=< >=}}
this.authentications = {
<#authMethods>
<#isBasic>
<#isBasicBasic>
'<name>': {type: 'basic'}<^-last>,</-last>
</isBasicBasic>
<#isBasicBearer>
'<name>': {type: 'bearer'}<^-last>,</-last><#bearerFormat> // <&.></bearerFormat>
</isBasicBearer>
</isBasic>
<#isApiKey>
'<name>': {type: 'apiKey', 'in': <#isKeyInHeader>'header'</isKeyInHeader><^isKeyInHeader>'query'</isKeyInHeader>, name: '<keyParamName>'}<^-last>,</-last>
</isApiKey>
<#isOAuth>
'<name>': {type: 'oauth2'}<^-last>,</-last>
</isOAuth>
</authMethods>
}
}
paramToString(param) {
if (param == undefined || param == null) {
return '';
}
if (param instanceof Date) {
return param.toJSON();
}
return param.toString();
}
parametrizePath(path, pathParams) {
return url.replace(/\{([\w-]+)\}/g, (fullMatch, key) => {
var value;
if (pathParams.hasOwnProperty(key)) {
value = this.paramToString(pathParams[key]);
} else {
value = fullMatch;
}
return encodeURIComponent(value);
});
}
isFileParam(param) {
// fs.ReadStream in Node.js and Electron (but not in runtime like browserify)
if (typeof require === 'function') {
let fs;
try {
fs = require('fs');
} catch (err) {}
if (fs && fs.ReadStream && param instanceof fs.ReadStream) {
return true;
}
}
// Buffer in Node.js
if (typeof Buffer === 'function' && param instanceof Buffer) {
return true;
}
// Blob in browser
if (typeof Blob === 'function' && param instanceof Blob) {
return true;
}
// File in browser (it seems File object is also instance of Blob, but keep this for safe)
if (typeof File === 'function' && param instanceof File) {
return true;
}
return false;
}
normalizeParams(params) {
var newParams = {};
for (var key in params) {
if (params.hasOwnProperty(key) && params[key] != undefined && params[key] != null) {
var value = params[key];
if (this.isFileParam(value) || Array.isArray(value)) {
newParams[key] = value;
} else {
newParams[key] = this.paramToString(value);
}
}
}
return newParams;
}
buildCollectionParam(param, collectionFormat) {
if (param == null) {
return null;
}
switch (collectionFormat) {
case 'csv':
return param.map(this.paramToString).join(',');
case 'ssv':
return param.map(this.paramToString).join(' ');
case 'tsv':
return param.map(this.paramToString).join('\t');
case 'pipes':
return param.map(this.paramToString).join('|');
case 'multi':
//return the array directly as SuperAgent will handle it as expected
return param.map(this.paramToString);
default:
throw new Error('Unknown collection format: ' + collectionFormat);
}
}
applyAuthOptions(fetchOptions, authNames) {
fetchOptions.headers = fetchOptions.headers || {};
authNames.forEach((authName) => {
var auth = this.authentications[authName];
switch (auth.type) {
case 'basic':
if (auth.username || auth.password) {
fetchOptions.headers['Authorization'] = 'Basic ' + base64.encode(auth.username + ":" + auth.password);
}
break;
case 'bearer':
case 'oauth2':
if (auth.accessToken) {
fetchOptions.headers['Authorization'] = 'Bearer ' + auth.accessToken;
}
break;
case 'apiKey':
if (auth.apiKey) {
var data = {};
if (auth.apiKeyPrefix) {
data[auth.name] = auth.apiKeyPrefix + ' ' + auth.apiKey;
} else {
data[auth.name] = auth.apiKey;
}
if (auth['in'] === 'header') {
Object.assign(fetchOptions.headers, data);
} else {
Object.assign(fetchOptions.params, data);
}
}
break;
default:
throw new Error('Unknown authentication type: ' + auth.type);
}
});
}
async callApi(path, httpMethod, pathParams,
queryParams, headerParams, formParams, bodyParam, authNames,
returnType) {
var parameterizedPath = this.parametrizePath(path, pathParams);
var fetchOptions = {
headers: headerParams,
params: queryParams
};
this.applyAuthOptions(fetchOptions, authNames);
var body = null;
if (bodyParam !== null && bodyParam !== undefined) {
body = bodyParam;
} else if (formParams !== null && formParams !== undefined) {
var _formParams = this.normalizeParams(formParams);
for (var key in _formParams) {
if (_formParams.hasOwnProperty(key)) {
body[key] = _formParams[key];
}
}
}
var response;
var httpMethodFn = httpMethod.toLowerCase();
if (httpMethodFn == 'get' || httpMethodFn == 'delete') {
response = await this[httpMethodFn](parameterizedPath, fetchOptions);
} else {
response = await this[httpMethodFn](parameterizedPath, body, fetchOptions)
}
var convertedResponse = ApiClient.convertToType(response, returnType);
return convertedResponse;
}
static parseDate(str) {
return new Date(str);
}
static convertToType(data, type) {
if (data === null || data === undefined)
return data
switch (type) {
case 'Boolean':
return Boolean(data);
case 'Integer':
return parseInt(data, 10);
case 'Number':
return parseFloat(data);
case 'String':
return String(data);
case 'Date':
return ApiClient.parseDate(String(data));
case 'Blob':
return data;
default:
if (type === Object) {
// generic object, return directly
return data;
} else if (typeof type.constructFromObject === 'function') {
// for model type like User and enum class
return type.constructFromObject(data);
} else if (Array.isArray(type)) {
// for array type like: ['String']
var itemType = type[0];
return data.map((item) => {
return ApiClient.convertToType(item, itemType);
});
} else if (typeof type === 'object') {
// for plain object type like: {'String': 'Integer'}
var keyType, valueType;
for (var k in type) {
if (type.hasOwnProperty(k)) {
keyType = k;
valueType = type[k];
break;
}
}
var result = {};
for (var k in data) {
if (data.hasOwnProperty(k)) {
var key = ApiClient.convertToType(k, keyType);
var value = ApiClient.convertToType(data[k], valueType);
result[key] = value;
}
}
return result;
} else {
// for unknown type, return the data directly
return data;
}
}
}
static constructFromObject(data, obj, itemType) {
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
if (data.hasOwnProperty(i))
obj[i] = ApiClient.convertToType(data[i], itemType);
}
} else {
for (var k in data) {
if (data.hasOwnProperty(k))
obj[k] = ApiClient.convertToType(data[k], itemType);
}
}
};
}
ApiClient.CollectionFormatEnum = {
CSV: ',',
SSV: ' ',
TSV: '\t',
PIPES: '|',
MULTI: 'multi'
};

View File

@@ -0,0 +1,226 @@
# {{projectName}}
{{moduleName}} - JavaScript client for {{projectName}}
{{#appDescriptionWithNewLines}}
{{{appDescriptionWithNewLines}}}
{{/appDescriptionWithNewLines}}
This SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project:
- API version: {{appVersion}}
- Package version: {{projectVersion}}
{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}
{{/hideGenerationTimestamp}}
- Build package: {{generatorClass}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}
## Installation
### For [Node.js](https://nodejs.org/)
#### npm
To publish the library as a [npm](https://www.npmjs.com/), please follow the procedure in ["Publishing npm packages"](https://docs.npmjs.com/getting-started/publishing-npm-packages).
Then install it via:
```shell
npm install {{{projectName}}} --save
```
Finally, you need to build the module:
```shell
npm run build
```
##### Local development
To use the library locally without publishing to a remote npm registry, first install the dependencies by changing into the directory containing `package.json` (and this README). Let's call this `JAVASCRIPT_CLIENT_DIR`. Then run:
```shell
npm install
```
Next, [link](https://docs.npmjs.com/cli/link) it globally in npm with the following, also from `JAVASCRIPT_CLIENT_DIR`:
```shell
npm link
```
To use the link you just defined in your project, switch to the directory you want to use your {{{projectName}}} from, and run:
```shell
npm link /path/to/<JAVASCRIPT_CLIENT_DIR>
```
Finally, you need to build the module:
```shell
npm run build
```
#### git
If the library is hosted at a git repository, e.g.https://github.com/{{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}YOUR_USERNAME{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{projectName}}{{/gitRepoId}}
then install it via:
```shell
npm install {{#gitUserId}}{{.}}{{/gitUserId}}{{^gitUserId}}YOUR_USERNAME{{/gitUserId}}/{{#gitRepoId}}{{.}}{{/gitRepoId}}{{^gitRepoId}}{{projectName}}{{/gitRepoId}} --save
```
### For browser
The library also works in the browser environment via npm and [browserify](http://browserify.org/). After following
the above steps with Node.js and installing browserify with `npm install -g browserify`,
perform the following (assuming *main.js* is your entry file):
```shell
browserify main.js > bundle.js
```
Then include *bundle.js* in the HTML pages.
### Webpack Configuration
Using Webpack you may encounter the following error: "Module not found: Error:
Cannot resolve module", most certainly you should disable AMD loader. Add/merge
the following section to your webpack config:
```javascript
module: {
rules: [
{
parser: {
amd: false
}
}
]
}
```
## Getting Started
Please follow the [installation](#installation) instruction and execute the following JS code:
```javascript
var {{{moduleName}}} = require('{{{projectName}}}');
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
{{#hasAuthMethods}}
var defaultClient = {{{moduleName}}}.ApiClient.instance;
{{#authMethods}}
{{#isBasic}}
{{#isBasicBasic}}
// Configure HTTP basic authorization: {{{name}}}
var {{{name}}} = defaultClient.authentications['{{{name}}}'];
{{{name}}}.username = 'YOUR USERNAME'
{{{name}}}.password = 'YOUR PASSWORD'
{{/isBasicBasic}}
{{#isBasicBearer}}
// Configure Bearer{{#bearerFormat}} ({{{.}}}){{/bearerFormat}} access token for authorization: {{{name}}}
var {{{name}}} = defaultClient.authentications['{{{name}}}'];
{{{name}}}.accessToken = "YOUR ACCESS TOKEN"
{{/isBasicBearer}}
{{/isBasic}}
{{#isApiKey}}
// Configure API key authorization: {{{name}}}
var {{{name}}} = defaultClient.authentications['{{{name}}}'];
{{{name}}}.apiKey = "YOUR API KEY"
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//{{{name}}}.apiKeyPrefix['{{{keyParamName}}}'] = "Token"
{{/isApiKey}}
{{#isOAuth}}
// Configure OAuth2 access token for authorization: {{{name}}}
var {{{name}}} = defaultClient.authentications['{{{name}}}'];
{{{name}}}.accessToken = "YOUR ACCESS TOKEN"
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
var api = new {{{moduleName}}}.{{{classname}}}()
{{#hasParams}}
{{#requiredParams}}
var {{{paramName}}} = {{{example}}}; // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}}
{{/requiredParams}}
{{#optionalParams}}
{{#-first}}
var opts = {
{{/-first}}
'{{{paramName}}}': {{{example}}}{{^-last}},{{/-last}} // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}}
{{#-last}}
};
{{/-last}}
{{/optionalParams}}
{{/hasParams}}
{{#usePromises}}
api.{{{operationId}}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}).then(function({{#returnType}}data{{/returnType}}) {
{{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}}
}, function(error) {
console.error(error);
});
{{/usePromises}}
{{^usePromises}}
var callback = function(error, data, response) {
if (error) {
console.error(error);
} else {
{{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}}
}
};
api.{{{operationId}}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}{{#hasParams}}, {{/hasParams}}callback);
{{/usePromises}}
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
```
## Documentation for API Endpoints
All URIs are relative to *{{basePath}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{moduleName}}.{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation for Models
{{#models}}{{#model}} - [{{moduleName}}.{{classname}}]({{modelDocPath}}{{classname}}.md)
{{/model}}{{/models}}
## Documentation for Authorization
{{^authMethods}}
All endpoints do not require authorization.
{{/authMethods}}
{{#authMethods}}
{{#last}} Authentication schemes defined for the API:{{/last}}
### {{name}}
{{#isApiKey}}
- **Type**: API key
- **API key parameter name**: {{keyParamName}}
- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}}
{{/isApiKey}}
{{#isBasic}}
{{#isBasicBasic}}
- **Type**: HTTP basic authentication
{{/isBasicBasic}}
{{#isBasicBearer}}
- **Type**: Bearer authentication{{#bearerFormat}} ({{{.}}}){{/bearerFormat}}
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
- **Type**: OAuth
- **Flow**: {{flow}}
- **Authorization URL**: {{authorizationUrl}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - {{scope}}: {{description}}
{{/scopes}}
{{/isOAuth}}
{{/authMethods}}

View File

@@ -0,0 +1,88 @@
{{>licenseInfo}}
{{=< >=}}
import ApiClient from "../ApiClient";
<#imports>import <&import> from '../<#modelPackage><&modelPackage>/</modelPackage><import>';
</imports>
<#emitJSDoc>/**
* <baseName> service.
* @module <#invokerPackage><&invokerPackage>/</invokerPackage><#apiPackage><&apiPackage>/</apiPackage><classname>
* @version <&projectVersion>
*/</emitJSDoc>
export default class <&classname> extends ApiClient {
<#emitJSDoc>/**
* Constructs a new <&classname>. <#description>
* <description></description>
* @alias module:<#invokerPackage><&invokerPackage>/</invokerPackage><#apiPackage><&apiPackage>/</apiPackage><classname>
* @class
*/</emitJSDoc>
constructor() {
super();
this.baseURL = <#servers.0>basePath</servers.0><^servers.0>null</servers.0>;
}
<#operations><#operation><#emitJSDoc>
/**<#summary>
* <&summary></summary><#notes>
* <&notes></notes><#allParams><#required>
* @param {<&vendorExtensions.x-jsdoc-type>} <&paramName> <&description></required></allParams><#hasOptionalParams>
* @param {Object} opts Optional parameters<#allParams><^required>
* @param {<&vendorExtensions.x-jsdoc-type>} opts.<&paramName> <&description><#defaultValue> (default to <&.>)</defaultValue></required></allParams></hasOptionalParams>
<=| |=>* @return {Promise|#returnType|<|&vendorExtensions.x-jsdoc-type|>|/returnType|}|=< >=|
*/
</emitJSDoc> async <operationId>(<vendorExtensions.x-codegen-arg-list>) {
<#vendorExtensions.x-codegen-has-optional-params>
opts = opts || {};
</vendorExtensions.x-codegen-has-optional-params>
let postBody = <#bodyParam><#required><paramName></required><^required>opts['<paramName>']</required></bodyParam><^bodyParam>null</bodyParam>;
<#allParams>
<#required>
// verify the required parameter '<paramName>' is set
if (<paramName> === undefined || <paramName> === null) {
throw new Error("Missing the required parameter '<paramName>' when calling <operationId>");
}
</required>
</allParams>
let pathParams = {<#pathParams>
'<baseName>': <#required><paramName></required><^required>opts['<paramName>']</required><#hasMore>,</hasMore></pathParams>
};
let queryParams = {<#queryParams>
'<baseName>': <#collectionFormat>this.buildCollectionParam(<#required><paramName></required><^required>opts['<paramName>']</required>, '<collectionFormat>')</collectionFormat><^collectionFormat><#required><paramName></required><^required>opts['<paramName>']</required></collectionFormat><#hasMore>,</hasMore></queryParams>
};
let headerParams = {<#headerParams>
'<baseName>': <#required><paramName></required><^required>opts['<paramName>']</required><#hasMore>,</hasMore></headerParams>
};
let formParams = {<#formParams>
'<baseName>': <#collectionFormat>this.buildCollectionParam(<#required><paramName></required><^required>opts['<paramName>']</required>, '<collectionFormat>')</collectionFormat><^collectionFormat><#required><paramName></required><^required>opts['<paramName>']</required></collectionFormat><#hasMore>,</hasMore></formParams>
};
let authNames = [<#authMethods>'<name>'<#hasMore>, </hasMore></authMethods>];
let contentTypes = [<#consumes>'<& mediaType>'<#hasMore>, </hasMore></consumes>];
let accepts = [<#produces>'<& mediaType>'<#hasMore>, </hasMore></produces>];
let returnType = <#vendorExtensions.x-return-type><&vendorExtensions.x-return-type></vendorExtensions.x-return-type><^vendorExtensions.x-return-type>null</vendorExtensions.x-return-type>;
<#servers.0>
let basePaths = [<#servers>'<url>'<^-last>, </-last></servers>];
let basePath = basePaths[0]; // by default use the first one in "servers" defined in OpenAPI
if (typeof opts['_base_path_index'] !== 'undefined') {
if (opts['_base_path_index'] >= basePaths.length || opts['_base_path_index'] < 0) {
throw new Error("Invalid index " + opts['_base_path_index'] + " when selecting the host settings. Must be less than " + basePaths.length);
}
basePath = basePaths[opts['_base_path_index']];
}
</servers.0>
return this.callApi(
'<&path>', '<httpMethod>',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
</operation></operations>
}
<={{ }}=>

View File

@@ -0,0 +1,112 @@
# {{moduleName}}.{{classname}}{{#description}}
{{description}}{{/description}}
All URIs are relative to *{{basePath}}*
Method | HTTP request | Description
------------- | ------------- | -------------
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}
{{#operations}}
{{#operation}}
## {{operationId}}
> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}})
{{summary}}{{#notes}}
{{notes}}{{/notes}}
### Example
```javascript
import {{{moduleName}}} from '{{{projectName}}}';
{{#hasAuthMethods}}
let defaultClient = {{{moduleName}}}.ApiClient.instance;
{{#authMethods}}
{{#isBasic}}
{{#isBasicBasic}}
// Configure HTTP basic authorization: {{{name}}}
let {{{name}}} = defaultClient.authentications['{{{name}}}'];
{{{name}}}.username = 'YOUR USERNAME';
{{{name}}}.password = 'YOUR PASSWORD';
{{/isBasicBasic}}
{{#isBasicBearer}}
// Configure Bearer{{#bearerFormat}} ({{{.}}}){{/bearerFormat}} access token for authorization: {{{name}}}
let {{{name}}} = defaultClient.authentications['{{{name}}}'];
{{{name}}}.accessToken = "YOUR ACCESS TOKEN"
{{/isBasicBearer}}
{{/isBasic}}
{{#isApiKey}}
// Configure API key authorization: {{{name}}}
let {{{name}}} = defaultClient.authentications['{{{name}}}'];
{{{name}}}.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//{{{name}}}.apiKeyPrefix = 'Token';
{{/isApiKey}}
{{#isOAuth}}
// Configure OAuth2 access token for authorization: {{{name}}}
let {{{name}}} = defaultClient.authentications['{{{name}}}'];
{{{name}}}.accessToken = 'YOUR ACCESS TOKEN';
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
let apiInstance = new {{{moduleName}}}.{{{classname}}}();
{{#requiredParams}}
let {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}}
{{/requiredParams}}
{{#optionalParams}}
{{#-first}}
let opts = {
{{/-first}}
'{{{paramName}}}': {{{example}}}{{^-last}},{{/-last}} // {{{dataType}}} | {{{description}}}
{{#-last}}
};
{{/-last}}
{{/optionalParams}}
{{#usePromises}}
apiInstance.{{{operationId}}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}).then(({{#returnType}}data{{/returnType}}) => {
{{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}}
}, (error) => {
console.error(error);
});
{{/usePromises}}
{{^usePromises}}
apiInstance.{{{operationId}}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}{{#optionalParams}}{{#-last}}{{#hasRequiredParams}}, {{/hasRequiredParams}}opts{{/-last}}{{/optionalParams}}{{#hasParams}}, {{/hasParams}}(error, data, response) => {
if (error) {
console.error(error);
} else {
{{#returnType}}console.log('API called successfully. Returned data: ' + data);{{/returnType}}{{^returnType}}console.log('API called successfully.');{{/returnType}}
}
});
{{/usePromises}}
```
### Parameters
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}
{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}
{{/allParams}}
### Return type
{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}}
### Authorization
{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}}
### HTTP request headers
- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}
{{/operation}}
{{/operations}}

View File

@@ -0,0 +1,44 @@
{{>licenseInfo}}
// CommonJS-like environments that support module.exports, like Node.
factory(require('expect.js'), require(process.cwd()+'/src/{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}index'));
'use strict';
var instance;
beforeEach(function() {
instance = new {{moduleName}}.{{classname}}();
});
var getProperty = function(object, getter, property) {
// Use getter method if present; otherwise, get the property directly.
if (typeof object[getter] === 'function')
return object[getter]();
else
return object[property];
}
var setProperty = function(object, setter, property, value) {
// Use setter method if present; otherwise, set the property directly.
if (typeof object[setter] === 'function')
object[setter](value);
else
object[property] = value;
}
describe('{{classname}}', function() {
{{#operations}}
{{#operation}}
describe('{{operationId}}', function() {
it('should call {{operationId}} successfully', function(done) {
//uncomment below and update the code to test {{operationId}}
//instance.{{operationId}}(function(error) {
// if (error) throw error;
//expect().to.be();
//});
done();
});
});
{{/operation}}
{{/operations}}
});

View File

@@ -0,0 +1,15 @@
{{#emitJSDoc}}/**
* Allowed values for the <code>{{baseName}}</code> property.
* @enum {{=<% %>=}}{<%datatype%>}<%={{ }}=%>
* @readonly
*/{{/emitJSDoc}}
export default {{datatypeWithEnum}} = {
{{#allowableValues}}{{#enumVars}}
{{#emitJSDoc}}/**
* value: {{{value}}}
* @const
*/{{/emitJSDoc}}
"{{name}}": {{{value}}}{{^-last}},
{{/-last}}
{{/enumVars}}{{/allowableValues}}
};

View File

@@ -0,0 +1,58 @@
#!/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-pestore-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="{{{gitHost}}}"
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id="{{{gitUserId}}}"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="{{{gitRepoId}}}"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="{{{releaseNote}}}"
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,33 @@
# Logs
logs
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directory
node_modules
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history

View File

@@ -0,0 +1,58 @@
{{>licenseInfo}}
import ApiClient from './ApiClient';
{{#models}}import {{#model}}{{classFilename}}{{/model}} from './{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{importPath}}';
{{/models}}{{#apiInfo}}{{#apis}}import {{importPath}} from './{{#apiPackage}}{{apiPackage}}/{{/apiPackage}}{{importPath}}';
{{/apis}}{{/apiInfo}}
{{#emitJSDoc}}/**{{#projectDescription}}
* {{projectDescription}}.<br>{{/projectDescription}}
* The <code>index</code> module provides access to constructors for all the classes which comprise the public API.
* <p>
* An AMD (recommended!) or CommonJS application will generally do something equivalent to the following:
* <pre>
* var {{moduleName}} = require('{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}index'); // See note below*.
* var xxxSvc = new {{moduleName}}.XxxApi(); // Allocate the API class we're going to use.
* var yyyModel = new {{moduleName}}.Yyy(); // Construct a model instance.
* yyyModel.someProperty = 'someValue';
* ...
* var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
* ...
* </pre>
* <em>*NOTE: For a top-level AMD script, use require(['{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}index'], function(){...})
* and put the application logic within the callback function.</em>
* </p>
* <p>
* A non-AMD browser application (discouraged) might do something like this:
* <pre>
* var xxxSvc = new {{moduleName}}.XxxApi(); // Allocate the API class we're going to use.
* var yyy = new {{moduleName}}.Yyy(); // Construct a model instance.
* yyyModel.someProperty = 'someValue';
* ...
* var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
* ...
* </pre>
* </p>
* @module {{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}index
* @version {{projectVersion}}
*/{{/emitJSDoc}}
export {
{{=< >=}}
<#emitJSDoc>/**
* The ApiClient constructor.
* @property {module:<#invokerPackage><invokerPackage>/</invokerPackage>ApiClient}
*/</emitJSDoc>
ApiClient<#models>,
<#emitJSDoc>/**
* The <importPath> model constructor.
* @property {module:<#invokerPackage><invokerPackage>/</invokerPackage><#modelPackage><modelPackage>/</modelPackage><importPath>}
*/</emitJSDoc>
<importPath></models><#apiInfo><#apis>,
<#emitJSDoc>/**
* The <importPath> service constructor.
* @property {module:<#invokerPackage><invokerPackage>/</invokerPackage><#apiPackage><apiPackage>/</apiPackage><importPath>}
*/</emitJSDoc>
<importPath></apis></apiInfo>
};<={{ }}=>

View File

@@ -0,0 +1,12 @@
/**
* {{{appName}}}
* {{{appDescription}}}
*
* {{#version}}The version of the OpenAPI document: {{{version}}}{{/version}}
* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
*/

View File

@@ -0,0 +1 @@
--timeout 10000

View File

@@ -0,0 +1,4 @@
{{>licenseInfo}}
import ApiClient from '../ApiClient';
{{#imports}}import {{import}} from './{{import}}';
{{/imports}}{{#models}}{{#model}}{{#isEnum}}{{>partial_model_enum_class}}{{/isEnum}}{{^isEnum}}{{>partial_model_generic}}{{/isEnum}}{{/model}}{{/models}}

View File

@@ -0,0 +1,26 @@
{{#models}}{{#model}}{{#isEnum}}# {{moduleName}}.{{classname}}
## Enum
{{#allowableValues}}{{#enumVars}}
* `{{name}}` (value: `{{{value}}}`)
{{/enumVars}}{{/allowableValues}}
{{/isEnum}}{{^isEnum}}# {{moduleName}}.{{classname}}
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}
{{/vars}}
{{#vars}}{{#isEnum}}
## Enum: {{datatypeWithEnum}}
{{#allowableValues}}{{#enumVars}}
* `{{name}}` (value: `{{{value}}}`)
{{/enumVars}}{{/allowableValues}}
{{/isEnum}}{{/vars}}
{{/isEnum}}{{/model}}{{/models}}

View File

@@ -0,0 +1,65 @@
{{>licenseInfo}}
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD.
define(['expect.js', process.cwd()+'/src/{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}index'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
factory(require('expect.js'), require(process.cwd()+'/src/{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}index'));
} else {
// Browser globals (root is window)
factory(root.expect, root.{{moduleName}});
}
}(this, function(expect, {{moduleName}}) {
'use strict';
var instance;
beforeEach(function() {
{{#models}}
{{#model}}
{{^isEnum}}
instance = new {{moduleName}}.{{classname}}();
{{/isEnum}}
{{/model}}
{{/models}}
});
var getProperty = function(object, getter, property) {
// Use getter method if present; otherwise, get the property directly.
if (typeof object[getter] === 'function')
return object[getter]();
else
return object[property];
}
var setProperty = function(object, setter, property, value) {
// Use setter method if present; otherwise, set the property directly.
if (typeof object[setter] === 'function')
object[setter](value);
else
object[property] = value;
}
describe('{{classname}}', function() {
it('should create an instance of {{classname}}', function() {
// uncomment below and update the code to test {{classname}}
//var instane = new {{moduleName}}.{{classname}}();
//expect(instance).to.be.a({{moduleName}}.{{classname}});
});
{{#models}}
{{#model}}
{{#vars}}
it('should have the property {{name}} (base name: "{{baseName}}")', function() {
// uncomment below and update the code to test the property {{name}}
//var instane = new {{moduleName}}.{{classname}}();
//expect(instance).to.be();
});
{{/vars}}
{{/model}}
{{/models}}
});
}));

View File

@@ -0,0 +1,29 @@
{
"name": "{{{projectName}}}",
"version": "{{{projectVersion}}}",
"description": "{{{projectDescription}}}",
"license": "{{licenseName}}",
"main": "src/index.js",
"scripts": {
"test": "mocha --require @babel/register --recursive"
},
"browser": {
"fs": false
},
{{#npmRepository}}
"publishConfig":{
"registry":"{{npmRepository}}"
},
{{/npmRepository}}
"dependencies": {
"apollo-datasource-rest": "^0.7.0"
},
"devDependencies": {
"expect.js": "^0.3.1",
"mocha": "^5.2.0",
"sinon": "^7.2.0"
},
"files": [
"src"
]
}

View File

@@ -0,0 +1,24 @@
{{#emitJSDoc}}/**
* Enum class {{classname}}.
* @enum {{=<% %>=}}{<%datatype%>}<%={{ }}=%>
* @readonly
*/{{/emitJSDoc}}
export default class {{classname}} {
{{#allowableValues}}{{#enumVars}}
{{#emitJSDoc}}/**
* value: {{{value}}}
* @const
*/{{/emitJSDoc}}
"{{name}}" = {{{value}}};
{{/enumVars}}{{/allowableValues}}
{{#emitJSDoc}}/**
* Returns a <code>{{classname}}</code> enum value from a Javascript object name.
* @param {Object} data The plain JavaScript object containing the name of the enum value.
* @return {{=< >=}}{module:<#invokerPackage><invokerPackage>/</invokerPackage><#modelPackage><modelPackage>/</modelPackage><classname>}<={{ }}=> The enum <code>{{classname}}</code> value.
*/{{/emitJSDoc}}
static constructFromObject(object) {
return object;
}
}

View File

@@ -0,0 +1,82 @@
{{#models}}{{#model}}{{#emitJSDoc}}/**
* The {{classname}} model module.
* @module {{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{classname}}
* @version {{projectVersion}}
*/{{/emitJSDoc}}
class {{classname}} {{#parent}}{{^parentModel}}{{#vendorExtensions.x-is-array}}extends Array {{/vendorExtensions.x-is-array}}{{/parentModel}}{{/parent}}{
{{#vars}}
{{#emitJSDoc}}/**
* @member {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{baseName}}
* @type {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=>{{#defaultValue}}
* @default {{{defaultValue}}}{{/defaultValue}}
*/{{/emitJSDoc}}
{{baseName}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}};
{{/vars}}
{{#useInheritance}}{{#interfaceModels}}{{#allVars}}{{#emitJSDoc}}/**
* @member {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{baseName}}
* @type {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=>
*/{{/emitJSDoc}}
#{{baseName}};
{{/allVars}}{{/interfaceModels}}{{/useInheritance}}
{{#emitJSDoc}}/**
* Constructs a new <code>{{classname}}</code>.{{#description}}
* {{description}}{{/description}}
* @alias module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{classname}}{{#useInheritance}}{{#parent}}
* @extends {{#parentModel}}module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{classname}}{{/parentModel}}{{^parentModel}}{{#vendorExtensions.x-is-array}}Array{{/vendorExtensions.x-is-array}}{{#vendorExtensions.x-is-map}}Object{{/vendorExtensions.x-is-map}}{{/parentModel}}{{/parent}}{{#interfaces}}
* @implements module:{{#invokerPackage}}{{invokerPackage}}/{{/invokerPackage}}{{#modelPackage}}{{modelPackage}}/{{/modelPackage}}{{.}}{{/interfaces}}{{/useInheritance}}{{#vendorExtensions.x-all-required}}
* @param {{name}} {{=< >=}}{<&vendorExtensions.x-jsdoc-type>}<={{ }}=> {{#description}}{{{description}}}{{/description}}{{/vendorExtensions.x-all-required}}
*/{{/emitJSDoc}}
constructor({{#vendorExtensions.x-all-required}}{{name}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-all-required}}) { {{#parent}}{{^parentModel}}{{#vendorExtensions.x-is-array}}
super();
{{/vendorExtensions.x-is-array}}{{/parentModel}}{{/parent}}{{#useInheritance}}
{{#interfaceModels}}{{classname}}.initialize(this{{#vendorExtensions.x-all-required}}, {{name}}{{/vendorExtensions.x-all-required}});{{/interfaceModels}}{{/useInheritance}}
{{classname}}.initialize(this{{#vendorExtensions.x-all-required}}, {{name}}{{/vendorExtensions.x-all-required}});
}
{{#emitJSDoc}}/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/{{/emitJSDoc}}
static initialize(obj{{#vendorExtensions.x-all-required}}, {{name}}{{/vendorExtensions.x-all-required}}) { {{#vars}}{{#required}}
obj['{{baseName}}'] = {{name}};{{/required}}{{/vars}}
}
{{#emitJSDoc}}/**
* Constructs a <code>{{classname}}</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {{=< >=}}{module:<#invokerPackage><invokerPackage>/</invokerPackage><#modelPackage><modelPackage>/</modelPackage><classname>}<={{ }}=> obj Optional instance to populate.
* @return {{=< >=}}{module:<#invokerPackage><invokerPackage>/</invokerPackage><#modelPackage><modelPackage>/</modelPackage><classname>}<={{ }}=> The populated <code>{{classname}}</code> instance.
*/{{/emitJSDoc}}
static constructFromObject(data, obj) {
if (data){{! TODO: support polymorphism: discriminator property on data determines class to instantiate.}} {
obj = obj || new {{classname}}();{{#parent}}{{^parentModel}}
ApiClient.constructFromObject(data, obj, '{{vendorExtensions.x-item-type}}');
{{/parentModel}}{{/parent}}{{#useInheritance}}{{#parentModel}}
{{classname}}.constructFromObject(data, obj);{{/parentModel}}{{#interfaces}}
{{.}}.constructFromObject(data, obj);{{/interfaces}}{{/useInheritance}}
{{#vars}}
if (data.hasOwnProperty('{{baseName}}')) {
obj['{{baseName}}']{{{defaultValueWithParam}}}
}
{{/vars}}
}
return obj;
}
{{/model}}
}
{{#vars}}{{#isEnum}}{{^isContainer}}
{{>partial_model_inner_enum}}
{{/isContainer}}{{/isEnum}}{{#items.isEnum}}{{#items}}{{^isContainer}}
{{>partial_model_inner_enum}}
{{/isContainer}}{{/items}}{{/items.isEnum}}{{/vars}}
export default {{classname}};
{{/models}}

View File

@@ -0,0 +1,15 @@
{{#emitJSDoc}}/**
* Allowed values for the <code>{{baseName}}</code> property.
* @enum {{=<% %>=}}{<%datatype%>}<%={{ }}=%>
* @readonly
*/{{/emitJSDoc}}
{{classname}}['{{datatypeWithEnum}}'] = {
{{#allowableValues}}{{#enumVars}}
{{#emitJSDoc}}/**
* value: {{{value}}}
* @const
*/{{/emitJSDoc}}
"{{name}}": {{{value}}}{{^-last}},
{{/-last}}
{{/enumVars}}{{/allowableValues}}
};

View File

@@ -0,0 +1,5 @@
language: node_js
cache: npm
node_js:
- "6"
- "6.1"

View File

@@ -60,6 +60,7 @@ org.openapitools.codegen.languages.JavaResteasyServerCodegen
org.openapitools.codegen.languages.JavaResteasyEapServerCodegen
org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen
org.openapitools.codegen.languages.JavascriptClientCodegen
org.openapitools.codegen.languages.JavascriptApolloClientCodegen
org.openapitools.codegen.languages.JavascriptFlowtypedClientCodegen
org.openapitools.codegen.languages.JavascriptClosureAngularClientCodegen
org.openapitools.codegen.languages.JMeterClientCodegen