[typescript-node] fixed enum generator for top level enums #665 (#2266)

* [typescript-node] fixed enum generator for top level enums #665

* [typescript-node] fixed enum generator for top level enums in models.mustache #665

* Remove wrong copyright line
This commit is contained in:
christof-vollrath-spring-media 2019-07-15 15:41:40 +02:00 committed by Esteban Gehring
parent 244eefcec4
commit 8417c5bed0
16 changed files with 710 additions and 0 deletions

View File

@ -10,6 +10,7 @@ import { {{classname}} } from './{{filename}}';
* {{{description}}} * {{{description}}}
*/ */
{{/description}} {{/description}}
{{^isEnum}}
export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{
{{#vars}} {{#vars}}
{{#description}} {{#description}}
@ -65,5 +66,15 @@ export namespace {{classname}} {
{{/vars}} {{/vars}}
} }
{{/hasEnums}} {{/hasEnums}}
{{/isEnum}}
{{#isEnum}}
export enum {{classname}} {
{{#allowableValues}}
{{#enumVars}}
{{name}} = <any> {{{value}}}{{^-last}},{{/-last}}
{{/enumVars}}
{{/allowableValues}}
}
{{/isEnum}}
{{/model}} {{/model}}
{{/models}} {{/models}}

View File

@ -34,6 +34,9 @@ let enumsMap: {[index: string]: any} = {
{{/isEnum}} {{/isEnum}}
{{/vars}} {{/vars}}
{{/hasEnums}} {{/hasEnums}}
{{#isEnum}}
"{{classname}}": {{classname}},
{{/isEnum}}
{{/model}} {{/model}}
{{/models}} {{/models}}
} }
@ -41,7 +44,9 @@ let enumsMap: {[index: string]: any} = {
let typeMap: {[index: string]: any} = { let typeMap: {[index: string]: any} = {
{{#models}} {{#models}}
{{#model}} {{#model}}
{{^isEnum}}
"{{classname}}": {{classname}}, "{{classname}}": {{classname}},
{{/isEnum}}
{{/model}} {{/model}}
{{/models}} {{/models}}
} }

View File

@ -0,0 +1,50 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.typescript.typescriptnode;
import org.openapitools.codegen.AbstractIntegrationTest;
import org.openapitools.codegen.CodegenConfig;
import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen;
import org.openapitools.codegen.languages.TypeScriptNodeClientCodegen;
import org.openapitools.codegen.testutils.IntegrationTestPathsConfig;
import java.util.HashMap;
import java.util.Map;
public class TypescriptNodeEnumIntegrationTest extends AbstractIntegrationTest {
@Override
protected CodegenConfig getCodegenConfig() {
return new TypeScriptNodeClientCodegen();
}
@Override
protected Map<String, String> configProperties() {
Map<String, String> properties = new HashMap<>();
properties.put("npmName", "node-es6-test");
properties.put("npmVersion", "1.0.3");
properties.put("snapshot", "false");
properties.put("supportsES6", "false");
return properties;
}
@Override
protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() {
return new IntegrationTestPathsConfig("typescript/objectsWithEnums");
}
}

View File

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

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,3 @@
// This is the entrypoint for the package
export * from './api/apis';
export * from './model/models';

View File

@ -0,0 +1,3 @@
export * from './defaultApi';
import { DefaultApi } from './defaultApi';
export const APIS = [DefaultApi];

View File

@ -0,0 +1,171 @@
/**
* OpenAPI enums
* Tests generation of enums with open opi
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import localVarRequest = require('request');
import http = require('http');
import Promise = require('bluebird');
/* tslint:disable:no-unused-locals */
import { ObjectWithEnums } from '../model/objectWithEnums';
import { ObjectSerializer, Authentication, HttpBasicAuth, ApiKeyAuth, OAuth, VoidAuth } from '../model/models';
let defaultBasePath = 'http://enums.openapi3';
// ===============================================
// This file is autogenerated - Please do not edit
// ===============================================
export enum DefaultApiApiKeys {
}
export class DefaultApi {
protected _basePath = defaultBasePath;
protected defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications = {
'default': <Authentication>new VoidAuth(),
}
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
set basePath(basePath: string) {
this._basePath = basePath;
}
get basePath() {
return this._basePath;
}
public setDefaultAuthentication(auth: Authentication) {
this.authentications.default = auth;
}
public setApiKey(key: DefaultApiApiKeys, value: string) {
(this.authentications as any)[DefaultApiApiKeys[key]].apiKey = value;
}
/**
*
*/
public getObjectWithEnums (options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.ClientResponse; body: Array<ObjectWithEnums>; }> {
const localVarPath = this.basePath + '/getobjectwithenums';
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders);
let localVarFormParams: any = {};
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'GET',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
this.authentications.default.applyToRequest(localVarRequestOptions);
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.ClientResponse; body: Array<ObjectWithEnums>; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
body = ObjectSerializer.deserialize(body, "Array<ObjectWithEnums>");
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
});
});
}
/**
*
* @param objectWithEnums
*/
public postObjectWithEnums (objectWithEnums: ObjectWithEnums, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.ClientResponse; body?: any; }> {
const localVarPath = this.basePath + '/postobjectwithenums';
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders);
let localVarFormParams: any = {};
// verify required parameter 'objectWithEnums' is not null or undefined
if (objectWithEnums === null || objectWithEnums === undefined) {
throw new Error('Required parameter objectWithEnums was null or undefined when calling postObjectWithEnums.');
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'POST',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: ObjectSerializer.serialize(objectWithEnums, "ObjectWithEnums")
};
this.authentications.default.applyToRequest(localVarRequestOptions);
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject({ response: response, body: body });
}
}
});
});
}
}

View File

@ -0,0 +1,52 @@
#!/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"
git_user_id=$1
git_repo_id=$2
release_note=$3
if [ "$git_user_id" = "" ]; then
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=""
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note=""
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://github.com/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${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://github.com/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -0,0 +1,17 @@
/**
* OpenAPI enums
* Tests generation of enums with open opi
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export enum ExternalEnum {
Green = <any> 'green',
Yellow = <any> 'yellow'
}

View File

@ -0,0 +1,191 @@
export * from './externalEnum';
export * from './objectWithEnums';
import localVarRequest = require('request');
import { ExternalEnum } from './externalEnum';
import { ObjectWithEnums } from './objectWithEnums';
/* tslint:disable:no-unused-variable */
let primitives = [
"string",
"boolean",
"double",
"integer",
"long",
"float",
"number",
"any"
];
let enumsMap: {[index: string]: any} = {
"ExternalEnum": ExternalEnum,
"ObjectWithEnums.EnumInObjectEnum": ObjectWithEnums.EnumInObjectEnum,
}
let typeMap: {[index: string]: any} = {
"ObjectWithEnums": ObjectWithEnums,
}
export class ObjectSerializer {
public static findCorrectType(data: any, expectedType: string) {
if (data == undefined) {
return expectedType;
} else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) {
return expectedType;
} else if (expectedType === "Date") {
return expectedType;
} else {
if (enumsMap[expectedType]) {
return expectedType;
}
if (!typeMap[expectedType]) {
return expectedType; // w/e we don't know the type
}
// Check the discriminator
let discriminatorProperty = typeMap[expectedType].discriminator;
if (discriminatorProperty == null) {
return expectedType; // the type does not have a discriminator. use it.
} else {
if (data[discriminatorProperty]) {
var discriminatorType = data[discriminatorProperty];
if(typeMap[discriminatorType]){
return discriminatorType; // use the type given in the discriminator
} else {
return expectedType; // discriminator did not map to a type
}
} else {
return expectedType; // discriminator was not present (or an empty string)
}
}
}
}
public static serialize(data: any, type: string) {
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index in data) {
let date = data[index];
transformedData.push(ObjectSerializer.serialize(date, subType));
}
return transformedData;
} else if (type === "Date") {
return data.toISOString();
} else {
if (enumsMap[type]) {
return data;
}
if (!typeMap[type]) { // in case we dont know the type
return data;
}
// Get the actual type of this object
type = this.findCorrectType(data, type);
// get the map for the correct type.
let attributeTypes = typeMap[type].getAttributeTypeMap();
let instance: {[index: string]: any} = {};
for (let index in attributeTypes) {
let attributeType = attributeTypes[index];
instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type);
}
return instance;
}
}
public static deserialize(data: any, type: string) {
// polymorphism may change the actual type.
type = ObjectSerializer.findCorrectType(data, type);
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index in data) {
let date = data[index];
transformedData.push(ObjectSerializer.deserialize(date, subType));
}
return transformedData;
} else if (type === "Date") {
return new Date(data);
} else {
if (enumsMap[type]) {// is Enum
return data;
}
if (!typeMap[type]) { // dont know the type
return data;
}
let instance = new typeMap[type]();
let attributeTypes = typeMap[type].getAttributeTypeMap();
for (let index in attributeTypes) {
let attributeType = attributeTypes[index];
instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type);
}
return instance;
}
}
}
export interface Authentication {
/**
* Apply authentication settings to header and query params.
*/
applyToRequest(requestOptions: localVarRequest.Options): void;
}
export class HttpBasicAuth implements Authentication {
public username: string = '';
public password: string = '';
applyToRequest(requestOptions: localVarRequest.Options): void {
requestOptions.auth = {
username: this.username, password: this.password
}
}
}
export class ApiKeyAuth implements Authentication {
public apiKey: string = '';
constructor(private location: string, private paramName: string) {
}
applyToRequest(requestOptions: localVarRequest.Options): void {
if (this.location == "query") {
(<any>requestOptions.qs)[this.paramName] = this.apiKey;
} else if (this.location == "header" && requestOptions && requestOptions.headers) {
requestOptions.headers[this.paramName] = this.apiKey;
}
}
}
export class OAuth implements Authentication {
public accessToken: string = '';
applyToRequest(requestOptions: localVarRequest.Options): void {
if (requestOptions && requestOptions.headers) {
requestOptions.headers["Authorization"] = "Bearer " + this.accessToken;
}
}
}
export class VoidAuth implements Authentication {
public username: string = '';
public password: string = '';
applyToRequest(_: localVarRequest.Options): void {
// Do nothing
}
}

View File

@ -0,0 +1,43 @@
/**
* OpenAPI enums
* Tests generation of enums with open opi
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { ExternalEnum } from './externalEnum';
export class ObjectWithEnums {
'enumInObject'?: ObjectWithEnums.EnumInObjectEnum;
'externalEnum'?: ExternalEnum;
static discriminator: string | undefined = undefined;
static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [
{
"name": "enumInObject",
"baseName": "enumInObject",
"type": "ObjectWithEnums.EnumInObjectEnum"
},
{
"name": "externalEnum",
"baseName": "externalEnum",
"type": "ExternalEnum"
} ];
static getAttributeTypeMap() {
return ObjectWithEnums.attributeTypeMap;
}
}
export namespace ObjectWithEnums {
export enum EnumInObjectEnum {
Red = <any> 'red',
Blue = <any> 'blue'
}
}

View File

@ -0,0 +1,26 @@
{
"name": "node-es6-test",
"version": "1.0.3",
"description": "NodeJS client for node-es6-test",
"repository": "/",
"main": "dist/api.js",
"types": "dist/api.d.ts",
"scripts": {
"clean": "rm -Rf node_modules/ *.js",
"build": "tsc",
"test": "npm run build && node dist/client.js"
},
"author": "OpenAPI-Generator Contributors",
"license": "Unlicense",
"dependencies": {
"bluebird": "^3.5.0",
"request": "^2.81.0",
"@types/bluebird": "*",
"@types/request": "*",
"rewire": "^3.0.2"
},
"devDependencies": {
"typescript": "^2.4.2",
"@types/node": "8.10.34"
}
}

View File

@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true,
"target": "ES5",
"strict": true,
"moduleResolution": "node",
"removeComments": true,
"sourceMap": true,
"noLib": false,
"declaration": true,
"lib": ["dom", "es6", "es5", "dom.iterable", "scripthost"],
"outDir": "dist"
},
"exclude": [
"dist",
"node_modules"
]
}

View File

@ -0,0 +1,91 @@
{
"openapi" : "3.0.0",
"info" : {
"title" : "OpenAPI enums",
"description" : "Tests generation of enums with open opi",
"version" : "1.0.0"
},
"servers" : [ {
"url" : "http://enums.openapi3"
} ],
"paths" : {
"/postobjectwithenums" : {
"post" : {
"operationId" : "postObjectWithEnums",
"requestBody" : {
"$ref" : "#/components/requestBodies/ObjectWithEnums"
},
"responses" : {
"405" : {
"description" : "Invalid input"
}
}
}
},
"/getobjectwithenums" : {
"get" : {
"operationId" : "getObjectWithEnums",
"responses" : {
"200" : {
"description" : "successful operation",
"content" : {
"application/xml" : {
"schema" : {
"type" : "array",
"items" : {
"$ref" : "#/components/schemas/ObjectWithEnums"
}
}
},
"application/json" : {
"schema" : {
"type" : "array",
"items" : {
"$ref" : "#/components/schemas/ObjectWithEnums"
}
}
}
}
}
}
}
}
},
"components" : {
"schemas" : {
"ObjectWithEnums" : {
"type" : "object",
"properties" : {
"enumInObject" : {
"type" : "string",
"enum" : [ "red", "blue" ]
},
"externalEnum" : {
"$ref" : "#/components/schemas/ExternalEnum"
}
}
},
"ExternalEnum" : {
"type" : "string",
"enum" : [ "green", "yellow" ]
}
},
"requestBodies" : {
"ObjectWithEnums" : {
"content" : {
"application/json" : {
"schema" : {
"$ref" : "#/components/schemas/ObjectWithEnums"
}
},
"application/xml" : {
"schema" : {
"$ref" : "#/components/schemas/ObjectWithEnums"
}
}
},
"required" : true
}
}
}
}