Add typescript-inversify code generator (#7885)

* Add typescript-inversify language

* Add windows script


Add windows script

* Use rxjs instead of rx and encoding only the value of URL parameters

* Remove lodash dependency


Remove lodash dependency

* Readd linux user detail on run-docker script

* Solve import problems

* Remove configuration template

* Add usePromise config's variable

* Align Test to check usePromise config parameter

* Add possibility to receive all the httpResponse

* Better ts-lint on api service

* Update sample client example with new ts-lint

* Update petstore sample with new ts-lint
This commit is contained in:
Gualtieri Mario 2018-04-03 18:30:53 +02:00 committed by William Cheng
parent 240aad8686
commit e2c58fad71
67 changed files with 2660 additions and 1 deletions

View File

@ -0,0 +1,31 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/typescript-inversify -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l typescript-inversify -o samples/client/petstore-security-test/typescript-inversify"
java $JAVA_OPTS -jar $executable $ags

View File

@ -0,0 +1,31 @@
#!/bin/sh
SCRIPT="$0"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"
if [ ! -f "$executable" ]
then
mvn clean package
fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l typescript-inversify -o samples/client/petstore/typescript-inversify"
java $JAVA_OPTS -jar $executable $ags

View File

@ -0,0 +1,14 @@
@ECHO OFF
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
echo
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l typescript-inversify -o samples\client\petstore\typescript-inversify\builds\default
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -0,0 +1,10 @@
set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l typescript-inversify -o samples\client\petstore\typescript-inversify
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -0,0 +1,373 @@
package io.swagger.codegen.languages;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.SupportingFile;
import io.swagger.codegen.utils.SemVer;
import io.swagger.models.ModelImpl;
import io.swagger.models.properties.*;
public class TypeScriptInversifyClientCodegen extends AbstractTypeScriptClientCodegen {
private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm");
private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value";
public static final String NPM_NAME = "npmName";
public static final String NPM_VERSION = "npmVersion";
public static final String NPM_REPOSITORY = "npmRepository";
public static final String SNAPSHOT = "snapshot";
public static final String WITH_INTERFACES = "withInterfaces";
public static final String USE_PROMISE = "usePromise";
public static final String TAGGED_UNIONS ="taggedUnions";
protected String npmVersion = null;
protected String npmName = null;
protected String npmRepository = null;
private boolean taggedUnions = false;
public TypeScriptInversifyClientCodegen() {
super();
this.outputFolder = "generated-code/typescript-inversify";
embeddedTemplateDir = templateDir = "typescript-inversify";
modelTemplateFiles.put("model.mustache", ".ts");
apiTemplateFiles.put("api.service.mustache", ".ts");
languageSpecificPrimitives.add("Blob");
typeMapping.put("file", "Blob");
apiPackage = "api";
modelPackage = "model";
this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package"));
this.cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package"));
this.cliOptions.add(new CliOption(NPM_REPOSITORY,
"Use this property to set an url your private npmRepo in the package.json"));
this.cliOptions.add(new CliOption(SNAPSHOT,
"When setting this property to true the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm",
BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(WITH_INTERFACES,
"Setting this property to true will generate interfaces next to the default class implementations.",
BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(USE_PROMISE,
"Setting this property to use promise instead of observable inside every service.",
BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(TAGGED_UNIONS,
"Use discriminators to create tagged unions instead of extending interfaces.",
BooleanProperty.TYPE).defaultValue(Boolean.FALSE.toString()));
}
@Override
protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, ModelImpl swaggerModel) {
codegenModel.additionalPropertiesType = getTypeDeclaration(swaggerModel.getAdditionalProperties());
addImport(codegenModel, codegenModel.additionalPropertiesType);
}
@Override
public String getName() {
return "typescript-inversify";
}
@Override
public String getHelp() {
return "Generates Typescript services using Inversify IOC";
}
@Override
public void processOpts() {
super.processOpts();
// HttpClient
supportingFiles.add(new SupportingFile("IHttpClient.mustache", getIndexDirectory(), "IHttpClient.ts"));
supportingFiles.add(new SupportingFile("IAPIConfiguration.mustache", getIndexDirectory(), "IAPIConfiguration.ts"));
supportingFiles.add(new SupportingFile("HttpClient.mustache", getIndexDirectory(), "HttpClient.ts"));
supportingFiles.add(new SupportingFile("HttpResponse.mustache", getIndexDirectory(), "HttpResponse.ts"));
supportingFiles.add(new SupportingFile("Headers.mustache", getIndexDirectory(), "Headers.ts"));
supportingFiles.add(new SupportingFile("ApiServiceBinder.mustache", getIndexDirectory(), "ApiServiceBinder.ts"));
supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts"));
if (additionalProperties.containsKey(NPM_NAME)) {
addNpmPackageGeneration();
}
if (additionalProperties.containsKey(WITH_INTERFACES)) {
boolean withInterfaces = Boolean.parseBoolean(additionalProperties.get(WITH_INTERFACES).toString());
if (withInterfaces) {
apiTemplateFiles.put("apiInterface.mustache", "Interface.ts");
}
}
if (additionalProperties.containsKey(TAGGED_UNIONS)) {
taggedUnions = Boolean.parseBoolean(additionalProperties.get(TAGGED_UNIONS).toString());
}
}
private void addNpmPackageGeneration() {
if (additionalProperties.containsKey(NPM_NAME)) {
this.setNpmName(additionalProperties.get(NPM_NAME).toString());
}
if (additionalProperties.containsKey(NPM_VERSION)) {
this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString());
}
if (additionalProperties.containsKey(SNAPSHOT)
&& Boolean.valueOf(additionalProperties.get(SNAPSHOT).toString())) {
this.setNpmVersion(npmVersion + "-SNAPSHOT." + SNAPSHOT_SUFFIX_FORMAT.format(new Date()));
}
additionalProperties.put(NPM_VERSION, npmVersion);
if (additionalProperties.containsKey(NPM_REPOSITORY)) {
this.setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString());
}
//Files for building our lib
supportingFiles.add(new SupportingFile("models.mustache", modelPackage().replace('.', File.separatorChar), "models.ts"));
supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts"));
supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("README.mustache", getIndexDirectory(), "README.md"));
supportingFiles.add(new SupportingFile("package.mustache", getIndexDirectory(), "package.json"));
supportingFiles.add(new SupportingFile("tsconfig.mustache", getIndexDirectory(), "tsconfig.json"));
}
private String getIndexDirectory() {
String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.')));
return indexPackage.replace('.', File.separatorChar);
}
@Override
public boolean isDataTypeFile(final String dataType) {
return dataType != null && dataType.equals("Blob");
}
@Override
public String getTypeDeclaration(Property p) {
if (p instanceof FileProperty) {
return "Blob";
} else if (p instanceof ObjectProperty) {
return "any";
} else {
return super.getTypeDeclaration(p);
}
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
if (isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) {
return swaggerType;
}
applyLocalTypeMapping(swaggerType);
return swaggerType;
}
private String applyLocalTypeMapping(String type) {
if (typeMapping.containsKey(type)) {
type = typeMapping.get(type);
}
return type;
}
private boolean isLanguagePrimitive(String type) {
return languageSpecificPrimitives.contains(type);
}
private boolean isLanguageGenericType(String type) {
for (String genericType : languageGenericTypes) {
if (type.startsWith(genericType + "<")) {
return true;
}
}
return false;
}
@Override
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
parameter.dataType = applyLocalTypeMapping(parameter.dataType);
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> operations) {
Map<String, Object> objs = (Map<String, Object>) operations.get("operations");
// Add filename information for api imports
objs.put("apiFilename", getApiFilenameFromClassname(objs.get("classname").toString()));
List<CodegenOperation> ops = (List<CodegenOperation>) objs.get("operation");
for (CodegenOperation op : ops) {
// Prep a string buffer where we're going to set up our new version of the string.
StringBuilder pathBuffer = new StringBuilder();
StringBuilder parameterName = new StringBuilder();
int insideCurly = 0;
op.httpMethod = op.httpMethod.toLowerCase();
// Iterate through existing string, one character at a time.
for (int i = 0; i < op.path.length(); i++) {
switch (op.path.charAt(i)) {
case '{':
// We entered curly braces, so track that.
insideCurly++;
// Add the more complicated component instead of just the brace.
pathBuffer.append("${encodeURIComponent(String(");
break;
case '}':
// We exited curly braces, so track that.
insideCurly--;
// Add the more complicated component instead of just the brace.
pathBuffer.append(toVarName(parameterName.toString()));
pathBuffer.append("))}");
parameterName.setLength(0);
break;
default:
if (insideCurly > 0) {
parameterName.append(op.path.charAt(i));
} else {
pathBuffer.append(op.path.charAt(i));
}
break;
}
}
// Overwrite path to TypeScript template string, after applying everything we just did.
op.path = pathBuffer.toString();
}
// Add additional filename information for model imports in the services
List<Map<String, Object>> imports = (List<Map<String, Object>>) operations.get("imports");
for (Map<String, Object> im : imports) {
im.put("filename", im.get("import"));
im.put("classname", getModelnameFromModelFilename(im.get("filename").toString()));
}
return operations;
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
Map<String, Object> result = super.postProcessModels(objs);
return postProcessModelsEnum(result);
}
@Override
public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
Map<String, Object> result = super.postProcessAllModels(objs);
for (Map.Entry<String, Object> entry : result.entrySet()) {
Map<String, Object> inner = (Map<String, Object>) entry.getValue();
List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models");
for (Map<String, Object> mo : models) {
CodegenModel cm = (CodegenModel) mo.get("model");
if (taggedUnions) {
mo.put(TAGGED_UNIONS, true);
if (cm.discriminator != null && cm.children != null) {
for (CodegenModel child : cm.children) {
cm.imports.add(child.classname);
}
}
if (cm.parent != null) {
cm.imports.remove(cm.parent);
}
}
// Add additional filename information for imports
mo.put("tsImports", toTsImports(cm, cm.imports));
}
}
return result;
}
private List<Map<String, String>> toTsImports(CodegenModel cm, Set<String> imports) {
List<Map<String, String>> tsImports = new ArrayList<>();
for (String im : imports) {
if (!im.equals(cm.classname)) {
HashMap<String, String> tsImport = new HashMap<>();
tsImport.put("classname", im);
tsImport.put("filename", toModelFilename(im));
tsImports.add(tsImport);
}
}
return tsImports;
}
@Override
public String toApiName(String name) {
if (name.length() == 0) {
return "DefaultService";
}
return initialCaps(name) + "Service";
}
@Override
public String toApiFilename(String name) {
if (name.length() == 0) {
return "default.service";
}
return camelize(name, true) + ".service";
}
@Override
public String toApiImport(String name) {
return apiPackage() + "/" + toApiFilename(name);
}
@Override
public String toModelFilename(String name) {
return camelize(toModelName(name), true);
}
@Override
public String toModelImport(String name) {
return modelPackage() + "/" + toModelFilename(name);
}
public String getNpmName() {
return npmName;
}
public void setNpmName(String npmName) {
this.npmName = npmName;
}
public String getNpmVersion() {
return npmVersion;
}
public void setNpmVersion(String npmVersion) {
this.npmVersion = npmVersion;
}
public String getNpmRepository() {
return npmRepository;
}
public void setNpmRepository(String npmRepository) {
this.npmRepository = npmRepository;
}
private String getApiFilenameFromClassname(String classname) {
String name = classname.substring(0, classname.length() - "Service".length());
return toApiFilename(name);
}
private String getModelnameFromModelFilename(String filename) {
String name = filename.substring((modelPackage() + "/").length());
return camelize(name);
}
}

View File

@ -81,6 +81,7 @@ io.swagger.codegen.languages.SymfonyServerCodegen
io.swagger.codegen.languages.TizenClientCodegen
io.swagger.codegen.languages.TypeScriptAureliaClientCodegen
io.swagger.codegen.languages.TypeScriptAngularClientCodegen
io.swagger.codegen.languages.TypeScriptInversifyClientCodegen
io.swagger.codegen.languages.TypeScriptAngularJsClientCodegen
io.swagger.codegen.languages.TypeScriptFetchClientCodegen
io.swagger.codegen.languages.TypeScriptJqueryClientCodegen

View File

@ -0,0 +1,20 @@
import {interfaces} from "inversify";
{{#apiInfo}}
{{#apis}}
import { {{classname}} } from './{{importPath}}';
{{#withInterfaces}}
import { {{classname}}Interface } from './{{importPath}}Interface';
{{/withInterfaces}}
{{/apis}}
{{/apiInfo}}
export class ApiServiceBinder {
public static with(container: interfaces.Container) {
{{#apiInfo}}
{{#apis}}
container.bind<{{classname}}{{#withInterfaces}}Interface{{/withInterfaces}}>("{{classname}}").to({{classname}}).inSingletonScope();
{{/apis}}
{{/apiInfo}}
}
}

View File

@ -0,0 +1,3 @@
export interface Headers {
[index:string]: string
}

View File

@ -0,0 +1,63 @@
import IHttpClient from "./IHttpClient";
import { Observable } from "rxjs/Observable";
import "whatwg-fetch";
import HttpResponse from "./HttpResponse";
import {injectable} from "inversify";
import "rxjs/add/observable/fromPromise";
import { Headers } from "./Headers";
@injectable()
class HttpClient implements IHttpClient {
get(url:string, headers?: Headers):Observable<HttpResponse> {
return this.performNetworkCall(url, "get", undefined, headers);
}
post(url: string, body: {}|FormData, headers?: Headers): Observable<HttpResponse> {
return this.performNetworkCall(url, "post", this.getJsonBody(body), this.addJsonHeaders(headers));
}
put(url: string, body: {}, headers?: Headers): Observable<HttpResponse> {
return this.performNetworkCall(url, "put", this.getJsonBody(body), this.addJsonHeaders(headers));
}
delete(url: string, headers?: Headers): Observable<HttpResponse> {
return this.performNetworkCall(url, "delete", undefined, headers);
}
private getJsonBody(body: {}|FormData) {
return !(body instanceof FormData) ? JSON.stringify(body) : body;
}
private addJsonHeaders(headers: Headers) {
return Object.assign({}, {
"Accept": "application/json",
"Content-Type": "application/json"
}, headers);
};
private performNetworkCall(url: string, method: string, body?: any, headers?: Headers): Observable<HttpResponse> {
let promise = window.fetch(url, {
method: method,
body: body,
headers: <any>headers
}).then(response => {
let headers: Headers = {};
response.headers.forEach((value, name) => {
headers[name.toString().toLowerCase()] = value;
});
return response.text().then(text => {
let contentType = headers["content-type"] || "";
let payload = contentType.match("application/json") ? JSON.parse(text) : text;
let httpResponse = new HttpResponse(payload, response.status, headers);
if (response.status >= 400)
throw httpResponse;
return httpResponse;
});
});
return Observable.fromPromise(promise);
}
}
export default HttpClient

View File

@ -0,0 +1,8 @@
import { Headers } from "./Headers"
class HttpResponse<T = any> {
constructor(public response: T, public status:number, public headers?: Headers) {
}
}
export default HttpResponse

View File

@ -0,0 +1,8 @@
export interface IAPIConfiguration {
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
}

View File

@ -0,0 +1,12 @@
import { Observable } from "rxjs/Observable";
import HttpResponse from "./HttpResponse";
import { Headers } from "./Headers";
interface IHttpClient {
get(url:string, headers?: Headers):Observable<HttpResponse>
post(url:string, body:{}|FormData, headers?: Headers):Observable<HttpResponse>
put(url:string, body:{}, headers?: Headers):Observable<HttpResponse>
delete(url:string, headers?: Headers):Observable<HttpResponse>
}
export default IHttpClient

View File

@ -0,0 +1,74 @@
## {{npmName}}@{{npmVersion}}
### Building
To build an compile the typescript sources to javascript use:
```
npm install
npm run build
```
### publishing
First build the package than run ```npm publish```
### consuming
navigate to the folder of your consuming project and run one of next commando's.
_published:_
```
npm install {{npmName}}@{{npmVersion}} --save
```
_unPublished (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE --save
```
_using `npm link`:_
In PATH_TO_GENERATED_PACKAGE:
```
npm link
```
In your project:
```
npm link {{npmName}}@{{npmVersion}}
```
## Requirements
Services require a `IHttpClient` and a `IApiConfiguration`. The `IHttpClient` is necessary to manage http's call and with the `IApiConfiguration` you can provide settings for the Authentication.
For the sake of simplicity an implementation of `IHttpClient` is already provided, but if you want you can override it.
For these reasons you have to manually bind these two services:
```typescript
let container = new Container();
container.bind<IHttpClient>("IApiHttpClient").to(HttpClient).inSingletonScope();
container.bind<IApiConfiguration>("IApiConfiguration").to(ApiConfiguration).inSingletonScope();
```
## Services Binding
To bind all the generated services you can use `ApiServiceBinder`.
```typescript
ApiServiceBinder.with(container);
```
## Final result
```typescript
let container = new Container();
container.bind<IHttpClient>("IApiHttpClient").to(HttpClient).inSingletonScope();
container.bind<IApiConfiguration>("IApiConfiguration").to(ApiConfiguration).inSingletonScope();
ApiServiceBinder.with(container);
```

View File

@ -0,0 +1,180 @@
{{>licenseInfo}}
/* tslint:disable:no-unused-variable member-ordering */
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import IHttpClient from "../IHttpClient";
import { inject, injectable } from "inversify";
import { IAPIConfiguration } from "../IAPIConfiguration";
import { Headers } from "../Headers";
import HttpResponse from "../HttpResponse";
{{#imports}}
import { {{classname}} } from '../{{filename}}';
{{/imports}}
import { COLLECTION_FORMATS } from '../variables';
{{#withInterfaces}}
import { {{classname}}Interface } from './{{classname}}Interface';
{{/withInterfaces}}
{{#operations}}
{{#description}}
/**
* {{&description}}
*/
{{/description}}
@injectable()
{{#withInterfaces}}
export class {{classname}} implements {{classname}}Interface {
{{/withInterfaces}}
{{^withInterfaces}}
export class {{classname}} {
{{/withInterfaces}}
private basePath: string = '{{{basePath}}}';
constructor(@inject("IApiHttpClient") private httpClient: IHttpClient,
@inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) {
if(this.APIConfiguration.basePath)
this.basePath = this.APIConfiguration.basePath;
}
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}}* @param {{paramName}} {{description}}
{{/allParams}}{{#useHttpClient}}* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.{{/useHttpClient}}
*/
public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'body', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>;
public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'response', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}<HttpResponse<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>>;
public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe: any = 'body', headers: Headers = {}): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}<any> {
{{#allParams}}
{{#required}}
if (!{{paramName}}){
throw new Error('Required parameter {{paramName}} was null or undefined when calling {{nickname}}.');
}
{{/required}}
{{/allParams}}
{{#hasQueryParams}}
let queryParameters: string[] = [];
{{#queryParams}}
{{#isListContainer}}
if ({{paramName}}) {
{{#isCollectionFormatMulti}}
{{paramName}}.forEach((element) => {
queryParameters.push("{{paramName}}="+encodeURIComponent(String({{paramName}})));
})
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
queryParameters.push("{{paramName}}="+encodeURIComponent({{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])));
{{/isCollectionFormatMulti}}
}
{{/isListContainer}}
{{^isListContainer}}
if ({{paramName}} !== undefined) {
{{#isDateTime}}
queryParameters.push("{{paramName}}="+encodeURIComponent(<any>{{paramName}}.toISOString()));
{{/isDateTime}}
{{^isDateTime}}
queryParameters.push("{{paramName}}="+encodeURIComponent(String({{paramName}})));
{{/isDateTime}}
}
{{/isListContainer}}
{{/queryParams}}
{{/hasQueryParams}}
{{#headerParams}}
{{#isListContainer}}
if ({{paramName}}) {
headers['{{baseName}}'] = {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}']);
}
{{/isListContainer}}
{{^isListContainer}}
if ({{paramName}}) {
headers['{{baseName}}'] = String({{paramName}});
}
{{/isListContainer}}
{{/headerParams}}
{{#authMethods}}
// authentication ({{name}}) required
{{#isApiKey}}
{{#isKeyInHeader}}
if (this.APIConfiguration.apiKeys["{{keyParamName}}"]) {
headers['{{keyParamName}}'] = this.APIConfiguration.apiKeys["{{keyParamName}}"];
}
{{/isKeyInHeader}}
{{#isKeyInQuery}}
if (this.APIConfiguration.apiKeys["{{keyParamName}}"]) {
queryParameters.push("{{paramName}}="+encodeURIComponent(String(this.APIConfiguration.apiKeys["{{keyParamName}}"])));
}
{{/isKeyInQuery}}
{{/isApiKey}}
{{#isBasic}}
if (this.APIConfiguration.username || this.APIConfiguration.password) {
headers['Authorization'] = btoa(this.APIConfiguration.username + ':' + this.APIConfiguration.password);
}
{{/isBasic}}
{{#isOAuth}}
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
{{/isOAuth}}
{{/authMethods}}
{{^produces}}
headers['Accept'] = 'application/json';
{{/produces}}
{{#produces.0}}
headers['Accept'] = '{{{mediaType}}}';
{{/produces.0}}
{{#bodyParam}}
{{^consumes}}
headers['Content-Type'] = 'application/json';
{{/consumes}}
{{#consumes.0}}
headers['Content-Type'] = '{{{mediaType}}}';
{{/consumes.0}}
{{/bodyParam}}
{{#hasFormParams}}
let formData: FormData = new FormData();
headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
{{#formParams}}
{{#isListContainer}}
if ({{paramName}}) {
{{#isCollectionFormatMulti}}
{{paramName}}.forEach((element) => {
formData.append('{{baseName}}', <any>element);
})
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
formData.append('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}']));
{{/isCollectionFormatMulti}}
}
{{/isListContainer}}
{{^isListContainer}}
if ({{paramName}} !== undefined) {
formData.append('{{baseName}}', <any>{{paramName}});
}
{{/isListContainer}}
{{/formParams}}
{{/hasFormParams}}
const response: Observable<HttpResponse<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>> = this.httpClient.{{httpMethod}}(`${this.basePath}{{{path}}}{{#hasQueryParams}}?${queryParameters.join('&')}{{/hasQueryParams}}`{{#bodyParam}}, {{paramName}} {{/bodyParam}}{{#hasFormParams}}, body{{/hasFormParams}}, headers);
if (observe == 'body') {
return response.map(httpResponse => <{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>(httpResponse.response)){{#usePromise}}.toPromise(){{/usePromise}};
}
return response{{#usePromise}}.toPromise(){{/usePromise}};
}
{{/operation}}}
{{/operations}}

View File

@ -0,0 +1,26 @@
{{>licenseInfo}}
import { Headers } from "../Headers";
import { Observable } from "rxjs/Observable";
import * as models from "../model/models";
import HttpResponse from "../HttpResponse";
{{#operations}}
{{#description}}
/**
* {{&description}}
*/
{{/description}}
export interface {{classname}}Interface {
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}}* @param {{paramName}} {{description}}
{{/allParams}}*/
{{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'body', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>;
{{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe?: 'response', headers?: Headers): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}}<HttpResponse<{{#returnType}}{{{returnType}}}{{#isResponseTypeFile}}|undefined{{/isResponseTypeFile}}{{/returnType}}{{^returnType}}any{{/returnType}}>>;
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1,5 @@
{{#apiInfo}}
{{#apis}}
export * from './{{ classFilename }}';
{{/apis}}
{{/apiInfo}}

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 swagger-petstore-perl "minor update"
git_user_id=$1
git_repo_id=$2
release_note=$3
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://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,6 @@
wwwroot/*.js
node_modules
typings
dist
.vscode
.idea

View File

@ -0,0 +1,7 @@
export * from './api/api';
export * from './model/models';
export * from './variables';
export * from './IAPIConfiguration';
export * from './ApiServiceBinder';
export * from './IHttpClient';
export * from './HttpClient';

View File

@ -0,0 +1,11 @@
/**
* {{{appName}}}
* {{{appDescription}}}
*
* {{#version}}OpenAPI spec version: {{{version}}}{{/version}}
* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/

View File

@ -0,0 +1,16 @@
{{>licenseInfo}}
{{#models}}
{{#model}}
{{#tsImports}}
import { {{classname}} } from './{{filename}}';
{{/tsImports}}
{{#description}}
/**
* {{{description}}}
*/
{{/description}}
{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#isAlias}}{{>modelAlias}}{{/isAlias}}{{^isAlias}}{{#taggedUnions}}{{>modelTaggedUnion}}{{/taggedUnions}}{{^taggedUnions}}{{>modelGeneric}}{{/taggedUnions}}{{/isAlias}}{{/isEnum}}
{{/model}}
{{/models}}

View File

@ -0,0 +1 @@
export type {{classname}} = {{dataType}};

View File

@ -0,0 +1,9 @@
export type {{classname}} = {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}} | {{/-last}}{{/enumVars}}{{/allowableValues}};
export const {{classname}} = {
{{#allowableValues}}
{{#enumVars}}
{{name}}: {{{value}}} as {{classname}}{{^-last}},{{/-last}}
{{/enumVars}}
{{/allowableValues}}
}

View File

@ -0,0 +1,10 @@
export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ {{>modelGenericAdditionalProperties}}
{{#vars}}
{{#description}}
/**
* {{{description}}}
*/
{{/description}}
{{#isReadOnly}}readonly {{/isReadOnly}}{{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}};
{{/vars}}
}{{>modelGenericEnums}}

View File

@ -0,0 +1,5 @@
{{#additionalPropertiesType}}
[key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}};
{{/additionalPropertiesType}}

View File

@ -0,0 +1,16 @@
{{#hasEnums}}
export namespace {{classname}} {
{{#vars}}
{{#isEnum}}
export type {{enumName}} = {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}} | {{/-last}}{{/enumVars}}{{/allowableValues}};
export const {{enumName}} = {
{{#allowableValues}}
{{#enumVars}}
{{name}}: {{{value}}} as {{enumName}}{{^-last}},{{/-last}}
{{/enumVars}}
{{/allowableValues}}
}
{{/isEnum}}
{{/vars}}
}{{/hasEnums}}

View File

@ -0,0 +1,21 @@
{{#discriminator}}
export type {{classname}} = {{#children}}{{^-first}} | {{/-first}}{{classname}}{{/children}};
{{/discriminator}}
{{^discriminator}}
{{#parent}}
export interface {{classname}} { {{>modelGenericAdditionalProperties}}
{{#allVars}}
{{#description}}
/**
* {{{description}}}
*/
{{/description}}
{{name}}{{^required}}?{{/required}}: {{#discriminatorValue}}'{{discriminatorValue}}'{{/discriminatorValue}}{{^discriminatorValue}}{{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}{{/discriminatorValue}};
{{/allVars}}
}
{{>modelGenericEnums}}
{{/parent}}
{{^parent}}
{{>modelGeneric}}
{{/parent}}
{{/discriminator}}

View File

@ -0,0 +1,5 @@
{{#models}}
{{#model}}
export * from './{{{ classFilename }}}';
{{/model}}
{{/models}}

View File

@ -0,0 +1,29 @@
{
"name": "{{{npmName}}}",
"version": "{{{npmVersion}}}",
"description": "swagger client for {{{npmName}}}",
"author": "Swagger Codegen Contributors",
"keywords": [
"swagger-client"
],
"license": "Unlicense",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"scripts": {
"build": "tsc --outDir dist/",
"postinstall": "npm run build"
},
"dependencies": {
"inversify": "^4.3.0",
"rxjs": "~5.5.7",
"whatwg-fetch": "~2.0.1",
"reflect-metadata": "0.1.8"
},
"devDependencies": {
}{{#npmRepository}},{{/npmRepository}}
{{#npmRepository}}
"publishConfig": {
"registry": "{{{npmRepository}}}"
}
{{/npmRepository}}
}

View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true,
"target": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}es5{{/supportsES6}}",
"module": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}commonjs{{/supportsES6}}",
"moduleResolution": "node",
"removeComments": true,
"sourceMap": true,
"outDir": "./dist",
"noLib": false,
"declaration": true,
"lib": [ "es6", "dom" ]
},
"exclude": [
"node_modules",
"dist"
],
"filesGlob": [
"./model/*.ts",
"./api/*.ts"
]
}

View File

@ -0,0 +1,6 @@
export const COLLECTION_FORMATS = {
'csv': ',',
'tsv': ' ',
'ssv': ' ',
'pipes': '|'
}

View File

@ -0,0 +1,50 @@
package io.swagger.codegen.options;
import com.google.common.collect.ImmutableMap;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.languages.TypeScriptAngularClientCodegen;
import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen;
import java.util.Map;
public class TypeScriptInversifyClientOptionsProvider implements OptionsProvider {
public static final String SUPPORTS_ES6_VALUE = "false";
public static final String SORT_PARAMS_VALUE = "false";
public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true";
public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase";
private static final String NMP_NAME = "npmName";
private static final String NMP_VERSION = "1.1.2";
private static final String NPM_REPOSITORY = "https://registry.npmjs.org";
public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false";
public static final String USE_PROMISE = "false";
@Override
public String getLanguage() {
return "typescript-inversify";
}
@Override
public Map<String, String> createOptions() {
ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>();
return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE)
.put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE)
.put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE)
.put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE)
.put(TypeScriptInversifyClientCodegen.NPM_NAME, NMP_NAME)
.put(TypeScriptInversifyClientCodegen.NPM_VERSION, NMP_VERSION)
.put(TypeScriptInversifyClientCodegen.SNAPSHOT, Boolean.FALSE.toString())
.put(TypeScriptInversifyClientCodegen.WITH_INTERFACES, Boolean.FALSE.toString())
.put(TypeScriptInversifyClientCodegen.TAGGED_UNIONS, Boolean.FALSE.toString())
.put(TypeScriptInversifyClientCodegen.USE_PROMISE, Boolean.FALSE.toString())
.put(TypeScriptInversifyClientCodegen.NPM_REPOSITORY, NPM_REPOSITORY)
.put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE)
.build();
}
@Override
public boolean isServer() {
return false;
}
}

View File

@ -0,0 +1,36 @@
package io.swagger.codegen.typescript.typescriptinversify;
import io.swagger.codegen.AbstractOptionsTest;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen;
import io.swagger.codegen.options.TypeScriptInversifyClientOptionsProvider;
import mockit.Expectations;
import mockit.Tested;
public class TypeScriptInversifyClientOptionsTest extends AbstractOptionsTest {
@Tested
private TypeScriptInversifyClientCodegen clientCodegen;
public TypeScriptInversifyClientOptionsTest() {
super(new TypeScriptInversifyClientOptionsProvider());
}
@Override
protected CodegenConfig getCodegenConfig() {
return clientCodegen;
}
@SuppressWarnings("unused")
@Override
protected void setExpectations() {
new Expectations(clientCodegen) {{
clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(TypeScriptInversifyClientOptionsProvider.SORT_PARAMS_VALUE));
times = 1;
clientCodegen.setModelPropertyNaming(TypeScriptInversifyClientOptionsProvider.MODEL_PROPERTY_NAMING_VALUE);
times = 1;
clientCodegen.setSupportsES6(Boolean.valueOf(TypeScriptInversifyClientOptionsProvider.SUPPORTS_ES6_VALUE));
times = 1;
}};
}
}

View File

@ -0,0 +1,198 @@
package io.swagger.codegen.typescript.typescriptinversify;
import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.google.common.collect.Sets;
import io.swagger.codegen.CodegenModel;
import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.models.ArrayModel;
import io.swagger.models.Model;
import io.swagger.models.ModelImpl;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.DateTimeProperty;
import io.swagger.models.properties.DateProperty;
import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
@SuppressWarnings("static-method")
public class TypeScriptInversifyModelTest {
@Test(description = "convert a simple TypeScript Angular model")
public void simpleModelTest() {
final Model model = new ModelImpl()
.description("a sample model")
.property("id", new LongProperty())
.property("name", new StringProperty())
.property("createdAt", new DateTimeProperty())
.property("birthDate", new DateProperty())
.required("id")
.required("name");
final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen();
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 4);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "id");
Assert.assertEquals(property1.datatype, "number");
Assert.assertEquals(property1.name, "id");
Assert.assertEquals(property1.defaultValue, "undefined");
Assert.assertEquals(property1.baseType, "number");
Assert.assertTrue(property1.hasMore);
Assert.assertTrue(property1.required);
Assert.assertTrue(property1.isNotContainer);
final CodegenProperty property2 = cm.vars.get(1);
Assert.assertEquals(property2.baseName, "name");
Assert.assertEquals(property2.datatype, "string");
Assert.assertEquals(property2.name, "name");
Assert.assertEquals(property2.defaultValue, "undefined");
Assert.assertEquals(property2.baseType, "string");
Assert.assertTrue(property2.hasMore);
Assert.assertTrue(property2.required);
Assert.assertTrue(property2.isNotContainer);
final CodegenProperty property3 = cm.vars.get(2);
Assert.assertEquals(property3.baseName, "createdAt");
Assert.assertEquals(property3.complexType, null);
Assert.assertEquals(property3.datatype, "Date");
Assert.assertEquals(property3.name, "createdAt");
Assert.assertEquals(property3.baseType, "Date");
Assert.assertEquals(property3.defaultValue, "undefined");
Assert.assertTrue(property3.hasMore);
Assert.assertFalse(property3.required);
Assert.assertTrue(property3.isNotContainer);
final CodegenProperty property4 = cm.vars.get(3);
Assert.assertEquals(property4.baseName, "birthDate");
Assert.assertEquals(property4.complexType, null);
Assert.assertEquals(property4.datatype, "string");
Assert.assertEquals(property4.name, "birthDate");
Assert.assertEquals(property4.baseType, "string");
Assert.assertEquals(property4.defaultValue, "undefined");
Assert.assertFalse(property4.hasMore);
Assert.assertFalse(property4.required);
Assert.assertTrue(property4.isNotContainer);
}
@Test(description = "convert a model with list property")
public void listPropertyTest() {
final Model model = new ModelImpl()
.description("a sample model")
.property("id", new LongProperty())
.property("urls", new ArrayProperty().items(new StringProperty()))
.required("id");
final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen();
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 2);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "id");
Assert.assertEquals(property1.datatype, "number");
Assert.assertEquals(property1.name, "id");
Assert.assertEquals(property1.defaultValue, "undefined");
Assert.assertEquals(property1.baseType, "number");
Assert.assertTrue(property1.hasMore);
Assert.assertTrue(property1.required);
Assert.assertTrue(property1.isNotContainer);
final CodegenProperty property2 = cm.vars.get(1);
Assert.assertEquals(property2.baseName, "urls");
Assert.assertEquals(property2.datatype, "Array<string>");
Assert.assertEquals(property2.name, "urls");
Assert.assertEquals(property2.baseType, "Array");
Assert.assertFalse(property2.hasMore);
Assert.assertFalse(property2.required);
Assert.assertTrue(property2.isContainer);
}
@Test(description = "convert a model with complex property")
public void complexPropertyTest() {
final Model model = new ModelImpl()
.description("a sample model")
.property("children", new RefProperty("#/definitions/Children"));
final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen();
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 1);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "children");
Assert.assertEquals(property1.datatype, "Children");
Assert.assertEquals(property1.name, "children");
Assert.assertEquals(property1.defaultValue, "undefined");
Assert.assertEquals(property1.baseType, "Children");
Assert.assertFalse(property1.required);
Assert.assertTrue(property1.isNotContainer);
}
@Test(description = "convert a model with complex list property")
public void complexListPropertyTest() {
final Model model = new ModelImpl()
.description("a sample model")
.property("children", new ArrayProperty()
.items(new RefProperty("#/definitions/Children")));
final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen();
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 1);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "children");
Assert.assertEquals(property1.complexType, "Children");
Assert.assertEquals(property1.datatype, "Array<Children>");
Assert.assertEquals(property1.name, "children");
Assert.assertEquals(property1.baseType, "Array");
Assert.assertFalse(property1.required);
Assert.assertTrue(property1.isContainer);
}
@Test(description = "convert an array model")
public void arrayModelTest() {
final Model model = new ArrayModel()
.description("an array model")
.items(new RefProperty("#/definitions/Children"));
final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen();
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "an array model");
Assert.assertEquals(cm.vars.size(), 0);
}
@Test(description = "convert a map model")
public void mapModelTest() {
final Model model = new ModelImpl()
.description("a map model")
.additionalProperties(new RefProperty("#/definitions/Children"));
final DefaultCodegen codegen = new TypeScriptInversifyClientCodegen();
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a map model");
Assert.assertEquals(cm.vars.size(), 0);
Assert.assertEquals(cm.imports.size(), 1);
Assert.assertEquals(cm.additionalPropertiesType, "Children");
Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1);
}
}

View File

@ -0,0 +1,32 @@
package io.swagger.codegen.typescript.typescriptinversify;
import java.util.HashMap;
import java.util.Map;
import io.swagger.codegen.AbstractIntegrationTest;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen;
import io.swagger.codegen.testutils.IntegrationTestPathsConfig;
public class TypescriptInversifyAdditionalPropertiesIntegrationTest extends AbstractIntegrationTest {
@Override
protected CodegenConfig getCodegenConfig() {
return new TypeScriptInversifyClientCodegen();
}
@Override
protected Map<String, String> configProperties() {
Map<String, String> properties = new HashMap<>();
properties.put("npmName", "additionalPropertiesTest");
properties.put("npmVersion", "1.0.2");
properties.put("snapshot", "false");
return properties;
}
@Override
protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() {
return new IntegrationTestPathsConfig("typescript/additional-properties");
}
}

View File

@ -0,0 +1,32 @@
package io.swagger.codegen.typescript.typescriptinversify;
import java.util.HashMap;
import java.util.Map;
import io.swagger.codegen.AbstractIntegrationTest;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen;
import io.swagger.codegen.testutils.IntegrationTestPathsConfig;
public class TypescriptInversifyArrayAndObjectIntegrationTest extends AbstractIntegrationTest {
@Override
protected CodegenConfig getCodegenConfig() {
return new TypeScriptInversifyClientCodegen();
}
@Override
protected Map<String, String> configProperties() {
Map<String, String> properties = new HashMap<>();
properties.put("npmName", "arrayAndAnyTest");
properties.put("npmVersion", "1.0.2");
properties.put("snapshot", "false");
return properties;
}
@Override
protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() {
return new IntegrationTestPathsConfig("typescript/array-and-object");
}
}

View File

@ -0,0 +1,33 @@
package io.swagger.codegen.typescript.typescriptinversify;
import java.util.HashMap;
import java.util.Map;
import io.swagger.codegen.AbstractIntegrationTest;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.languages.TypeScriptInversifyClientCodegen;
import io.swagger.codegen.testutils.IntegrationTestPathsConfig;
public class TypescriptInversifyPestoreIntegrationTest extends AbstractIntegrationTest {
@Override
protected CodegenConfig getCodegenConfig() {
return new TypeScriptInversifyClientCodegen();
}
@Override
protected Map<String, String> configProperties() {
Map<String, String> properties = new HashMap<>();
properties.put("npmName", "petstore-integration-test");
properties.put("npmVersion", "1.0.3");
properties.put("snapshot", "false");
properties.put("usePromise", "false");
return properties;
}
@Override
protected IntegrationTestPathsConfig getIntegrationTestPathsConfig() {
return new IntegrationTestPathsConfig("typescript/petstore");
}
}

View File

@ -11,7 +11,7 @@ docker run --rm -it \
-w /gen \
-e GEN_DIR=/gen \
-e MAVEN_CONFIG=/var/maven/.m2 \
-u "$(id -u):$(id -g)" \
-u "$(id -u):$(id -g)" \
-v "${PWD}:/gen" \
-v "${maven_cache_repo}:/var/maven/.m2/repository" \
--entrypoint /gen/docker-entrypoint.sh \

View File

@ -0,0 +1,23 @@
# Swagger Codegen Ignore
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
# 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 Swagger Codgen 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,9 @@
import {interfaces} from "inversify";
import { FakeService } from './api/fake.service';
export class ApiServiceBinder {
public static with(container: interfaces.Container) {
container.bind<FakeService>("FakeService").to(FakeService).inSingletonScope();
}
}

View File

@ -0,0 +1,3 @@
export interface Headers {
[index:string]: string
}

View File

@ -0,0 +1,63 @@
import IHttpClient from "./IHttpClient";
import { Observable } from "rxjs/Observable";
import "whatwg-fetch";
import HttpResponse from "./HttpResponse";
import {injectable} from "inversify";
import "rxjs/add/observable/fromPromise";
import { Headers } from "./Headers";
@injectable()
class HttpClient implements IHttpClient {
get(url:string, headers?: Headers):Observable<HttpResponse> {
return this.performNetworkCall(url, "get", undefined, headers);
}
post(url: string, body: {}|FormData, headers?: Headers): Observable<HttpResponse> {
return this.performNetworkCall(url, "post", this.getJsonBody(body), this.addJsonHeaders(headers));
}
put(url: string, body: {}, headers?: Headers): Observable<HttpResponse> {
return this.performNetworkCall(url, "put", this.getJsonBody(body), this.addJsonHeaders(headers));
}
delete(url: string, headers?: Headers): Observable<HttpResponse> {
return this.performNetworkCall(url, "delete", undefined, headers);
}
private getJsonBody(body: {}|FormData) {
return !(body instanceof FormData) ? JSON.stringify(body) : body;
}
private addJsonHeaders(headers: Headers) {
return Object.assign({}, {
"Accept": "application/json",
"Content-Type": "application/json"
}, headers);
};
private performNetworkCall(url: string, method: string, body?: any, headers?: Headers): Observable<HttpResponse> {
let promise = window.fetch(url, {
method: method,
body: body,
headers: <any>headers
}).then(response => {
let headers: Headers = {};
response.headers.forEach((value, name) => {
headers[name.toString().toLowerCase()] = value;
});
return response.text().then(text => {
let contentType = headers["content-type"] || "";
let payload = contentType.match("application/json") ? JSON.parse(text) : text;
let httpResponse = new HttpResponse(payload, response.status, headers);
if (response.status >= 400)
throw httpResponse;
return httpResponse;
});
});
return Observable.fromPromise(promise);
}
}
export default HttpClient

View File

@ -0,0 +1,8 @@
import { Headers } from "./Headers"
class HttpResponse<T = any> {
constructor(public response: T, public status:number, public headers?: Headers) {
}
}
export default HttpResponse

View File

@ -0,0 +1,8 @@
export interface IAPIConfiguration {
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
}

View File

@ -0,0 +1,12 @@
import { Observable } from "rxjs/Observable";
import HttpResponse from "./HttpResponse";
import { Headers } from "./Headers";
interface IHttpClient {
get(url:string, headers?: Headers):Observable<HttpResponse>
post(url:string, body:{}|FormData, headers?: Headers):Observable<HttpResponse>
put(url:string, body:{}, headers?: Headers):Observable<HttpResponse>
delete(url:string, headers?: Headers):Observable<HttpResponse>
}
export default IHttpClient

View File

@ -0,0 +1,62 @@
/**
* Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end --
*
* OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r
* Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import IHttpClient from "../IHttpClient";
import { inject, injectable } from "inversify";
import { IAPIConfiguration } from "../IAPIConfiguration";
import { Headers } from "../Headers";
import HttpResponse from "../HttpResponse";
import { COLLECTION_FORMATS } from '../variables';
@injectable()
export class FakeService {
private basePath: string = 'https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r';
constructor(@inject("IApiHttpClient") private httpClient: IHttpClient,
@inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) {
if(this.APIConfiguration.basePath)
this.basePath = this.APIConfiguration.basePath;
}
/**
* To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r
*
* @param testCodeInjectEndRnNR To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r
*/
public testCodeInjectEndRnNR(testCodeInjectEndRnNR?: string, observe?: 'body', headers?: Headers): Observable<any>;
public testCodeInjectEndRnNR(testCodeInjectEndRnNR?: string, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public testCodeInjectEndRnNR(testCodeInjectEndRnNR?: string, observe: any = 'body', headers: Headers = {}): Observable<any> {
headers['Accept'] = 'application/json';
let formData: FormData = new FormData();
headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
if (testCodeInjectEndRnNR !== undefined) {
formData.append('test code inject */ &#39; &quot; &#x3D;end -- \r\n \n \r', <any>testCodeInjectEndRnNR);
}
const response: Observable<HttpResponse<any>> = this.httpClient.put(`${this.basePath}/fake`, body, headers);
if (observe == 'body') {
return response.map(httpResponse => <any>(httpResponse.response));
}
return response;
}
}

View File

@ -0,0 +1,22 @@
/**
* Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end --
*
* OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r
* Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/**
* Model for testing reserved words *_/ ' \" =end -- \\r\\n \\n \\r
*/
export interface ModelReturn {
/**
* property description *_/ ' \" =end -- \\r\\n \\n \\r
*/
_return?: number;
}

View File

@ -0,0 +1,6 @@
export const COLLECTION_FORMATS = {
'csv': ',',
'tsv': ' ',
'ssv': ' ',
'pipes': '|'
}

View File

@ -0,0 +1,23 @@
# Swagger Codegen Ignore
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
# 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 Swagger Codgen 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 @@
2.4.0-SNAPSHOT

View File

@ -0,0 +1,13 @@
import {interfaces} from "inversify";
import { PetService } from './api/pet.service';
import { StoreService } from './api/store.service';
import { UserService } from './api/user.service';
export class ApiServiceBinder {
public static with(container: interfaces.Container) {
container.bind<PetService>("PetService").to(PetService).inSingletonScope();
container.bind<StoreService>("StoreService").to(StoreService).inSingletonScope();
container.bind<UserService>("UserService").to(UserService).inSingletonScope();
}
}

View File

@ -0,0 +1,3 @@
export interface Headers {
[index:string]: string
}

View File

@ -0,0 +1,63 @@
import IHttpClient from "./IHttpClient";
import { Observable } from "rxjs/Observable";
import "whatwg-fetch";
import HttpResponse from "./HttpResponse";
import {injectable} from "inversify";
import "rxjs/add/observable/fromPromise";
import { Headers } from "./Headers";
@injectable()
class HttpClient implements IHttpClient {
get(url:string, headers?: Headers):Observable<HttpResponse> {
return this.performNetworkCall(url, "get", undefined, headers);
}
post(url: string, body: {}|FormData, headers?: Headers): Observable<HttpResponse> {
return this.performNetworkCall(url, "post", this.getJsonBody(body), this.addJsonHeaders(headers));
}
put(url: string, body: {}, headers?: Headers): Observable<HttpResponse> {
return this.performNetworkCall(url, "put", this.getJsonBody(body), this.addJsonHeaders(headers));
}
delete(url: string, headers?: Headers): Observable<HttpResponse> {
return this.performNetworkCall(url, "delete", undefined, headers);
}
private getJsonBody(body: {}|FormData) {
return !(body instanceof FormData) ? JSON.stringify(body) : body;
}
private addJsonHeaders(headers: Headers) {
return Object.assign({}, {
"Accept": "application/json",
"Content-Type": "application/json"
}, headers);
};
private performNetworkCall(url: string, method: string, body?: any, headers?: Headers): Observable<HttpResponse> {
let promise = window.fetch(url, {
method: method,
body: body,
headers: <any>headers
}).then(response => {
let headers: Headers = {};
response.headers.forEach((value, name) => {
headers[name.toString().toLowerCase()] = value;
});
return response.text().then(text => {
let contentType = headers["content-type"] || "";
let payload = contentType.match("application/json") ? JSON.parse(text) : text;
let httpResponse = new HttpResponse(payload, response.status, headers);
if (response.status >= 400)
throw httpResponse;
return httpResponse;
});
});
return Observable.fromPromise(promise);
}
}
export default HttpClient

View File

@ -0,0 +1,8 @@
import { Headers } from "./Headers"
class HttpResponse<T = any> {
constructor(public response: T, public status:number, public headers?: Headers) {
}
}
export default HttpResponse

View File

@ -0,0 +1,8 @@
export interface IAPIConfiguration {
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
}

View File

@ -0,0 +1,12 @@
import { Observable } from "rxjs/Observable";
import HttpResponse from "./HttpResponse";
import { Headers } from "./Headers";
interface IHttpClient {
get(url:string, headers?: Headers):Observable<HttpResponse>
post(url:string, body:{}|FormData, headers?: Headers):Observable<HttpResponse>
put(url:string, body:{}, headers?: Headers):Observable<HttpResponse>
delete(url:string, headers?: Headers):Observable<HttpResponse>
}
export default IHttpClient

View File

@ -0,0 +1,315 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import IHttpClient from "../IHttpClient";
import { inject, injectable } from "inversify";
import { IAPIConfiguration } from "../IAPIConfiguration";
import { Headers } from "../Headers";
import HttpResponse from "../HttpResponse";
import { ApiResponse } from '../model/apiResponse';
import { Pet } from '../model/pet';
import { COLLECTION_FORMATS } from '../variables';
@injectable()
export class PetService {
private basePath: string = 'http://petstore.swagger.io/v2';
constructor(@inject("IApiHttpClient") private httpClient: IHttpClient,
@inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) {
if(this.APIConfiguration.basePath)
this.basePath = this.APIConfiguration.basePath;
}
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
*/
public addPet(body: Pet, observe?: 'body', headers?: Headers): Observable<any>;
public addPet(body: Pet, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public addPet(body: Pet, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!body){
throw new Error('Required parameter body was null or undefined when calling addPet.');
}
// authentication (petstore_auth) required
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
headers['Accept'] = 'application/xml';
headers['Content-Type'] = 'application/json';
const response: Observable<HttpResponse<any>> = this.httpClient.post(`${this.basePath}/pet`, body , headers);
if (observe == 'body') {
return response.map(httpResponse => <any>(httpResponse.response));
}
return response;
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
*/
public deletePet(petId: number, apiKey?: string, observe?: 'body', headers?: Headers): Observable<any>;
public deletePet(petId: number, apiKey?: string, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public deletePet(petId: number, apiKey?: string, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!petId){
throw new Error('Required parameter petId was null or undefined when calling deletePet.');
}
if (apiKey) {
headers['api_key'] = String(apiKey);
}
// authentication (petstore_auth) required
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
headers['Accept'] = 'application/xml';
const response: Observable<HttpResponse<any>> = this.httpClient.delete(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, headers);
if (observe == 'body') {
return response.map(httpResponse => <any>(httpResponse.response));
}
return response;
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma separated strings
* @param status Status values that need to be considered for filter
*/
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', headers?: Headers): Observable<Array<Pet>>;
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', headers?: Headers): Observable<HttpResponse<Array<Pet>>>;
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!status){
throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.');
}
let queryParameters: string[] = [];
if (status) {
queryParameters.push("status="+encodeURIComponent(status.join(COLLECTION_FORMATS['csv'])));
}
// authentication (petstore_auth) required
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
headers['Accept'] = 'application/xml';
const response: Observable<HttpResponse<Array<Pet>>> = this.httpClient.get(`${this.basePath}/pet/findByStatus?${queryParameters.join('&')}`, headers);
if (observe == 'body') {
return response.map(httpResponse => <Array<Pet>>(httpResponse.response));
}
return response;
}
/**
* Finds Pets by tags
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by
*/
public findPetsByTags(tags: Array<string>, observe?: 'body', headers?: Headers): Observable<Array<Pet>>;
public findPetsByTags(tags: Array<string>, observe?: 'response', headers?: Headers): Observable<HttpResponse<Array<Pet>>>;
public findPetsByTags(tags: Array<string>, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!tags){
throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.');
}
let queryParameters: string[] = [];
if (tags) {
queryParameters.push("tags="+encodeURIComponent(tags.join(COLLECTION_FORMATS['csv'])));
}
// authentication (petstore_auth) required
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
headers['Accept'] = 'application/xml';
const response: Observable<HttpResponse<Array<Pet>>> = this.httpClient.get(`${this.basePath}/pet/findByTags?${queryParameters.join('&')}`, headers);
if (observe == 'body') {
return response.map(httpResponse => <Array<Pet>>(httpResponse.response));
}
return response;
}
/**
* Find pet by ID
* Returns a single pet
* @param petId ID of pet to return
*/
public getPetById(petId: number, observe?: 'body', headers?: Headers): Observable<Pet>;
public getPetById(petId: number, observe?: 'response', headers?: Headers): Observable<HttpResponse<Pet>>;
public getPetById(petId: number, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!petId){
throw new Error('Required parameter petId was null or undefined when calling getPetById.');
}
// authentication (api_key) required
if (this.APIConfiguration.apiKeys["api_key"]) {
headers['api_key'] = this.APIConfiguration.apiKeys["api_key"];
}
headers['Accept'] = 'application/xml';
const response: Observable<HttpResponse<Pet>> = this.httpClient.get(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, headers);
if (observe == 'body') {
return response.map(httpResponse => <Pet>(httpResponse.response));
}
return response;
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
*/
public updatePet(body: Pet, observe?: 'body', headers?: Headers): Observable<any>;
public updatePet(body: Pet, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public updatePet(body: Pet, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!body){
throw new Error('Required parameter body was null or undefined when calling updatePet.');
}
// authentication (petstore_auth) required
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
headers['Accept'] = 'application/xml';
headers['Content-Type'] = 'application/json';
const response: Observable<HttpResponse<any>> = this.httpClient.put(`${this.basePath}/pet`, body , headers);
if (observe == 'body') {
return response.map(httpResponse => <any>(httpResponse.response));
}
return response;
}
/**
* Updates a pet in the store with form data
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
*/
public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', headers?: Headers): Observable<any>;
public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!petId){
throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.');
}
// authentication (petstore_auth) required
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
headers['Accept'] = 'application/xml';
let formData: FormData = new FormData();
headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
if (name !== undefined) {
formData.append('name', <any>name);
}
if (status !== undefined) {
formData.append('status', <any>status);
}
const response: Observable<HttpResponse<any>> = this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, body, headers);
if (observe == 'body') {
return response.map(httpResponse => <any>(httpResponse.response));
}
return response;
}
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', headers?: Headers): Observable<ApiResponse>;
public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', headers?: Headers): Observable<HttpResponse<ApiResponse>>;
public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!petId){
throw new Error('Required parameter petId was null or undefined when calling uploadFile.');
}
// authentication (petstore_auth) required
if (this.APIConfiguration.accessToken) {
let accessToken = typeof this.APIConfiguration.accessToken === 'function'
? this.APIConfiguration.accessToken()
: this.APIConfiguration.accessToken;
headers['Authorization'] = 'Bearer ' + accessToken;
}
headers['Accept'] = 'application/json';
let formData: FormData = new FormData();
headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
if (additionalMetadata !== undefined) {
formData.append('additionalMetadata', <any>additionalMetadata);
}
if (file !== undefined) {
formData.append('file', <any>file);
}
const response: Observable<HttpResponse<ApiResponse>> = this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, body, headers);
if (observe == 'body') {
return response.map(httpResponse => <ApiResponse>(httpResponse.response));
}
return response;
}
}

View File

@ -0,0 +1,130 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import IHttpClient from "../IHttpClient";
import { inject, injectable } from "inversify";
import { IAPIConfiguration } from "../IAPIConfiguration";
import { Headers } from "../Headers";
import HttpResponse from "../HttpResponse";
import { Order } from '../model/order';
import { COLLECTION_FORMATS } from '../variables';
@injectable()
export class StoreService {
private basePath: string = 'http://petstore.swagger.io/v2';
constructor(@inject("IApiHttpClient") private httpClient: IHttpClient,
@inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) {
if(this.APIConfiguration.basePath)
this.basePath = this.APIConfiguration.basePath;
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted
*/
public deleteOrder(orderId: string, observe?: 'body', headers?: Headers): Observable<any>;
public deleteOrder(orderId: string, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public deleteOrder(orderId: string, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!orderId){
throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.');
}
headers['Accept'] = 'application/xml';
const response: Observable<HttpResponse<any>> = this.httpClient.delete(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, headers);
if (observe == 'body') {
return response.map(httpResponse => <any>(httpResponse.response));
}
return response;
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*/
public getInventory(observe?: 'body', headers?: Headers): Observable<{ [key: string]: number; }>;
public getInventory(observe?: 'response', headers?: Headers): Observable<HttpResponse<{ [key: string]: number; }>>;
public getInventory(observe: any = 'body', headers: Headers = {}): Observable<any> {
// authentication (api_key) required
if (this.APIConfiguration.apiKeys["api_key"]) {
headers['api_key'] = this.APIConfiguration.apiKeys["api_key"];
}
headers['Accept'] = 'application/json';
const response: Observable<HttpResponse<{ [key: string]: number; }>> = this.httpClient.get(`${this.basePath}/store/inventory`, headers);
if (observe == 'body') {
return response.map(httpResponse => <{ [key: string]: number; }>(httpResponse.response));
}
return response;
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
*/
public getOrderById(orderId: number, observe?: 'body', headers?: Headers): Observable<Order>;
public getOrderById(orderId: number, observe?: 'response', headers?: Headers): Observable<HttpResponse<Order>>;
public getOrderById(orderId: number, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!orderId){
throw new Error('Required parameter orderId was null or undefined when calling getOrderById.');
}
headers['Accept'] = 'application/xml';
const response: Observable<HttpResponse<Order>> = this.httpClient.get(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, headers);
if (observe == 'body') {
return response.map(httpResponse => <Order>(httpResponse.response));
}
return response;
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
*/
public placeOrder(body: Order, observe?: 'body', headers?: Headers): Observable<Order>;
public placeOrder(body: Order, observe?: 'response', headers?: Headers): Observable<HttpResponse<Order>>;
public placeOrder(body: Order, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!body){
throw new Error('Required parameter body was null or undefined when calling placeOrder.');
}
headers['Accept'] = 'application/xml';
headers['Content-Type'] = 'application/json';
const response: Observable<HttpResponse<Order>> = this.httpClient.post(`${this.basePath}/store/order`, body , headers);
if (observe == 'body') {
return response.map(httpResponse => <Order>(httpResponse.response));
}
return response;
}
}

View File

@ -0,0 +1,239 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import IHttpClient from "../IHttpClient";
import { inject, injectable } from "inversify";
import { IAPIConfiguration } from "../IAPIConfiguration";
import { Headers } from "../Headers";
import HttpResponse from "../HttpResponse";
import { User } from '../model/user';
import { COLLECTION_FORMATS } from '../variables';
@injectable()
export class UserService {
private basePath: string = 'http://petstore.swagger.io/v2';
constructor(@inject("IApiHttpClient") private httpClient: IHttpClient,
@inject("IAPIConfiguration") private APIConfiguration: IAPIConfiguration ) {
if(this.APIConfiguration.basePath)
this.basePath = this.APIConfiguration.basePath;
}
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
*/
public createUser(body: User, observe?: 'body', headers?: Headers): Observable<any>;
public createUser(body: User, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public createUser(body: User, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!body){
throw new Error('Required parameter body was null or undefined when calling createUser.');
}
headers['Accept'] = 'application/xml';
headers['Content-Type'] = 'application/json';
const response: Observable<HttpResponse<any>> = this.httpClient.post(`${this.basePath}/user`, body , headers);
if (observe == 'body') {
return response.map(httpResponse => <any>(httpResponse.response));
}
return response;
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
public createUsersWithArrayInput(body: Array<User>, observe?: 'body', headers?: Headers): Observable<any>;
public createUsersWithArrayInput(body: Array<User>, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public createUsersWithArrayInput(body: Array<User>, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!body){
throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.');
}
headers['Accept'] = 'application/xml';
headers['Content-Type'] = 'application/json';
const response: Observable<HttpResponse<any>> = this.httpClient.post(`${this.basePath}/user/createWithArray`, body , headers);
if (observe == 'body') {
return response.map(httpResponse => <any>(httpResponse.response));
}
return response;
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
public createUsersWithListInput(body: Array<User>, observe?: 'body', headers?: Headers): Observable<any>;
public createUsersWithListInput(body: Array<User>, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public createUsersWithListInput(body: Array<User>, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!body){
throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.');
}
headers['Accept'] = 'application/xml';
headers['Content-Type'] = 'application/json';
const response: Observable<HttpResponse<any>> = this.httpClient.post(`${this.basePath}/user/createWithList`, body , headers);
if (observe == 'body') {
return response.map(httpResponse => <any>(httpResponse.response));
}
return response;
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
*/
public deleteUser(username: string, observe?: 'body', headers?: Headers): Observable<any>;
public deleteUser(username: string, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public deleteUser(username: string, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!username){
throw new Error('Required parameter username was null or undefined when calling deleteUser.');
}
headers['Accept'] = 'application/xml';
const response: Observable<HttpResponse<any>> = this.httpClient.delete(`${this.basePath}/user/${encodeURIComponent(String(username))}`, headers);
if (observe == 'body') {
return response.map(httpResponse => <any>(httpResponse.response));
}
return response;
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
*/
public getUserByName(username: string, observe?: 'body', headers?: Headers): Observable<User>;
public getUserByName(username: string, observe?: 'response', headers?: Headers): Observable<HttpResponse<User>>;
public getUserByName(username: string, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!username){
throw new Error('Required parameter username was null or undefined when calling getUserByName.');
}
headers['Accept'] = 'application/xml';
const response: Observable<HttpResponse<User>> = this.httpClient.get(`${this.basePath}/user/${encodeURIComponent(String(username))}`, headers);
if (observe == 'body') {
return response.map(httpResponse => <User>(httpResponse.response));
}
return response;
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
*/
public loginUser(username: string, password: string, observe?: 'body', headers?: Headers): Observable<string>;
public loginUser(username: string, password: string, observe?: 'response', headers?: Headers): Observable<HttpResponse<string>>;
public loginUser(username: string, password: string, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!username){
throw new Error('Required parameter username was null or undefined when calling loginUser.');
}
if (!password){
throw new Error('Required parameter password was null or undefined when calling loginUser.');
}
let queryParameters: string[] = [];
if (username !== undefined) {
queryParameters.push("username="+encodeURIComponent(String(username)));
}
if (password !== undefined) {
queryParameters.push("password="+encodeURIComponent(String(password)));
}
headers['Accept'] = 'application/xml';
const response: Observable<HttpResponse<string>> = this.httpClient.get(`${this.basePath}/user/login?${queryParameters.join('&')}`, headers);
if (observe == 'body') {
return response.map(httpResponse => <string>(httpResponse.response));
}
return response;
}
/**
* Logs out current logged in user session
*
*/
public logoutUser(observe?: 'body', headers?: Headers): Observable<any>;
public logoutUser(observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public logoutUser(observe: any = 'body', headers: Headers = {}): Observable<any> {
headers['Accept'] = 'application/xml';
const response: Observable<HttpResponse<any>> = this.httpClient.get(`${this.basePath}/user/logout`, headers);
if (observe == 'body') {
return response.map(httpResponse => <any>(httpResponse.response));
}
return response;
}
/**
* Updated user
* This can only be done by the logged in user.
* @param username name that need to be deleted
* @param body Updated user object
*/
public updateUser(username: string, body: User, observe?: 'body', headers?: Headers): Observable<any>;
public updateUser(username: string, body: User, observe?: 'response', headers?: Headers): Observable<HttpResponse<any>>;
public updateUser(username: string, body: User, observe: any = 'body', headers: Headers = {}): Observable<any> {
if (!username){
throw new Error('Required parameter username was null or undefined when calling updateUser.');
}
if (!body){
throw new Error('Required parameter body was null or undefined when calling updateUser.');
}
headers['Accept'] = 'application/xml';
headers['Content-Type'] = 'application/json';
const response: Observable<HttpResponse<any>> = this.httpClient.put(`${this.basePath}/user/${encodeURIComponent(String(username))}`, body , headers);
if (observe == 'body') {
return response.map(httpResponse => <any>(httpResponse.response));
}
return response;
}
}

View File

@ -0,0 +1,21 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/**
* Describes the result of uploading an image resource
*/
export interface ApiResponse {
code?: number;
type?: string;
message?: string;
}

View File

@ -0,0 +1,20 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/**
* A category for a pet
*/
export interface Category {
id?: number;
name?: string;
}

View File

@ -0,0 +1,35 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/**
* An order for a pets from the pet store
*/
export interface Order {
id?: number;
petId?: number;
quantity?: number;
shipDate?: Date;
/**
* Order Status
*/
status?: Order.StatusEnum;
complete?: boolean;
}
export namespace Order {
export type StatusEnum = 'placed' | 'approved' | 'delivered';
export const StatusEnum = {
Placed: 'placed' as StatusEnum,
Approved: 'approved' as StatusEnum,
Delivered: 'delivered' as StatusEnum
}
}

View File

@ -0,0 +1,37 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
import { Category } from './category';
import { Tag } from './tag';
/**
* A pet for sale in the pet store
*/
export interface Pet {
id?: number;
category?: Category;
name: string;
photoUrls: Array<string>;
tags?: Array<Tag>;
/**
* pet status in the store
*/
status?: Pet.StatusEnum;
}
export namespace Pet {
export type StatusEnum = 'available' | 'pending' | 'sold';
export const StatusEnum = {
Available: 'available' as StatusEnum,
Pending: 'pending' as StatusEnum,
Sold: 'sold' as StatusEnum
}
}

View File

@ -0,0 +1,20 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/**
* A tag for a pet
*/
export interface Tag {
id?: number;
name?: string;
}

View File

@ -0,0 +1,29 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/**
* A User who is purchasing from the pet store
*/
export interface User {
id?: number;
username?: string;
firstName?: string;
lastName?: string;
email?: string;
password?: string;
phone?: string;
/**
* User Status
*/
userStatus?: number;
}

View File

@ -0,0 +1,6 @@
export const COLLECTION_FORMATS = {
'csv': ',',
'tsv': ' ',
'ssv': ' ',
'pipes': '|'
}