diff --git a/bin/security/typescript-inversify.sh b/bin/security/typescript-inversify.sh new file mode 100755 index 00000000000..0dcb407c41f --- /dev/null +++ b/bin/security/typescript-inversify.sh @@ -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 diff --git a/bin/typescript-inversify-petstore.sh b/bin/typescript-inversify-petstore.sh new file mode 100755 index 00000000000..9d8f439d8f7 --- /dev/null +++ b/bin/typescript-inversify-petstore.sh @@ -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 diff --git a/bin/windows/typescript-inversify-petstore.bat b/bin/windows/typescript-inversify-petstore.bat new file mode 100644 index 00000000000..0e677041ecb --- /dev/null +++ b/bin/windows/typescript-inversify-petstore.bat @@ -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% diff --git a/bin/windows/typescript-inversify.bat b/bin/windows/typescript-inversify.bat new file mode 100755 index 00000000000..10ff5c02b6c --- /dev/null +++ b/bin/windows/typescript-inversify.bat @@ -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% diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptInversifyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptInversifyClientCodegen.java new file mode 100644 index 00000000000..56c224c0649 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptInversifyClientCodegen.java @@ -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 postProcessOperations(Map operations) { + Map objs = (Map) operations.get("operations"); + + // Add filename information for api imports + objs.put("apiFilename", getApiFilenameFromClassname(objs.get("classname").toString())); + + List ops = (List) 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> imports = (List>) operations.get("imports"); + for (Map im : imports) { + im.put("filename", im.get("import")); + im.put("classname", getModelnameFromModelFilename(im.get("filename").toString())); + } + + return operations; + } + + @Override + public Map postProcessModels(Map objs) { + Map result = super.postProcessModels(objs); + + return postProcessModelsEnum(result); + } + + @Override + public Map postProcessAllModels(Map objs) { + Map result = super.postProcessAllModels(objs); + + for (Map.Entry entry : result.entrySet()) { + Map inner = (Map) entry.getValue(); + List> models = (List>) inner.get("models"); + for (Map 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> toTsImports(CodegenModel cm, Set imports) { + List> tsImports = new ArrayList<>(); + for (String im : imports) { + if (!im.equals(cm.classname)) { + HashMap 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); + } + +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index b14bc875b5b..50b27709411 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -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 diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/ApiServiceBinder.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/ApiServiceBinder.mustache new file mode 100644 index 00000000000..0026933c69c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/ApiServiceBinder.mustache @@ -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}} + } +} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/Headers.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/Headers.mustache new file mode 100644 index 00000000000..0fa7760e01e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/Headers.mustache @@ -0,0 +1,3 @@ +export interface Headers { + [index:string]: string +} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpClient.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpClient.mustache new file mode 100644 index 00000000000..64fe12a3045 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpClient.mustache @@ -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 { + return this.performNetworkCall(url, "get", undefined, headers); + } + + post(url: string, body: {}|FormData, headers?: Headers): Observable { + return this.performNetworkCall(url, "post", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + put(url: string, body: {}, headers?: Headers): Observable { + return this.performNetworkCall(url, "put", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + delete(url: string, headers?: Headers): Observable { + 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 { + let promise = window.fetch(url, { + method: method, + body: body, + headers: 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 \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpResponse.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpResponse.mustache new file mode 100644 index 00000000000..411240cde2b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/HttpResponse.mustache @@ -0,0 +1,8 @@ +import { Headers } from "./Headers" + +class HttpResponse { + constructor(public response: T, public status:number, public headers?: Headers) { + } +} + +export default HttpResponse \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/IAPIConfiguration.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/IAPIConfiguration.mustache new file mode 100644 index 00000000000..2364e83e6cb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/IAPIConfiguration.mustache @@ -0,0 +1,8 @@ +export interface IAPIConfiguration { + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/IHttpClient.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/IHttpClient.mustache new file mode 100644 index 00000000000..22d9e07c903 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/IHttpClient.mustache @@ -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 + post(url:string, body:{}|FormData, headers?: Headers):Observable + put(url:string, body:{}, headers?: Headers):Observable + delete(url:string, headers?: Headers):Observable +} + +export default IHttpClient \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/README.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/README.mustache new file mode 100644 index 00000000000..4da4e854d96 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/README.mustache @@ -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("IApiHttpClient").to(HttpClient).inSingletonScope(); +container.bind("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("IApiHttpClient").to(HttpClient).inSingletonScope(); +container.bind("IApiConfiguration").to(ApiConfiguration).inSingletonScope(); +ApiServiceBinder.with(container); +``` + + + + + diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/api.service.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/api.service.mustache new file mode 100644 index 00000000000..25958375576 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/api.service.mustache @@ -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}}>; + public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}observe: any = 'body', headers: Headers = {}): {{#usePromise}}Promise{{/usePromise}}{{^usePromise}}Observable{{/usePromise}} { +{{#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({{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}}', element); + }) + {{/isCollectionFormatMulti}} + {{^isCollectionFormatMulti}} + formData.append('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])); + {{/isCollectionFormatMulti}} + } + {{/isListContainer}} + {{^isListContainer}} + if ({{paramName}} !== undefined) { + formData.append('{{baseName}}', {{paramName}}); + } + {{/isListContainer}} +{{/formParams}} + +{{/hasFormParams}} + const response: Observable> = 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}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/apiInterface.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/apiInterface.mustache new file mode 100644 index 00000000000..cb31c6396b9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/apiInterface.mustache @@ -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}}>; +{{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/apis.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/apis.mustache new file mode 100644 index 00000000000..3d49b9488b4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/apis.mustache @@ -0,0 +1,5 @@ +{{#apiInfo}} +{{#apis}} +export * from './{{ classFilename }}'; +{{/apis}} +{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/git_push.sh.mustache new file mode 100755 index 00000000000..a2d75234837 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/git_push.sh.mustache @@ -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' + diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/gitignore b/modules/swagger-codegen/src/main/resources/typescript-inversify/gitignore new file mode 100644 index 00000000000..23c3bdf9c9b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/gitignore @@ -0,0 +1,6 @@ +wwwroot/*.js +node_modules +typings +dist +.vscode +.idea \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/index.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/index.mustache new file mode 100644 index 00000000000..54e1715c1e1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/index.mustache @@ -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'; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/licenseInfo.mustache new file mode 100644 index 00000000000..7d61c4ee055 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/licenseInfo.mustache @@ -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. + */ \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/model.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/model.mustache new file mode 100644 index 00000000000..0b93ad2998f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/model.mustache @@ -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}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelAlias.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelAlias.mustache new file mode 100644 index 00000000000..c1c6bf7a5da --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelAlias.mustache @@ -0,0 +1 @@ +export type {{classname}} = {{dataType}}; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelEnum.mustache new file mode 100644 index 00000000000..932d3c0fb47 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelEnum.mustache @@ -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}} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGeneric.mustache new file mode 100644 index 00000000000..a4248ea3da0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGeneric.mustache @@ -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}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericAdditionalProperties.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericAdditionalProperties.mustache new file mode 100644 index 00000000000..e6499ce9d63 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericAdditionalProperties.mustache @@ -0,0 +1,5 @@ +{{#additionalPropertiesType}} + + [key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}}; + +{{/additionalPropertiesType}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericEnums.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericEnums.mustache new file mode 100644 index 00000000000..432020b726f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelGenericEnums.mustache @@ -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}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/modelTaggedUnion.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelTaggedUnion.mustache new file mode 100644 index 00000000000..cd7d1c8b936 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/modelTaggedUnion.mustache @@ -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}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/models.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/models.mustache new file mode 100644 index 00000000000..02a39c248c4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/models.mustache @@ -0,0 +1,5 @@ +{{#models}} +{{#model}} +export * from './{{{ classFilename }}}'; +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/package.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/package.mustache new file mode 100644 index 00000000000..9733f2058a5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/package.mustache @@ -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}} +} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/tsconfig.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/tsconfig.mustache new file mode 100644 index 00000000000..3ed5f2c0b10 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/tsconfig.mustache @@ -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" + ] +} diff --git a/modules/swagger-codegen/src/main/resources/typescript-inversify/variables.mustache b/modules/swagger-codegen/src/main/resources/typescript-inversify/variables.mustache new file mode 100644 index 00000000000..5d3805255c2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-inversify/variables.mustache @@ -0,0 +1,6 @@ +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptInversifyClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptInversifyClientOptionsProvider.java new file mode 100644 index 00000000000..191cd6788c3 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptInversifyClientOptionsProvider.java @@ -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 createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + 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; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyClientOptionsTest.java new file mode 100644 index 00000000000..2aee4c61b5c --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyClientOptionsTest.java @@ -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; + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyModelTest.java new file mode 100644 index 00000000000..986f4b6956a --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypeScriptInversifyModelTest.java @@ -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"); + 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"); + 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); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyAdditionalPropertiesIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyAdditionalPropertiesIntegrationTest.java new file mode 100644 index 00000000000..8edf39f2f2c --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyAdditionalPropertiesIntegrationTest.java @@ -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 configProperties() { + Map 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"); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyArrayAndObjectIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyArrayAndObjectIntegrationTest.java new file mode 100644 index 00000000000..6dbc175923b --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyArrayAndObjectIntegrationTest.java @@ -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 configProperties() { + Map 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"); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyPestoreIntegrationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyPestoreIntegrationTest.java new file mode 100644 index 00000000000..de6cc5b5c51 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptinversify/TypescriptInversifyPestoreIntegrationTest.java @@ -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 configProperties() { + Map 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"); + } +} diff --git a/run-in-docker.sh b/run-in-docker.sh index 6777d9a31b5..b762ecde368 100755 --- a/run-in-docker.sh +++ b/run-in-docker.sh @@ -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 \ diff --git a/samples/client/petstore-security-test/typescript-inversify/.swagger-codegen-ignore b/samples/client/petstore-security-test/typescript-inversify/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/.swagger-codegen-ignore @@ -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 diff --git a/samples/client/petstore-security-test/typescript-inversify/.swagger-codegen/VERSION b/samples/client/petstore-security-test/typescript-inversify/.swagger-codegen/VERSION new file mode 100644 index 00000000000..855ff9501eb --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-inversify/ApiServiceBinder.ts b/samples/client/petstore-security-test/typescript-inversify/ApiServiceBinder.ts new file mode 100644 index 00000000000..60f8cd6fa5d --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/ApiServiceBinder.ts @@ -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").to(FakeService).inSingletonScope(); + } +} diff --git a/samples/client/petstore-security-test/typescript-inversify/Headers.ts b/samples/client/petstore-security-test/typescript-inversify/Headers.ts new file mode 100644 index 00000000000..0fa7760e01e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/Headers.ts @@ -0,0 +1,3 @@ +export interface Headers { + [index:string]: string +} diff --git a/samples/client/petstore-security-test/typescript-inversify/HttpClient.ts b/samples/client/petstore-security-test/typescript-inversify/HttpClient.ts new file mode 100644 index 00000000000..64fe12a3045 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/HttpClient.ts @@ -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 { + return this.performNetworkCall(url, "get", undefined, headers); + } + + post(url: string, body: {}|FormData, headers?: Headers): Observable { + return this.performNetworkCall(url, "post", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + put(url: string, body: {}, headers?: Headers): Observable { + return this.performNetworkCall(url, "put", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + delete(url: string, headers?: Headers): Observable { + 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 { + let promise = window.fetch(url, { + method: method, + body: body, + headers: 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 \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-inversify/HttpResponse.ts b/samples/client/petstore-security-test/typescript-inversify/HttpResponse.ts new file mode 100644 index 00000000000..411240cde2b --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/HttpResponse.ts @@ -0,0 +1,8 @@ +import { Headers } from "./Headers" + +class HttpResponse { + constructor(public response: T, public status:number, public headers?: Headers) { + } +} + +export default HttpResponse \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-inversify/IAPIConfiguration.ts b/samples/client/petstore-security-test/typescript-inversify/IAPIConfiguration.ts new file mode 100644 index 00000000000..2364e83e6cb --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/IAPIConfiguration.ts @@ -0,0 +1,8 @@ +export interface IAPIConfiguration { + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; +} \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-inversify/IHttpClient.ts b/samples/client/petstore-security-test/typescript-inversify/IHttpClient.ts new file mode 100644 index 00000000000..22d9e07c903 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/IHttpClient.ts @@ -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 + post(url:string, body:{}|FormData, headers?: Headers):Observable + put(url:string, body:{}, headers?: Headers):Observable + delete(url:string, headers?: Headers):Observable +} + +export default IHttpClient \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-inversify/api/fake.service.ts b/samples/client/petstore-security-test/typescript-inversify/api/fake.service.ts new file mode 100644 index 00000000000..418d247b156 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/api/fake.service.ts @@ -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 *_/ ' \" =end -- \\r\\n \\n \\r + * + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + + */ + public testCodeInjectEndRnNR(testCodeInjectEndRnNR?: string, observe?: 'body', headers?: Headers): Observable; + public testCodeInjectEndRnNR(testCodeInjectEndRnNR?: string, observe?: 'response', headers?: Headers): Observable>; + public testCodeInjectEndRnNR(testCodeInjectEndRnNR?: string, observe: any = 'body', headers: Headers = {}): Observable { + 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 */ ' " =end -- \r\n \n \r', testCodeInjectEndRnNR); + } + + const response: Observable> = this.httpClient.put(`${this.basePath}/fake`, body, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + +} diff --git a/samples/client/petstore-security-test/typescript-inversify/model/modelReturn.ts b/samples/client/petstore-security-test/typescript-inversify/model/modelReturn.ts new file mode 100644 index 00000000000..515aa6eff6a --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/model/modelReturn.ts @@ -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; +} diff --git a/samples/client/petstore-security-test/typescript-inversify/variables.ts b/samples/client/petstore-security-test/typescript-inversify/variables.ts new file mode 100644 index 00000000000..5d3805255c2 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-inversify/variables.ts @@ -0,0 +1,6 @@ +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/samples/client/petstore/typescript-inversify/.swagger-codegen-ignore b/samples/client/petstore/typescript-inversify/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/.swagger-codegen-ignore @@ -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 diff --git a/samples/client/petstore/typescript-inversify/.swagger-codegen/VERSION b/samples/client/petstore/typescript-inversify/.swagger-codegen/VERSION new file mode 100644 index 00000000000..855ff9501eb --- /dev/null +++ b/samples/client/petstore/typescript-inversify/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.4.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-inversify/ApiServiceBinder.ts b/samples/client/petstore/typescript-inversify/ApiServiceBinder.ts new file mode 100644 index 00000000000..779a0871208 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/ApiServiceBinder.ts @@ -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").to(PetService).inSingletonScope(); + container.bind("StoreService").to(StoreService).inSingletonScope(); + container.bind("UserService").to(UserService).inSingletonScope(); + } +} diff --git a/samples/client/petstore/typescript-inversify/Headers.ts b/samples/client/petstore/typescript-inversify/Headers.ts new file mode 100644 index 00000000000..0fa7760e01e --- /dev/null +++ b/samples/client/petstore/typescript-inversify/Headers.ts @@ -0,0 +1,3 @@ +export interface Headers { + [index:string]: string +} diff --git a/samples/client/petstore/typescript-inversify/HttpClient.ts b/samples/client/petstore/typescript-inversify/HttpClient.ts new file mode 100644 index 00000000000..64fe12a3045 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/HttpClient.ts @@ -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 { + return this.performNetworkCall(url, "get", undefined, headers); + } + + post(url: string, body: {}|FormData, headers?: Headers): Observable { + return this.performNetworkCall(url, "post", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + put(url: string, body: {}, headers?: Headers): Observable { + return this.performNetworkCall(url, "put", this.getJsonBody(body), this.addJsonHeaders(headers)); + } + + delete(url: string, headers?: Headers): Observable { + 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 { + let promise = window.fetch(url, { + method: method, + body: body, + headers: 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 \ No newline at end of file diff --git a/samples/client/petstore/typescript-inversify/HttpResponse.ts b/samples/client/petstore/typescript-inversify/HttpResponse.ts new file mode 100644 index 00000000000..411240cde2b --- /dev/null +++ b/samples/client/petstore/typescript-inversify/HttpResponse.ts @@ -0,0 +1,8 @@ +import { Headers } from "./Headers" + +class HttpResponse { + constructor(public response: T, public status:number, public headers?: Headers) { + } +} + +export default HttpResponse \ No newline at end of file diff --git a/samples/client/petstore/typescript-inversify/IAPIConfiguration.ts b/samples/client/petstore/typescript-inversify/IAPIConfiguration.ts new file mode 100644 index 00000000000..2364e83e6cb --- /dev/null +++ b/samples/client/petstore/typescript-inversify/IAPIConfiguration.ts @@ -0,0 +1,8 @@ +export interface IAPIConfiguration { + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-inversify/IHttpClient.ts b/samples/client/petstore/typescript-inversify/IHttpClient.ts new file mode 100644 index 00000000000..22d9e07c903 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/IHttpClient.ts @@ -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 + post(url:string, body:{}|FormData, headers?: Headers):Observable + put(url:string, body:{}, headers?: Headers):Observable + delete(url:string, headers?: Headers):Observable +} + +export default IHttpClient \ No newline at end of file diff --git a/samples/client/petstore/typescript-inversify/api/pet.service.ts b/samples/client/petstore/typescript-inversify/api/pet.service.ts new file mode 100644 index 00000000000..b52d0f56cf8 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/api/pet.service.ts @@ -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; + public addPet(body: Pet, observe?: 'response', headers?: Headers): Observable>; + public addPet(body: Pet, observe: any = 'body', headers: Headers = {}): Observable { + 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> = this.httpClient.post(`${this.basePath}/pet`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (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; + public deletePet(petId: number, apiKey?: string, observe?: 'response', headers?: Headers): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', headers: Headers = {}): Observable { + 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> = this.httpClient.delete(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (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>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', headers?: Headers): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', headers: Headers = {}): Observable { + 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>> = this.httpClient.get(`${this.basePath}/pet/findByStatus?${queryParameters.join('&')}`, headers); + if (observe == 'body') { + return response.map(httpResponse => >(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, observe?: 'body', headers?: Headers): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', headers?: Headers): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', headers: Headers = {}): Observable { + 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>> = this.httpClient.get(`${this.basePath}/pet/findByTags?${queryParameters.join('&')}`, headers); + if (observe == 'body') { + return response.map(httpResponse => >(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; + public getPetById(petId: number, observe?: 'response', headers?: Headers): Observable>; + public getPetById(petId: number, observe: any = 'body', headers: Headers = {}): Observable { + 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> = this.httpClient.get(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (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; + public updatePet(body: Pet, observe?: 'response', headers?: Headers): Observable>; + public updatePet(body: Pet, observe: any = 'body', headers: Headers = {}): Observable { + 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> = this.httpClient.put(`${this.basePath}/pet`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (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; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', headers?: Headers): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', headers: Headers = {}): Observable { + 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', name); + } + if (status !== undefined) { + formData.append('status', status); + } + + const response: Observable> = this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}`, body, headers); + if (observe == 'body') { + return response.map(httpResponse => (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; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', headers?: Headers): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', headers: Headers = {}): Observable { + 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', additionalMetadata); + } + if (file !== undefined) { + formData.append('file', file); + } + + const response: Observable> = this.httpClient.post(`${this.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, body, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + +} diff --git a/samples/client/petstore/typescript-inversify/api/store.service.ts b/samples/client/petstore/typescript-inversify/api/store.service.ts new file mode 100644 index 00000000000..0185d32f2af --- /dev/null +++ b/samples/client/petstore/typescript-inversify/api/store.service.ts @@ -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 < 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; + public deleteOrder(orderId: string, observe?: 'response', headers?: Headers): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', headers: Headers = {}): Observable { + if (!orderId){ + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.delete(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (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>; + public getInventory(observe: any = 'body', headers: Headers = {}): Observable { + // 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> = 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 <= 5 or > 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; + public getOrderById(orderId: number, observe?: 'response', headers?: Headers): Observable>; + public getOrderById(orderId: number, observe: any = 'body', headers: Headers = {}): Observable { + if (!orderId){ + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/store/order/${encodeURIComponent(String(orderId))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (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; + public placeOrder(body: Order, observe?: 'response', headers?: Headers): Observable>; + public placeOrder(body: Order, observe: any = 'body', headers: Headers = {}): Observable { + 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> = this.httpClient.post(`${this.basePath}/store/order`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + +} diff --git a/samples/client/petstore/typescript-inversify/api/user.service.ts b/samples/client/petstore/typescript-inversify/api/user.service.ts new file mode 100644 index 00000000000..3a794603bf8 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/api/user.service.ts @@ -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; + public createUser(body: User, observe?: 'response', headers?: Headers): Observable>; + public createUser(body: User, observe: any = 'body', headers: Headers = {}): Observable { + 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> = this.httpClient.post(`${this.basePath}/user`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Creates list of users with given input array + * + * @param body List of user object + + */ + public createUsersWithArrayInput(body: Array, observe?: 'body', headers?: Headers): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', headers?: Headers): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', headers: Headers = {}): Observable { + 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> = this.httpClient.post(`${this.basePath}/user/createWithArray`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Creates list of users with given input array + * + * @param body List of user object + + */ + public createUsersWithListInput(body: Array, observe?: 'body', headers?: Headers): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', headers?: Headers): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', headers: Headers = {}): Observable { + 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> = this.httpClient.post(`${this.basePath}/user/createWithList`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (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; + public deleteUser(username: string, observe?: 'response', headers?: Headers): Observable>; + public deleteUser(username: string, observe: any = 'body', headers: Headers = {}): Observable { + if (!username){ + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.delete(`${this.basePath}/user/${encodeURIComponent(String(username))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (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; + public getUserByName(username: string, observe?: 'response', headers?: Headers): Observable>; + public getUserByName(username: string, observe: any = 'body', headers: Headers = {}): Observable { + if (!username){ + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/user/${encodeURIComponent(String(username))}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (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; + public loginUser(username: string, password: string, observe?: 'response', headers?: Headers): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', headers: Headers = {}): Observable { + 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> = this.httpClient.get(`${this.basePath}/user/login?${queryParameters.join('&')}`, headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + + + /** + * Logs out current logged in user session + * + + */ + public logoutUser(observe?: 'body', headers?: Headers): Observable; + public logoutUser(observe?: 'response', headers?: Headers): Observable>; + public logoutUser(observe: any = 'body', headers: Headers = {}): Observable { + headers['Accept'] = 'application/xml'; + + const response: Observable> = this.httpClient.get(`${this.basePath}/user/logout`, headers); + if (observe == 'body') { + return response.map(httpResponse => (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; + public updateUser(username: string, body: User, observe?: 'response', headers?: Headers): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', headers: Headers = {}): Observable { + 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> = this.httpClient.put(`${this.basePath}/user/${encodeURIComponent(String(username))}`, body , headers); + if (observe == 'body') { + return response.map(httpResponse => (httpResponse.response)); + } + return response; + } + +} diff --git a/samples/client/petstore/typescript-inversify/model/apiResponse.ts b/samples/client/petstore/typescript-inversify/model/apiResponse.ts new file mode 100644 index 00000000000..af5590c3d85 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/model/apiResponse.ts @@ -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; +} diff --git a/samples/client/petstore/typescript-inversify/model/category.ts b/samples/client/petstore/typescript-inversify/model/category.ts new file mode 100644 index 00000000000..093bd438a38 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/model/category.ts @@ -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; +} diff --git a/samples/client/petstore/typescript-inversify/model/order.ts b/samples/client/petstore/typescript-inversify/model/order.ts new file mode 100644 index 00000000000..6a1e1fd6bcf --- /dev/null +++ b/samples/client/petstore/typescript-inversify/model/order.ts @@ -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 + } +} diff --git a/samples/client/petstore/typescript-inversify/model/pet.ts b/samples/client/petstore/typescript-inversify/model/pet.ts new file mode 100644 index 00000000000..b8b659008af --- /dev/null +++ b/samples/client/petstore/typescript-inversify/model/pet.ts @@ -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; + tags?: Array; + /** + * 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 + } +} diff --git a/samples/client/petstore/typescript-inversify/model/tag.ts b/samples/client/petstore/typescript-inversify/model/tag.ts new file mode 100644 index 00000000000..e35232df691 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/model/tag.ts @@ -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; +} diff --git a/samples/client/petstore/typescript-inversify/model/user.ts b/samples/client/petstore/typescript-inversify/model/user.ts new file mode 100644 index 00000000000..e8788de129c --- /dev/null +++ b/samples/client/petstore/typescript-inversify/model/user.ts @@ -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; +} diff --git a/samples/client/petstore/typescript-inversify/variables.ts b/samples/client/petstore/typescript-inversify/variables.ts new file mode 100644 index 00000000000..5d3805255c2 --- /dev/null +++ b/samples/client/petstore/typescript-inversify/variables.ts @@ -0,0 +1,6 @@ +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +}