diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java index 26b6fef1135..812be6981d4 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -16,12 +16,14 @@ package io.swagger.codegen.plugin; * limitations under the License. */ +import io.swagger.codegen.CliOption; import io.swagger.codegen.ClientOptInput; import io.swagger.codegen.ClientOpts; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.DefaultGenerator; import io.swagger.models.Swagger; import io.swagger.parser.SwaggerParser; + import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -29,6 +31,9 @@ import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; +import config.Config; +import config.ConfigParser; + import java.io.File; import java.util.ServiceLoader; @@ -66,6 +71,12 @@ public class CodeGenMojo extends AbstractMojo { @Parameter(name = "language", required = true) private String language; + /** + * Path to json configuration file. + */ + @Parameter(name = "configurationFile", required = false) + private String configurationFile; + /** * Add the output directory to the project as a source root, so that the @@ -90,7 +101,20 @@ public class CodeGenMojo extends AbstractMojo { if (null != templateDirectory) { config.additionalProperties().put(TEMPLATE_DIR_PARAM, templateDirectory.getAbsolutePath()); } - + + if (null != configurationFile) { + Config genConfig = ConfigParser.read(configurationFile); + if (null != genConfig) { + for (CliOption langCliOption : config.cliOptions()) { + if (genConfig.hasOption(langCliOption.getOpt())) { + config.additionalProperties().put(langCliOption.getOpt(), genConfig.getOption(langCliOption.getOpt())); + } + } + } else { + throw new RuntimeException("Unable to read configuration file"); + } + } + ClientOptInput input = new ClientOptInput().opts(new ClientOpts()).swagger(swagger); input.setConfig(config); new DefaultGenerator().opts(input).generate(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index bc4f08d7f55..c44e070fe62 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -600,7 +600,7 @@ public class DefaultCodegen { public CodegenProperty fromProperty(String name, Property p) { if (p == null) { - LOGGER.error("unexpected missing property for name " + null); + LOGGER.error("unexpected missing property for name " + name); return null; } CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 6289757d80f..d48238c2489 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -2,6 +2,8 @@ package io.swagger.codegen; import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; + +import io.swagger.models.ComposedModel; import io.swagger.models.Contact; import io.swagger.models.Info; import io.swagger.models.License; @@ -12,6 +14,7 @@ import io.swagger.models.Swagger; import io.swagger.models.auth.OAuth2Definition; import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.util.Json; + import org.apache.commons.io.IOUtils; import java.io.File; @@ -21,6 +24,8 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; @@ -119,7 +124,9 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { // models Map definitions = swagger.getDefinitions(); if (definitions != null) { - for (String name : definitions.keySet()) { + List sortedModelKeys = sortModelsByInheritance(definitions); + + for (String name : sortedModelKeys) { Model model = definitions.get(name); Map modelMap = new HashMap(); modelMap.put(name, model); @@ -326,6 +333,52 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operation.put(flagFieldName, true); } } + + private List sortModelsByInheritance(final Map definitions) { + List sortedModelKeys = new ArrayList(definitions.keySet()); + Comparator cmp = new Comparator() { + @Override + public int compare(String o1, String o2) { + Model model1 = definitions.get(o1); + Model model2 = definitions.get(o2); + + int model1InheritanceDepth = getInheritanceDepth(model1); + int model2InheritanceDepth = getInheritanceDepth(model2); + + if (model1InheritanceDepth == model2InheritanceDepth) { + return 0; + } else if (model1InheritanceDepth > model2InheritanceDepth) { + return 1; + } else { + return -1; + } + } + + private int getInheritanceDepth(Model model) { + int inheritanceDepth = 0; + Model parent = getParent(model); + + while (parent != null) { + inheritanceDepth++; + parent = getParent(parent); + } + + return inheritanceDepth; + } + + private Model getParent(Model model) { + if (model instanceof ComposedModel) { + return definitions.get(((ComposedModel) model).getParent().getReference()); + } + + return null; + } + }; + + Collections.sort(sortedModelKeys, cmp); + + return sortedModelKeys; + } public Map> processPaths(Map paths) { Map> ops = new HashMap>(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java new file mode 100644 index 00000000000..883ad66ff7f --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -0,0 +1,143 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public AbstractTypeScriptClientCodegen() { + super(); + reservedWords = new HashSet(Arrays.asList("abstract", + "continue", "for", "new", "switch", "assert", "default", "if", + "package", "synchronized", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", + "byte", "else", "import", "public", "throws", "case", "enum", + "instanceof", "return", "transient", "catch", "extends", "int", + "short", "try", "char", "final", "interface", "static", "void", + "class", "finally", "const", "super", "while")); + + languageSpecificPrimitives = new HashSet(Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object")); + instantiationTypes.put("array", "Array"); + + typeMapping = new HashMap(); + typeMapping.put("Array", "Array"); + typeMapping.put("array", "Array"); + typeMapping.put("List", "Array"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("string", "string"); + typeMapping.put("int", "number"); + typeMapping.put("float", "number"); + typeMapping.put("number", "number"); + typeMapping.put("long", "number"); + typeMapping.put("short", "number"); + typeMapping.put("char", "string"); + typeMapping.put("double", "number"); + typeMapping.put("object", "any"); + typeMapping.put("integer", "number"); + typeMapping.put("Map", "any"); + typeMapping.put("DateTime", "Date"); + + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) + return name; + + // camelize the variable name + // pet_id => PetId + name = camelize(name, true); + + // for reserved word or word starting with number, append _ + if (reservedWords.contains(name) || name.matches("^\\d.*")) + name = escapeReservedWord(name); + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) + throw new RuntimeException(name + + " (reserved word) cannot be used as a model name"); + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // should be the same as the model name + return toModelName(name); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return "{ [key: string]: "+ getTypeDeclaration(inner) + "; }"; + } else if (p instanceof FileProperty) { + return "any"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) + return type; + } else + type = swaggerType; + return type; + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 0fdb19e806d..3e5edbc169f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -57,7 +57,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.clear(); typeMapping.put("enum", "NSString"); - typeMapping.put("Date", "NSDate"); + typeMapping.put("date", "NSDate"); typeMapping.put("DateTime", "NSDate"); typeMapping.put("boolean", "NSNumber"); typeMapping.put("string", "NSString"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 5d4f5f341a7..55c3864adb7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -100,7 +100,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("number", "Double"); typeMapping.put("double", "Double"); typeMapping.put("object", "String"); - typeMapping.put("file", "NSData"); + typeMapping.put("file", "NSURL"); importMapping = new HashMap(); @@ -109,6 +109,17 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { StringUtils.join(RESPONSE_LIBRARIES, ", ") + " are available.")); cliOptions.add(new CliOption("unwrapRequired", "Treat 'required' properties in response as non-optional " + "(which would crash the app if api returns null as opposed to required option specified in json schema")); + cliOptions.add(new CliOption("podSource", "Source information used for Podspec")); + cliOptions.add(new CliOption("podVersion", "Version used for Podspec")); + cliOptions.add(new CliOption("podAuthors", "Authors used for Podspec")); + cliOptions.add(new CliOption("podSocialMediaURL", "Social Media URL used for Podspec")); + cliOptions.add(new CliOption("podDocsetURL", "Docset URL used for Podspec")); + cliOptions.add(new CliOption("podLicense", "License used for Podspec")); + cliOptions.add(new CliOption("podHomepage", "Homepage used for Podspec")); + cliOptions.add(new CliOption("podSummary", "Summary used for Podspec")); + cliOptions.add(new CliOption("podDescription", "Description used for Podspec")); + cliOptions.add(new CliOption("podScreenshots", "Screenshots used for Podspec")); + cliOptions.add(new CliOption("podDocumentationURL", "Documentation URL used for Podspec")); } @Override @@ -143,6 +154,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("usePromiseKit", true); } + supportingFiles.add(new SupportingFile("Podspec.mustache", "", projectName + ".podspec")); supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, @@ -283,4 +295,4 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { return builder.toString(); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java index 11cae0de0ef..8eec2b8772e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -1,25 +1,28 @@ package io.swagger.codegen.languages; -import java.io.File; - import io.swagger.codegen.SupportingFile; -public class TypeScriptAngularClientCodegen extends TypeScriptNodeClientCodegen { +import java.io.File; + +public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen { @Override public String getName() { return "typescript-angular"; } - + + public String getHelp() { + return "Generates a TypeScript AngurlarJS client library."; + } + public TypeScriptAngularClientCodegen() { super(); outputFolder = "generated-code/typescript-angular"; modelTemplateFiles.put("model.mustache", ".ts"); apiTemplateFiles.put("api.mustache", ".ts"); templateDir = "TypeScript-Angular"; - apiPackage = "api"; - modelPackage = "model"; - - supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage + File.separator, "api.d.ts")); + apiPackage = "API.Client"; + modelPackage = "API.Client"; + supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage().replace('.', File.separatorChar), "api.d.ts")); } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java index 0ea33f21709..b92598b1fb6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -1,171 +1,24 @@ package io.swagger.codegen.languages; -import io.swagger.codegen.*; -import io.swagger.models.properties.*; +import io.swagger.codegen.SupportingFile; -import java.util.*; -import java.io.File; +public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen { -public class TypeScriptNodeClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-typescript-node-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/typescript"; + @Override + public String getName() { + return "typescript-node"; + } - @Override - public CodegenType getTag() { - return CodegenType.CLIENT; - } + @Override + public String getHelp() { + return "Generates a TypeScript nodejs client library."; + } - @Override - public String getName() { - return "typescript-node"; - } + public TypeScriptNodeClientCodegen() { + super(); + outputFolder = "generated-code/typescript-node"; + templateDir = "TypeScript-node"; + supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); + } - @Override - public String getHelp() { - return "Generates a TypeScript nodejs client library."; - } - - public TypeScriptNodeClientCodegen() { - super(); - outputFolder = "generated-code/typescript-node"; - modelTemplateFiles.put("model.mustache", ".ts"); - apiTemplateFiles.put("api.mustache", ".ts"); - templateDir = "TypeScript-node"; - apiPackage = "api"; - modelPackage = "model"; - - reservedWords = new HashSet(Arrays.asList("abstract", - "continue", "for", "new", "switch", "assert", "default", "if", - "package", "synchronized", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", - "byte", "else", "import", "public", "throws", "case", "enum", - "instanceof", "return", "transient", "catch", "extends", "int", - "short", "try", "char", "final", "interface", "static", "void", - "class", "finally", "const", "super", "while")); - - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - - languageSpecificPrimitives = new HashSet(Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object")); - instantiationTypes.put("array", "Array"); - - typeMapping = new HashMap(); - typeMapping.put("Array", "Array"); - typeMapping.put("array", "Array"); - typeMapping.put("List", "Array"); - typeMapping.put("boolean", "boolean"); - typeMapping.put("string", "string"); - typeMapping.put("int", "number"); - typeMapping.put("float", "number"); - typeMapping.put("number", "number"); - typeMapping.put("long", "number"); - typeMapping.put("short", "number"); - typeMapping.put("char", "string"); - typeMapping.put("double", "number"); - typeMapping.put("object", "any"); - typeMapping.put("integer", "number"); - typeMapping.put("Map", "any"); - typeMapping.put("DateTime", "Date"); - - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) - return name; - - // camelize the variable name - // pet_id => PetId - name = camelize(name, true); - - // for reserved word or word starting with number, append _ - if (reservedWords.contains(name) || name.matches("^\\d.*")) - name = escapeReservedWord(name); - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String toModelName(String name) { - // model name cannot use reserved keyword, e.g. return - if (reservedWords.contains(name)) - throw new RuntimeException(name - + " (reserved word) cannot be used as a model name"); - - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } - - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + ""; - } - return super.getTypeDeclaration(p); - } - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) - return type; - } else - type = swaggerType; - return type; - } } diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index bd5eaaef87a..427d847663b 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -6,11 +6,11 @@ module {{package}} { 'use strict'; - {{#description}} +{{#description}} /** * {{&description}} */ - {{/description}} +{{/description}} export class {{classname}} { private basePath = '{{contextPath}}'; @@ -21,24 +21,37 @@ module {{package}} { this.basePath = basePath; } } - {{#operation}} +{{#operation}} + public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { var path = this.basePath + '{{path}}'; - {{#pathParams}} + +{{#pathParams}} path = path.replace('{' + '{{paramName}}' + '}', String({{paramName}})); - {{/pathParams}} + +{{/pathParams}} var queryParameters: any = {}; var headerParams: any = {}; - {{#allParams}}{{#required}} + +{{#allParams}} +{{#required}} // verify required parameter '{{paramName}}' is set if (!{{paramName}}) { throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); } - {{/required}}{{/allParams}} - {{#queryParams}}if ({{paramName}} !== undefined) { + +{{/required}} +{{/allParams}} +{{#queryParams}} + if ({{paramName}} !== undefined) { queryParameters['{{paramName}}'] = {{paramName}}; - }{{/queryParams}} - {{#headerParams}}headerParams['{{paramName}}'] = {{paramName}};{{/headerParams}} + } + +{{/queryParams}} +{{#headerParams}} + headerParams['{{paramName}}'] = {{paramName}}; + +{{/headerParams}} var httpRequestParams: any = { method: '{{httpMethod}}', url: path, @@ -59,7 +72,7 @@ module {{package}} { return this.$http(httpRequestParams); } - {{/operation}} +{{/operation}} } } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index debeed69515..f8d4577ee7a 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -1,73 +1,245 @@ +import request = require('request'); +import promise = require('bluebird'); +import http = require('http'); + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + /* tslint:disable:no-unused-variable */ -{{#operations}} +{{#models}} +{{#model}} +{{#description}} +/** +* {{{description}}} +*/ +{{/description}} +export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ +{{#vars}} {{#description}} /** - * {{&description}} + * {{{description}}} */ +{{/description}} + {{name}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; +{{/vars}} +} + +{{#hasEnums}} +export module {{classname}} { +{{#vars}} +{{#isEnum}} + export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} + {{.}} = '{{.}}',{{/values}}{{/allowableValues}} + } +{{/isEnum}} +{{/vars}} +} +{{/hasEnums}} +{{/model}} +{{/models}} + +interface Authentication { + /** + * Apply authentication settings to header and query params. + */ + applyToRequest(requestOptions: request.Options): void; +} + +class HttpBasicAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + requestOptions.auth = { + username: this.username, password: this.password + } + } +} + +class ApiKeyAuth implements Authentication { + public apiKey: string; + + constructor(private location: string, private paramName: string) { + } + + applyToRequest(requestOptions: request.Options): void { + if (this.location == "query") { + (requestOptions.qs)[this.paramName] = this.apiKey; + } else if (this.location == "header") { + requestOptions.headers[this.paramName] = this.apiKey; + } + } +} + +class OAuth implements Authentication { + applyToRequest(requestOptions: request.Options): void { + // TODO: support oauth + } +} + +class VoidAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + // Do nothing + } +} + +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#description}} +/** +* {{&description}} +*/ {{/description}} export class {{classname}} { private basePath = '{{contextPath}}'; - - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; - } + public authentications = { + 'default': new VoidAuth(), +{{#authMethods}} +{{#isBasic}} + '{{name}}': new HttpBasicAuth(), +{{/isBasic}} +{{#isApiKey}} + '{{name}}': new ApiKeyAuth({{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{^isKeyInHeader}}'query'{{/isKeyInHeader}}, '{{keyParamName}}'), +{{/isApiKey}} +{{#isOAuth}} + '{{name}}': new OAuth(), +{{/isOAuth}} +{{/authMethods}} } - {{#operation}} - public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }> { - var path = this.url + this.basePath + '{{path}}'; - - {{#pathParams}} - path = path.replace('{' + '{{paramName}}' + '}', String({{paramName}})); - {{/pathParams}} - - var queryParameters: any = {}; - var headerParams: any = {}; - - {{#allParams}}{{#required}} - // verify required parameter '{{paramName}}' is set - if (!{{paramName}}) { - throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); - } - {{/required}}{{/allParams}} - - {{#queryParams}}if ({{paramName}} !== undefined) { - queryParameters['{{paramName}}'] = {{paramName}}; - } - {{/queryParams}} - - {{#headerParams}}headerParams['{{paramName}}'] = {{paramName}}; - {{/headerParams}} - - var deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }>(); - - request({ - method: '{{httpMethod}}', - qs: queryParameters, - uri: path, - json: true, - {{#bodyParam}}body: {{paramName}}, - {{/bodyParam}} - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); + constructor(url: string, basePath?: string); +{{#authMethods}} +{{#isBasic}} + constructor(url: string, username: string, password: string, basePath?: string); +{{/isBasic}} +{{/authMethods}} + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { +{{#authMethods}} +{{#isBasic}} + this.username = basePathOrUsername; + this.password = password +{{/isBasic}} +{{/authMethods}} + if (basePath) { + this.basePath = basePath; + } } else { - deferred.reject({ response: response, body: body }); + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } } - } - }); + } +{{#authMethods}} +{{#isBasic}} - return deferred.promise; - } + set username(username: string) { + this.authentications.{{name}}.username = username; + } - {{/operation}} + set password(password: string) { + this.authentications.{{name}}.password = password; + } +{{/isBasic}} +{{#isApiKey}} + + set apiKey(key: string) { + this.authentications.{{name}}.apiKey = key; + } +{{/isApiKey}} +{{#isOAuth}} +{{/isOAuth}} +{{/authMethods}} +{{#operation}} + + public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }> { + var path = this.url + this.basePath + '{{path}}'; + +{{#pathParams}} + path = path.replace('{' + '{{paramName}}' + '}', String({{paramName}})); + +{{/pathParams}} + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + +{{#allParams}} +{{#required}} + // verify required parameter '{{paramName}}' is set + if (!{{paramName}}) { + throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); + } + +{{/required}} +{{/allParams}} +{{#queryParams}} + if ({{paramName}} !== undefined) { + queryParameters['{{paramName}}'] = {{paramName}}; + } + +{{/queryParams}} +{{#headerParams}} + headerParams['{{paramName}}'] = {{paramName}}; + +{{/headerParams}} + var useFormData = false; + +{{#formParams}} + if ({{paramName}} !== undefined) { + formParams['{{paramName}}'] = {{paramName}}; + } +{{#isFile}} + useFormData = true; +{{/isFile}} + +{{/formParams}} + var deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }>(); + + var requestOptions: request.Options = { + method: '{{httpMethod}}', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, +{{#bodyParam}} + body: {{paramName}}, +{{/bodyParam}} + } + +{{#authMethods}} + this.authentications.{{name}}.applyToRequest(requestOptions); + +{{/authMethods}} + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +{{/operation}} } {{/operations}} +{{/apis}} +{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/model.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/model.mustache deleted file mode 100644 index 55c8997e1bc..00000000000 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/model.mustache +++ /dev/null @@ -1,33 +0,0 @@ -{{#models}} -{{#model}} -{{#description}} -/** - * {{{description}}} - */ -{{/description}} -export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ -{{#vars}} - -{{#description}} - /** - * {{{description}}} - */ -{{/description}} - {{name}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; -{{/vars}} -} - -{{#hasEnums}} -export module {{classname}} { -{{#vars}} -{{#isEnum}} - - export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} - {{.}} = '{{.}}',{{/values}}{{/allowableValues}} - } -{{/isEnum}} -{{/vars}} -} -{{/hasEnums}} -{{/model}} -{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index 0edab7414f1..a5871400352 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -5,9 +5,14 @@ #import "{{classPrefix}}JSONRequestSerializer.h" #import "{{classPrefix}}QueryParamCollection.h" #import "{{classPrefix}}Configuration.h" - -{{#models}}{{#model}}#import "{{classname}}.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +{{#models}}{{#model}}#import "{{classname}}.h" {{/model}}{{/models}} /** @@ -25,7 +30,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; @property(nonatomic, readonly) NSOperationQueue* queue; /** - * Get the Api Client instance from pool + * Gets the Api Client instance from pool * * @param baseUrl The base url of api client. * @@ -34,68 +39,68 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; +({{classPrefix}}ApiClient *)sharedClientFromPool:(NSString *)baseUrl; /** - * Get the operations queue + * Gets the operations queue * * @return The `shardQueue` static variable. */ +(NSOperationQueue*) sharedQueue; /** - * Clear Cache + * Clears Cache */ +(void)clearCache; /** - * Turn on cache + * Turns on cache * * @param enabled If the cached is enable, must be `YES` or `NO` */ +(void)setCacheEnabled:(BOOL) enabled; /** - * Get the request queue size + * Gets the request queue size * * @return The size of `queuedRequests` static variable. */ +(unsigned long)requestQueueSize; /** - * Set the client unreachable + * Sets the client unreachable * - * @param state off line state, must be `YES` or `NO` + * @param state off line state, must be `YES` or `NO` */ +(void) setOfflineState:(BOOL) state; /** - * Get the client reachability + * Gets the client reachability * * @return The client reachability. */ +(AFNetworkReachabilityStatus) getReachabilityStatus; /** - * Get the next request id + * Gets the next request id * * @return The next executed request id. */ +(NSNumber*) nextRequestId; /** - * Generate request id and add it to the queue + * Generates request id and add it to the queue * * @return The next executed request id. */ +(NSNumber*) queueRequest; /** - * Remove request id from the queue + * Removes request id from the queue * * @param requestId The request which will be removed. */ +(void) cancelRequest:(NSNumber*)requestId; /** - * URL encode NSString + * Gets URL encoded NSString * * @param unescaped The string which will be escaped. * @@ -104,21 +109,21 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; +(NSString*) escape:(id)unescaped; /** - * Customize the behavior when the reachability changed + * Customizes the behavior when the reachability changed * * @param changeBlock The block will be executed when the reachability changed. */ +(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; /** - * Set the client reachability strategy + * Sets the client reachability strategy * * @param host The host of {{classPrefix}}ApiClient. */ +(void) configureCacheReachibilityForHost:(NSString*)host; /** - * Detect Accept header from accepts NSArray + * Detects Accept header from accepts NSArray * * @param accepts NSArray of header * @@ -127,7 +132,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; +(NSString *) selectHeaderAccept:(NSArray *)accepts; /** - * Detect Content-Type header from contentTypes NSArray + * Detects Content-Type header from contentTypes NSArray * * @param contentTypes NSArray of header * @@ -136,7 +141,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; +(NSString *) selectHeaderContentType:(NSArray *)contentTypes; /** - * Set header for request + * Sets header for request * * @param value The header value * @param forKey The header key @@ -145,7 +150,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; forKey:(NSString*) forKey; /** - * Update header parameters and query parameters for authentication + * Updates header parameters and query parameters for authentication * * @param headers The header parameter will be udpated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. @@ -156,7 +161,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; WithAuthSettings:(NSArray *)authSettings; /** - * Deserialize the given data to Objective-C object. + * Deserializes the given data to Objective-C object. * * @param data The data will be deserialized. * @param class The type of objective-c object. @@ -164,7 +169,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; - (id) deserialize:(id) data class:(NSString *) class; /** - * Logging request and response + * Logs request and response * * @param operation AFHTTPRequestOperation for the HTTP request. * @param request The HTTP request. @@ -175,7 +180,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; error:(NSError *)error; /** - * Perform request + * Performs request * * @param path Request url. * @param method Request method. @@ -185,7 +190,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * @param authSettings Request authentication names. * @param requestContentType Request content-type. * @param responseContentType Response content-type. - * @param completionBlock The block will be executed when the request completed. + * @param completionBlock The block will be executed when the request completed. * * @return The request id. */ diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache index 832c69f417e..75d73d6e414 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache @@ -60,12 +60,20 @@ #pragma mark - Setter Methods -- (void) setValue:(NSString *)value forApiKeyField:(NSString *)field { - [self.mutableApiKey setValue:value forKey:field]; +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { + [self.mutableApiKey setValue:apiKey forKey:identifier]; } -- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field { - [self.mutableApiKeyPrefix setValue:value forKey:field]; +- (void) removeApiKey:(NSString *)identifier { + [self.mutableApiKey removeObjectForKey:identifier]; +} + +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier { + [self.mutableApiKeyPrefix setValue:prefix forKey:identifier]; +} + +- (void) removeApiKeyPrefix:(NSString *)identifier { + [self.mutableApiKeyPrefix removeObjectForKey:identifier]; } - (void) setLoggingFile:(NSString *)loggingFile { @@ -75,10 +83,10 @@ } _loggingFile = loggingFile; - self.loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - if (self.loggingFileHanlder == nil) { + _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHanlder == nil) { [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; - self.loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; } } diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache index 4f9518ea9d1..6b311e968b0 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache @@ -1,26 +1,36 @@ #import +/** The `{{classPrefix}}Configuration` class manages the configurations for the sdk. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ @interface {{classPrefix}}Configuration : NSObject /** * Api key values for Api Key type Authentication * - * To add or remove api key, use `setValue:forApiKeyField:`. + * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. */ @property (readonly, nonatomic, strong) NSDictionary *apiKey; /** * Api key prefix values to be prepend to the respective api key * - * To add or remove prefix, use `setValue:forApiKeyPrefixField:`. + * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. */ @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; /** - * Usename and Password for Basic type Authentication + * Usename for HTTP Basic Authentication + */ + @property (nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication */ -@property (nonatomic) NSString *username; @property (nonatomic) NSString *password; /** @@ -31,37 +41,74 @@ /** * Logging Settings */ -@property (nonatomic) BOOL debug; -@property (nonatomic) NSString *loggingFile; -@property (nonatomic) NSFileHandle *loggingFileHanlder; /** - * Get configuration singleton instance + * Debug switch, default false + */ +@property (nonatomic) BOOL debug; + +/** + * Debug file location, default log in console + */ +@property (nonatomic) NSString *loggingFile; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; + +/** + * Gets configuration singleton instance */ + (instancetype) sharedConfig; /** - * Sets field in `apiKey` + * Sets API key + * + * To remove a apiKey for an identifier, just set the apiKey to nil. + * + * @param apiKey API key or token. + * @param identifier API key identifier (authentication schema). + * */ -- (void) setValue:(NSString *)value forApiKeyField:(NSString*)field; +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; /** - * Sets field in `apiKeyPrefix` + * Removes api key + * + * @param identifier API key identifier. */ -- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field; +- (void) removeApiKey:(NSString *)identifier; /** - * Get API key (with prefix if set) + * Sets the prefix for API key + * + * To remove a apiKeyPrefix for an identifier, just set the apiKeyPrefix to nil. + * + * @param apiKeyPrefix API key prefix. + * @param identifier API key identifier. + */ +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; + +/** + * Removes api key prefix + * + * @param identifier API key identifier. + */ +- (void) removeApiKeyPrefix:(NSString *)identifier; + +/** + * Gets API key (with prefix if set) */ - (NSString *) getApiKeyWithPrefix:(NSString *) key; /** - * Get Basic Auth token + * Gets Basic Auth token */ - (NSString *) getBasicAuthToken; /** - * Get Authentication Setings + * Gets Authentication Setings */ - (NSDictionary *) authSettings; diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index 263c213dd6f..6b85f753e45 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -5,6 +5,12 @@ #import "{{classPrefix}}ApiClient.h" {{newline}} +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + {{#operations}} @interface {{classname}}: NSObject diff --git a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache index b728e6bb06c..33c0f8cf42b 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -3,12 +3,21 @@ #import "{{classname}}.h" @implementation {{classname}} - + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; @@ -21,6 +30,14 @@ } } +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + {{/model}} @end {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/objc/model-header.mustache b/modules/swagger-codegen/src/main/resources/objc/model-header.mustache index 4afaec31a24..c3f3c865424 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-header.mustache @@ -1,5 +1,12 @@ #import #import "{{classPrefix}}Object.h" + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + {{#imports}}#import "{{import}}.h" {{/imports}} {{newline}} @@ -8,7 +15,7 @@ @protocol {{classname}} @end - + @interface {{classname}} : {{classPrefix}}Object {{#vars}} diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 37bf1be69c0..16604bca18c 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -45,13 +45,13 @@ class ApiClient(object): :param header_value: a header value to pass when making calls to the API """ def __init__(self, host=Configuration().host, - header_name=None, header_value=None): + header_name=None, header_value=None, cookie=None): self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.host = host - self.cookie = None + self.cookie = cookie # Set default User-Agent. self.user_agent = 'Python-Swagger' diff --git a/modules/swagger-codegen/src/main/resources/python3/swagger.mustache b/modules/swagger-codegen/src/main/resources/python3/swagger.mustache index f99f0d4d250..57f959c380b 100644 --- a/modules/swagger-codegen/src/main/resources/python3/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python3/swagger.mustache @@ -18,13 +18,13 @@ from .models import * class ApiClient: """Generic API client for Swagger client library builds""" - def __init__(self, apiKey=None, apiServer=None): + def __init__(self, apiKey=None, apiServer=None, cookie=None): if apiKey == None: raise Exception('You must pass an apiKey when instantiating the ' 'APIClient') self.apiKey = apiKey self.apiServer = apiServer - self.cookie = None + self.cookie = cookie def callAPI(self, resourcePath, method, queryParams, postData, headerParams=None): diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 61e2bf2886d..c1718cb6780 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -29,7 +29,47 @@ class AlamofireRequestBuilder: RequestBuilder { managerStore[managerId] = manager let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL - let request = manager.request(Alamofire.Method(rawValue: method)!, URLString, parameters: parameters, encoding: encoding) + let xMethod = Alamofire.Method(rawValue: method) + let fileKeys = parameters == nil ? [] : map(filter(parameters!) { $1.isKindOfClass(NSURL) }) { $0.0 } + + if fileKeys.count > 0 { + manager.upload( + xMethod!, URLString, headers: nil, + multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as NSURL: + mpForm.appendBodyPart(fileURL: fileURL, name: k) + break + case let string as NSString: + mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + case let number as NSNumber: + mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, + encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let upload, _, _): + self.processRequest(upload, managerId, completion) + case .Failure(let encodingError): + completion(response: nil, erorr: encodingError) + } + } + ) + } else { + processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + } + + } + + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, erorr: NSError?) -> Void) { if let credential = self.credential { request.authenticate(usingCredential: credential) } @@ -66,7 +106,7 @@ class AlamofireRequestBuilder: RequestBuilder { completion(response: response, erorr: nil) return } - + completion(response: nil, erorr: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) } } diff --git a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache index af74617bcf2..f7838edf7ca 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache @@ -1,2 +1,2 @@ -github "Alamofire/Alamofire" >= 1.2 +github "Alamofire/Alamofire" >= 1.3 github "mxcl/PromiseKit" >=1.5.3 diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache new file mode 100644 index 00000000000..7b1ed59de8b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -0,0 +1,20 @@ +Pod::Spec.new do |s| + s.name = '{{projectName}}'{{#projectDescription}} + s.summary = '{{projectDescription}}'{{/projectDescription}} + s.ios.deployment_target = '8.0' + s.osx.deployment_target = '10.9' + s.version = '{{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}0.0.1{{/podVersion}}' + s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }{{/podSource}}{{#podAuthors}} + s.authors = {{& podAuthors}}{{/podAuthors}}{{#podSocialMediaURL}} + s.social_media_url = '{{podSocialMediaURL}}'{{/podSocialMediaURL}}{{#podDocsetURL}} + s.docset_url = '{{podDocsetURL}}'{{/podDocsetURL}} + s.license = {{#podLicense}}{{& podLicense}}{{/podLicense}}{{^podLicense}}'Apache License, Version 2.0'{{/podLicense}}{{#podHomepage}} + s.homepage = '{{podHomepage}}'{{/podHomepage}}{{#podSummary}} + s.summary = '{{podSummary}}'{{/podSummary}}{{#podDescription}} + s.description = '{{podDescription}}'{{/podDescription}}{{#podScreenshots}} + s.screenshots = {{& podScreenshots}}{{/podScreenshots}}{{#podDocumentationURL}} + s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} + s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift' + s.dependency 'PromiseKit', '~> 2.1' + s.dependency 'Alamofire', '~> 1.3' +end diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index cdc2395dc03..7595a1fa81d 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -35,7 +35,7 @@ extension {{projectName}}API { public class func {{operationId}}({{#allParams}}{{^secondaryParam}}#{{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{path}}"{{#pathParams}} path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}})", options: .LiteralSearch, range: nil){{/pathParams}} - let url = {{projectName}}API.basePath + path + let URLString = {{projectName}}API.basePath + path {{#bodyParam}} let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} let nillableParameters: [String:AnyObject?] = {{^queryParams}}{{^formParams}}[:]{{/formParams}}{{#formParams}}{{^secondaryParam}}[{{/secondaryParam}} @@ -47,7 +47,7 @@ extension {{projectName}}API { let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() - return requestBuilder(method: "{{httpMethod}}", URLString: url, parameters: parameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) + return requestBuilder(method: "{{httpMethod}}", URLString: URLString, parameters: parameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) } {{/operation}} } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h index 56c6adf30f2..ada8035e579 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h @@ -5,13 +5,18 @@ #import "SWGJSONRequestSerializer.h" #import "SWGQueryParamCollection.h" #import "SWGConfiguration.h" - -#import "SWGUser.h" -#import "SWGCategory.h" -#import "SWGPet.h" -#import "SWGTag.h" -#import "SWGOrder.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#import "SWGUser.h" +#import "SWGCategory.h" +#import "SWGPet.h" +#import "SWGTag.h" +#import "SWGOrder.h" /** @@ -29,7 +34,7 @@ extern NSString *const SWGResponseObjectErrorKey; @property(nonatomic, readonly) NSOperationQueue* queue; /** - * Get the Api Client instance from pool + * Gets the Api Client instance from pool * * @param baseUrl The base url of api client. * @@ -38,68 +43,68 @@ extern NSString *const SWGResponseObjectErrorKey; +(SWGApiClient *)sharedClientFromPool:(NSString *)baseUrl; /** - * Get the operations queue + * Gets the operations queue * * @return The `shardQueue` static variable. */ +(NSOperationQueue*) sharedQueue; /** - * Clear Cache + * Clears Cache */ +(void)clearCache; /** - * Turn on cache + * Turns on cache * * @param enabled If the cached is enable, must be `YES` or `NO` */ +(void)setCacheEnabled:(BOOL) enabled; /** - * Get the request queue size + * Gets the request queue size * * @return The size of `queuedRequests` static variable. */ +(unsigned long)requestQueueSize; /** - * Set the client unreachable + * Sets the client unreachable * - * @param state off line state, must be `YES` or `NO` + * @param state off line state, must be `YES` or `NO` */ +(void) setOfflineState:(BOOL) state; /** - * Get the client reachability + * Gets the client reachability * * @return The client reachability. */ +(AFNetworkReachabilityStatus) getReachabilityStatus; /** - * Get the next request id + * Gets the next request id * * @return The next executed request id. */ +(NSNumber*) nextRequestId; /** - * Generate request id and add it to the queue + * Generates request id and add it to the queue * * @return The next executed request id. */ +(NSNumber*) queueRequest; /** - * Remove request id from the queue + * Removes request id from the queue * * @param requestId The request which will be removed. */ +(void) cancelRequest:(NSNumber*)requestId; /** - * URL encode NSString + * Gets URL encoded NSString * * @param unescaped The string which will be escaped. * @@ -108,21 +113,21 @@ extern NSString *const SWGResponseObjectErrorKey; +(NSString*) escape:(id)unescaped; /** - * Customize the behavior when the reachability changed + * Customizes the behavior when the reachability changed * * @param changeBlock The block will be executed when the reachability changed. */ +(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; /** - * Set the client reachability strategy + * Sets the client reachability strategy * * @param host The host of SWGApiClient. */ +(void) configureCacheReachibilityForHost:(NSString*)host; /** - * Detect Accept header from accepts NSArray + * Detects Accept header from accepts NSArray * * @param accepts NSArray of header * @@ -131,7 +136,7 @@ extern NSString *const SWGResponseObjectErrorKey; +(NSString *) selectHeaderAccept:(NSArray *)accepts; /** - * Detect Content-Type header from contentTypes NSArray + * Detects Content-Type header from contentTypes NSArray * * @param contentTypes NSArray of header * @@ -140,7 +145,7 @@ extern NSString *const SWGResponseObjectErrorKey; +(NSString *) selectHeaderContentType:(NSArray *)contentTypes; /** - * Set header for request + * Sets header for request * * @param value The header value * @param forKey The header key @@ -149,7 +154,7 @@ extern NSString *const SWGResponseObjectErrorKey; forKey:(NSString*) forKey; /** - * Update header parameters and query parameters for authentication + * Updates header parameters and query parameters for authentication * * @param headers The header parameter will be udpated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. @@ -160,7 +165,7 @@ extern NSString *const SWGResponseObjectErrorKey; WithAuthSettings:(NSArray *)authSettings; /** - * Deserialize the given data to Objective-C object. + * Deserializes the given data to Objective-C object. * * @param data The data will be deserialized. * @param class The type of objective-c object. @@ -168,7 +173,7 @@ extern NSString *const SWGResponseObjectErrorKey; - (id) deserialize:(id) data class:(NSString *) class; /** - * Logging request and response + * Logs request and response * * @param operation AFHTTPRequestOperation for the HTTP request. * @param request The HTTP request. @@ -179,7 +184,7 @@ extern NSString *const SWGResponseObjectErrorKey; error:(NSError *)error; /** - * Perform request + * Performs request * * @param path Request url. * @param method Request method. @@ -189,7 +194,7 @@ extern NSString *const SWGResponseObjectErrorKey; * @param authSettings Request authentication names. * @param requestContentType Request content-type. * @param responseContentType Response content-type. - * @param completionBlock The block will be executed when the request completed. + * @param completionBlock The block will be executed when the request completed. * * @return The request id. */ diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.h b/samples/client/petstore/objc/SwaggerClient/SWGCategory.h index a2fed79b4a3..983fd610123 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGCategory.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGCategory.h @@ -1,10 +1,17 @@ #import #import "SWGObject.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + + @protocol SWGCategory @end - + @interface SWGCategory : SWGObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m index c41f76a5247..fb3ccecf176 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGCategory.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGCategory.m @@ -1,12 +1,21 @@ #import "SWGCategory.h" @implementation SWGCategory - + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"name"]; @@ -19,4 +28,12 @@ } } +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h index d3619c72ab5..0ccbe0cd8f6 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h @@ -1,26 +1,36 @@ #import +/** The `SWGConfiguration` class manages the configurations for the sdk. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ @interface SWGConfiguration : NSObject /** * Api key values for Api Key type Authentication * - * To add or remove api key, use `setValue:forApiKeyField:`. + * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. */ @property (readonly, nonatomic, strong) NSDictionary *apiKey; /** * Api key prefix values to be prepend to the respective api key * - * To add or remove prefix, use `setValue:forApiKeyPrefixField:`. + * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. */ @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; /** - * Usename and Password for Basic type Authentication + * Usename for HTTP Basic Authentication + */ + @property (nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication */ -@property (nonatomic) NSString *username; @property (nonatomic) NSString *password; /** @@ -31,37 +41,74 @@ /** * Logging Settings */ -@property (nonatomic) BOOL debug; -@property (nonatomic) NSString *loggingFile; -@property (nonatomic) NSFileHandle *loggingFileHanlder; /** - * Get configuration singleton instance + * Debug switch, default false + */ +@property (nonatomic) BOOL debug; + +/** + * Debug file location, default log in console + */ +@property (nonatomic) NSString *loggingFile; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; + +/** + * Gets configuration singleton instance */ + (instancetype) sharedConfig; /** - * Sets field in `apiKey` + * Sets API key + * + * To remove a apiKey for an identifier, just set the apiKey to nil. + * + * @param apiKey API key or token. + * @param identifier API key identifier (authentication schema). + * */ -- (void) setValue:(NSString *)value forApiKeyField:(NSString*)field; +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; /** - * Sets field in `apiKeyPrefix` + * Removes api key + * + * @param identifier API key identifier. */ -- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field; +- (void) removeApiKey:(NSString *)identifier; /** - * Get API key (with prefix if set) + * Sets the prefix for API key + * + * To remove a apiKeyPrefix for an identifier, just set the apiKeyPrefix to nil. + * + * @param apiKeyPrefix API key prefix. + * @param identifier API key identifier. + */ +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; + +/** + * Removes api key prefix + * + * @param identifier API key identifier. + */ +- (void) removeApiKeyPrefix:(NSString *)identifier; + +/** + * Gets API key (with prefix if set) */ - (NSString *) getApiKeyWithPrefix:(NSString *) key; /** - * Get Basic Auth token + * Gets Basic Auth token */ - (NSString *) getBasicAuthToken; /** - * Get Authentication Setings + * Gets Authentication Setings */ - (NSDictionary *) authSettings; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m index 81e308a53fc..0e0e70e27ea 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m @@ -60,12 +60,20 @@ #pragma mark - Setter Methods -- (void) setValue:(NSString *)value forApiKeyField:(NSString *)field { - [self.mutableApiKey setValue:value forKey:field]; +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { + [self.mutableApiKey setValue:apiKey forKey:identifier]; } -- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field { - [self.mutableApiKeyPrefix setValue:value forKey:field]; +- (void) removeApiKey:(NSString *)identifier { + [self.mutableApiKey removeObjectForKey:identifier]; +} + +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier { + [self.mutableApiKeyPrefix setValue:prefix forKey:identifier]; +} + +- (void) removeApiKeyPrefix:(NSString *)identifier { + [self.mutableApiKeyPrefix removeObjectForKey:identifier]; } - (void) setLoggingFile:(NSString *)loggingFile { @@ -75,10 +83,10 @@ } _loggingFile = loggingFile; - self.loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; - if (self.loggingFileHanlder == nil) { + _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHanlder == nil) { [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; - self.loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; } } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.h b/samples/client/petstore/objc/SwaggerClient/SWGOrder.h index 2e71906cd53..48a7cf0d6c1 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.h @@ -1,10 +1,17 @@ #import #import "SWGObject.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + + @protocol SWGOrder @end - + @interface SWGOrder : SWGObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m index 5d3179446ed..83fe5741cd7 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m @@ -1,12 +1,21 @@ #import "SWGOrder.h" @implementation SWGOrder - + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"complete"]; @@ -19,4 +28,12 @@ } } +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.h b/samples/client/petstore/objc/SwaggerClient/SWGPet.h index edd54e9f31a..d78baade81a 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.h @@ -1,12 +1,19 @@ #import #import "SWGObject.h" + +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + #import "SWGTag.h" #import "SWGCategory.h" @protocol SWGPet @end - + @interface SWGPet : SWGObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.m b/samples/client/petstore/objc/SwaggerClient/SWGPet.m index d5559aa6f72..3fd315ab011 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.m @@ -1,12 +1,21 @@ #import "SWGPet.h" @implementation SWGPet - + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"category": @"category", @"name": @"name", @"photoUrls": @"photoUrls", @"tags": @"tags", @"status": @"status" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"category", @"tags", @"status"]; @@ -19,4 +28,12 @@ } } +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h index 39f23edb028..929b16eab1f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h @@ -4,6 +4,12 @@ #import "SWGApiClient.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + @interface SWGPetApi: NSObject @property(nonatomic, assign)SWGApiClient *apiClient; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h index 7488c1baa70..7b4f99dea7b 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h @@ -4,6 +4,12 @@ #import "SWGApiClient.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + @interface SWGStoreApi: NSObject @property(nonatomic, assign)SWGApiClient *apiClient; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.h b/samples/client/petstore/objc/SwaggerClient/SWGTag.h index d9cc84be270..97e95807550 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGTag.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGTag.h @@ -1,10 +1,17 @@ #import #import "SWGObject.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + + @protocol SWGTag @end - + @interface SWGTag : SWGObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGTag.m b/samples/client/petstore/objc/SwaggerClient/SWGTag.m index 5d48a099070..3bcb9973dfd 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGTag.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGTag.m @@ -1,12 +1,21 @@ #import "SWGTag.h" @implementation SWGTag - + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"name"]; @@ -19,4 +28,12 @@ } } +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.h b/samples/client/petstore/objc/SwaggerClient/SWGUser.h index f505ca2c041..6ba19e632b8 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUser.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGUser.h @@ -1,10 +1,17 @@ #import #import "SWGObject.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + + @protocol SWGUser @end - + @interface SWGUser : SWGObject diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUser.m b/samples/client/petstore/objc/SwaggerClient/SWGUser.m index 060b65ffa12..d040a6bce6d 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUser.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUser.m @@ -1,12 +1,21 @@ #import "SWGUser.h" @implementation SWGUser - + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"username": @"username", @"firstName": @"firstName", @"lastName": @"lastName", @"email": @"email", @"password": @"password", @"phone": @"phone", @"userStatus": @"userStatus" }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[@"_id", @"username", @"firstName", @"lastName", @"email", @"password", @"phone", @"userStatus"]; @@ -19,4 +28,12 @@ } } +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h index 6fda87cca70..9a3dfd9d23d 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h @@ -4,6 +4,12 @@ #import "SWGApiClient.h" +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + @interface SWGUserApi: NSObject @property(nonatomic, assign)SWGApiClient *apiClient; diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 0ba21c560ef..a5fe06f63b7 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -23,6 +23,8 @@ 6003F5BC195388D20070C39A /* Tests.m in Sources */ = {isa = PBXBuildFile; fileRef = 6003F5BB195388D20070C39A /* Tests.m */; }; 873B8AEB1B1F5CCA007FD442 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 873B8AEA1B1F5CCA007FD442 /* Main.storyboard */; }; 94BE6BE84795B5034A811E61 /* libPods-SwaggerClient_Example.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 8D46325ECAD48245C07F6733 /* libPods-SwaggerClient_Example.a */; }; + CF0ADB481B5F95D6008A2729 /* PetTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF0ADB471B5F95D6008A2729 /* PetTest.m */; }; + CF8F71391B5F73AC00162980 /* DeserializationTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF8F71381B5F73AC00162980 /* DeserializationTest.m */; }; CFDFB4121B3CFFA8009739C5 /* UserApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CFDFB40D1B3CFEC3009739C5 /* UserApiTest.m */; }; CFDFB4131B3CFFDD009739C5 /* PetApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CFDFB40A1B3CFEC3009739C5 /* PetApiTest.m */; }; CFDFB4141B3CFFF6009739C5 /* StoreApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CFDFB40B1B3CFEC3009739C5 /* StoreApiTest.m */; }; @@ -65,6 +67,8 @@ 873B8AEA1B1F5CCA007FD442 /* Main.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = Main.storyboard; sourceTree = ""; }; 8D46325ECAD48245C07F6733 /* libPods-SwaggerClient_Example.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-SwaggerClient_Example.a"; sourceTree = BUILT_PRODUCTS_DIR; }; BFB4BE760737508B3CFC23B2 /* Pods-SwaggerClient_Example.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SwaggerClient_Example.release.xcconfig"; path = "Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example.release.xcconfig"; sourceTree = ""; }; + CF0ADB471B5F95D6008A2729 /* PetTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PetTest.m; sourceTree = ""; }; + CF8F71381B5F73AC00162980 /* DeserializationTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DeserializationTest.m; sourceTree = ""; }; CFDFB40A1B3CFEC3009739C5 /* PetApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PetApiTest.m; sourceTree = ""; }; CFDFB40B1B3CFEC3009739C5 /* StoreApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = StoreApiTest.m; sourceTree = ""; }; CFDFB40C1B3CFEC3009739C5 /* SWGApiClientTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiClientTest.m; sourceTree = ""; }; @@ -166,6 +170,8 @@ CFDFB40A1B3CFEC3009739C5 /* PetApiTest.m */, CFDFB40B1B3CFEC3009739C5 /* StoreApiTest.m */, CFDFB40C1B3CFEC3009739C5 /* SWGApiClientTest.m */, + CF0ADB471B5F95D6008A2729 /* PetTest.m */, + CF8F71381B5F73AC00162980 /* DeserializationTest.m */, CFDFB40D1B3CFEC3009739C5 /* UserApiTest.m */, 6003F5BB195388D20070C39A /* Tests.m */, 6003F5B6195388D20070C39A /* Supporting Files */, @@ -374,10 +380,12 @@ buildActionMask = 2147483647; files = ( CFDFB4141B3CFFF6009739C5 /* StoreApiTest.m in Sources */, + CF0ADB481B5F95D6008A2729 /* PetTest.m in Sources */, CFDFB4131B3CFFDD009739C5 /* PetApiTest.m in Sources */, 6003F5BC195388D20070C39A /* Tests.m in Sources */, CFDFB4151B3D000B009739C5 /* SWGApiClientTest.m in Sources */, CFDFB4121B3CFFA8009739C5 /* UserApiTest.m in Sources */, + CF8F71391B5F73AC00162980 /* DeserializationTest.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m index a56f31408aa..5fe98be055f 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m @@ -7,6 +7,8 @@ // #import "SWGViewController.h" +#import +#import @interface SWGViewController () @@ -17,13 +19,41 @@ - (void)viewDidLoad { [super viewDidLoad]; - // Do any additional setup after loading the view, typically from a nib. + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + [config setApiKey:@"hello" forApiKeyIdentifier:@"world"]; + [config setApiKey:@"geekerzp" forApiKeyIdentifier:@"zp"]; + [config removeApiKey:@"zp"]; + NSLog(@"%@", config.apiKey); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; - // Dispose of any resources that can be recreated. +} + +- (SWGPet*) createPet { + SWGPet * pet = [[SWGPet alloc] init]; + pet._id = [[NSNumber alloc] initWithLong:[[NSDate date] timeIntervalSince1970]]; + pet.name = @"monkey"; + + SWGCategory * category = [[SWGCategory alloc] init]; + category._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; + category.name = @"super-happy"; + pet.category = category; + + SWGTag *tag1 = [[SWGTag alloc] init]; + tag1._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; + tag1.name = @"test tag 1"; + SWGTag *tag2 = [[SWGTag alloc] init]; + tag2._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; + tag2.name = @"test tag 2"; + pet.tags = (NSArray *)[[NSArray alloc] initWithObjects:tag1, tag2, nil]; + + pet.status = @"available"; + + NSArray * photos = [[NSArray alloc] initWithObjects:@"http://foo.bar.com/3", @"http://foo.bar.com/4", nil]; + pet.photoUrls = photos; + return pet; } @end diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m new file mode 100644 index 00000000000..2650dde31d0 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m @@ -0,0 +1,119 @@ +#import +#import +#import +#import + +@interface DeserializationTest : XCTestCase { + +@private SWGApiClient *apiClient; + +} + +@end + +@implementation DeserializationTest + +- (void)setUp { + [super setUp]; + apiClient = [[SWGApiClient alloc] init]; +} + +- (void)testDeserializeDate { + NSString *dateStr = @"2012-09-27"; + + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + NSTimeZone *timezone = [NSTimeZone timeZoneWithName:@"UTC"]; + [formatter setTimeZone:timezone]; + [formatter setDateFormat:@"yyyy-MM-dd"]; + NSDate *date = [formatter dateFromString:dateStr]; + + NSDate *deserializedDate = [apiClient deserialize:dateStr class:@"NSDate*"]; + + XCTAssertEqualWithAccuracy([date timeIntervalSinceReferenceDate], [deserializedDate timeIntervalSinceReferenceDate], 0.001); +} + +- (void)testDeserializeDateTime { + NSString *dateTimeStr = @"1997-07-16T19:20:30+00:00"; + + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; + NSDate *dateTime = [formatter dateFromString:dateTimeStr]; + + NSDate *deserializedDateTime = [apiClient deserialize:dateTimeStr class:@"NSDate*"]; + + XCTAssertEqualWithAccuracy([dateTime timeIntervalSinceReferenceDate], [deserializedDateTime timeIntervalSinceReferenceDate], 0.001); +} + +- (void)testDeserializeObject { + XCTAssertTrue([[apiClient deserialize:@"" class:@"NSObject*"] isKindOfClass:[NSObject class]]); +} + +- (void)testDeserializeString { + NSString *data = @"test string"; + NSString *result = [apiClient deserialize:data class:@"NSString*"]; + + XCTAssertTrue([result isEqualToString:data]); +} + +- (void)testDeserializeListOfModels { + NSArray *data = + @[ + @{ + @"id": @119, + @"category": @{ + @"id": @0, + @"name": @"string" + }, + @"name": @"doggie", + @"photoUrls": @[ + @"string" + ], + @"tags": @[ + @{ + @"id": @0, + @"name": @"string" + } + ], + @"status": @"available" + + }]; + + NSArray *result = [apiClient deserialize:data class:@"NSArray*"]; + + XCTAssertTrue([result isKindOfClass:[NSArray class]]); + XCTAssertTrue([[result firstObject] isKindOfClass:[SWGPet class]]); + XCTAssertEqualObjects([[result firstObject] _id], @119); +} + +- (void)testDeserializeMapOfModels { + NSDictionary *data = + @{ + @"pet": @{ + @"id": @119, + @"category": @{ + @"id": @0, + @"name": @"string" + }, + @"name": @"doggie", + @"photoUrls": @[ + @"string" + ], + @"tags": @[ + @{ + @"id": @0, + @"name": @"string" + } + ], + @"status": @"available" + + } + }; + + NSDictionary *result = [apiClient deserialize:data class:@"NSDictionary* /* NSString, SWGPet */"]; + + XCTAssertTrue([result isKindOfClass:[NSDictionary class]]); + XCTAssertTrue([result[@"pet"] isKindOfClass:[SWGPet class]]); + XCTAssertEqualObjects([result[@"pet"] _id], @119); +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetTest.m new file mode 100644 index 00000000000..9dbde13310b --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetTest.m @@ -0,0 +1,37 @@ +#import +#import +#import + +@interface PetTest : XCTestCase { + +@private SWGPet *pet; + +} + +@end + +@implementation PetTest + +- (void)setUp { + [super setUp]; + + NSDictionary *petDict = @{ @"id": @1, @"name": @"test pet", + @"status": @"sold", + @"photoUrls": @[@"string"], + @"category": @{ @"id": @1, @"name": @"test category" }, + @"tags": @[ @{ @"id": @1, @"name": @"test tag" } ]}; + pet = [[SWGPet alloc] initWithDictionary:petDict error:nil]; +} + +- (void)testDescription { + NSDictionary *petDict = @{ @"id": @1, @"name": @"test pet", + @"status": @"sold", + @"photoUrls": @[@"string"], + @"category": @{ @"id": @1, @"name": @"test category" }, + @"tags": @[ @{ @"id": @1, @"name": @"test tag" } ]}; + NSString *petStr = [petDict description]; + + XCTAssertTrue([[pet description] isEqualToString:petStr]); +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m index 00c6bf70da6..d19180dc008 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/SWGApiClientTest.m @@ -61,8 +61,8 @@ - (void)testConfiguration { SWGConfiguration *config = [SWGConfiguration sharedConfig]; - [config setValue:@"123456" forApiKeyField:@"api_key"]; - [config setValue:@"PREFIX" forApiKeyPrefixField:@"api_key"]; + [config setApiKey:@"123456" forApiKeyIdentifier:@"api_key"]; + [config setApiKeyPrefix:@"PREFIX" forApiKeyPrefixIdentifier:@"api_key"]; config.username = @"test_username"; config.password = @"test_password"; @@ -98,77 +98,4 @@ XCTAssertEqualObjects(basicAuthCredentials, [config getBasicAuthToken]); } -- (void)testDeserialize { - id data; - id result; - - // list of models - data = - @[ - @{ - @"id": @119, - @"category": @{ - @"id": @0, - @"name": @"string" - }, - @"name": @"doggie", - @"photoUrls": @[ - @"string" - ], - @"tags": @[ - @{ - @"id": @0, - @"name": @"string" - } - ], - @"status": @"available" - - }]; - result = [self.apiClient deserialize:data class:@"NSArray*"]; - - XCTAssertTrue([result isKindOfClass:[NSArray class]]); - XCTAssertTrue([[result firstObject] isKindOfClass:[SWGPet class]]); - XCTAssertEqualObjects([[result firstObject] _id], @119); - - // map of models - data = - @{ - @"pet": @{ - @"id": @119, - @"category": @{ - @"id": @0, - @"name": @"string" - }, - @"name": @"doggie", - @"photoUrls": @[ - @"string" - ], - @"tags": @[ - @{ - @"id": @0, - @"name": @"string" - } - ], - @"status": @"available" - - } - }; - result = [self.apiClient deserialize:data class:@"NSDictionary* /* NSString, SWGPet */"]; - - XCTAssertTrue([result isKindOfClass:[NSDictionary class]]); - XCTAssertTrue([result[@"pet"] isKindOfClass:[SWGPet class]]); - XCTAssertEqualObjects([result[@"pet"] _id], @119); - - // pure object - result = [self.apiClient deserialize:@"" class:@"NSObject*"]; - - XCTAssertTrue([result isKindOfClass:[NSObject class]]); - - // NSString - data = @"test string"; - result = [self.apiClient deserialize:data class:@"NSString*"]; - - XCTAssertTrue([result isKindOfClass:[NSString class]]); -} - @end diff --git a/samples/client/petstore/typescript-angular/.gitignore b/samples/client/petstore/typescript-angular/.gitignore new file mode 100644 index 00000000000..abfad1bf5e2 --- /dev/null +++ b/samples/client/petstore/typescript-angular/.gitignore @@ -0,0 +1,3 @@ +/node_modules +/typings +/client.js \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular/api/Category.ts b/samples/client/petstore/typescript-angular/API/Client/Category.ts similarity index 87% rename from samples/client/petstore/typescript-angular/api/Category.ts rename to samples/client/petstore/typescript-angular/API/Client/Category.ts index e4a3caa208e..7faf87208eb 100644 --- a/samples/client/petstore/typescript-angular/api/Category.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Category.ts @@ -1,6 +1,6 @@ /// -module api { +module API.Client { 'use strict'; export class Category { diff --git a/samples/client/petstore/typescript-angular/api/Order.ts b/samples/client/petstore/typescript-angular/API/Client/Order.ts similarity index 91% rename from samples/client/petstore/typescript-angular/api/Order.ts rename to samples/client/petstore/typescript-angular/API/Client/Order.ts index 3f37c608758..abee3a2894b 100644 --- a/samples/client/petstore/typescript-angular/api/Order.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Order.ts @@ -1,6 +1,6 @@ /// -module api { +module API.Client { 'use strict'; export class Order { @@ -11,7 +11,7 @@ module api { quantity: number; - shipDate: DateTime; + shipDate: Date; /** * Order Status diff --git a/samples/client/petstore/typescript-angular/api/Pet.ts b/samples/client/petstore/typescript-angular/API/Client/Pet.ts similarity index 96% rename from samples/client/petstore/typescript-angular/api/Pet.ts rename to samples/client/petstore/typescript-angular/API/Client/Pet.ts index c34be9c3dbc..9523bef90b0 100644 --- a/samples/client/petstore/typescript-angular/api/Pet.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Pet.ts @@ -1,6 +1,6 @@ /// -module api { +module API.Client { 'use strict'; export class Pet { diff --git a/samples/client/petstore/typescript-angular/api/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts similarity index 74% rename from samples/client/petstore/typescript-angular/api/PetApi.ts rename to samples/client/petstore/typescript-angular/API/Client/PetApi.ts index d294cfbebbc..6bb4e10d387 100644 --- a/samples/client/petstore/typescript-angular/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -2,12 +2,11 @@ /* tslint:disable:no-unused-variable member-ordering */ -module api { +module API.Client { 'use strict'; - export class PetApi { - private basePath = 'http://petstore.swagger.io/v2'; + private basePath = '/v2'; static $inject: string[] = ['$http']; @@ -16,15 +15,13 @@ module api { this.basePath = basePath; } } - - public updatePet (body: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public updatePet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'PUT', url: path, @@ -32,11 +29,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -45,15 +42,13 @@ module api { return this.$http(httpRequestParams); } - - public addPet (body: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public addPet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -61,11 +56,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -74,28 +69,28 @@ module api { return this.$http(httpRequestParams); } - - public findPetsByStatus (status: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { + + public findPetsByStatus (status?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { var path = this.basePath + '/pet/findByStatus'; - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + if (status !== undefined) { queryParameters['status'] = status; } - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -104,28 +99,28 @@ module api { return this.$http(httpRequestParams); } - - public findPetsByTags (tags: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { + + public findPetsByTags (tags?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { var path = this.basePath + '/pet/findByTags'; - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + if (tags !== undefined) { queryParameters['tags'] = tags; } - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -134,33 +129,31 @@ module api { return this.$http(httpRequestParams); } - - public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/pet/{petId}'; - + path = path.replace('{' + 'petId' + '}', String(petId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling getPetById'); } - - - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -169,33 +162,31 @@ module api { return this.$http(httpRequestParams); } - - public updatePetWithForm (petId: string, name: string, status: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public updatePetWithForm (petId: string, name?: string, status?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet/{petId}'; - + path = path.replace('{' + 'petId' + '}', String(petId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling updatePetWithForm'); } - - - + var httpRequestParams: any = { method: 'POST', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -204,33 +195,33 @@ module api { return this.$http(httpRequestParams); } - - public deletePet (apiKey: string, petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet/{petId}'; - + path = path.replace('{' + 'petId' + '}', String(petId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling deletePet'); } - - + headerParams['apiKey'] = apiKey; + var httpRequestParams: any = { method: 'DELETE', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -239,33 +230,31 @@ module api { return this.$http(httpRequestParams); } - - public uploadFile (petId: number, additionalMetadata: string, file: file, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public uploadFile (petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/pet/{petId}/uploadImage'; - + path = path.replace('{' + 'petId' + '}', String(petId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling uploadFile'); } - - - + var httpRequestParams: any = { method: 'POST', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -274,9 +263,5 @@ module api { return this.$http(httpRequestParams); } - } - - angular.module('api_PetApi', ['$http']) - .service('PetApi', PetApi); } diff --git a/samples/client/petstore/typescript-angular/api/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts similarity index 72% rename from samples/client/petstore/typescript-angular/api/StoreApi.ts rename to samples/client/petstore/typescript-angular/API/Client/StoreApi.ts index e8c85b00c45..948b6859381 100644 --- a/samples/client/petstore/typescript-angular/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -2,12 +2,11 @@ /* tslint:disable:no-unused-variable member-ordering */ -module api { +module API.Client { 'use strict'; - export class StoreApi { - private basePath = 'http://petstore.swagger.io/v2'; + private basePath = '/v2'; static $inject: string[] = ['$http']; @@ -16,26 +15,24 @@ module api { this.basePath = basePath; } } - - public getInventory ( extraHttpRequestParams?: any ) : ng.IHttpPromise> { + + public getInventory (extraHttpRequestParams?: any ) : ng.IHttpPromise<{ [key: string]: number; }> { var path = this.basePath + '/store/inventory'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -44,15 +41,13 @@ module api { return this.$http(httpRequestParams); } - - public placeOrder (body: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public placeOrder (body?: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/store/order'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -60,11 +55,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -73,33 +68,31 @@ module api { return this.$http(httpRequestParams); } - - public getOrderById (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public getOrderById (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/store/order/{orderId}'; - + path = path.replace('{' + 'orderId' + '}', String(orderId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling getOrderById'); } - - - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -108,33 +101,31 @@ module api { return this.$http(httpRequestParams); } - - public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/store/order/{orderId}'; - + path = path.replace('{' + 'orderId' + '}', String(orderId)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling deleteOrder'); } - - - + var httpRequestParams: any = { method: 'DELETE', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -143,9 +134,5 @@ module api { return this.$http(httpRequestParams); } - } - - angular.module('api_StoreApi', ['$http']) - .service('StoreApi', StoreApi); } diff --git a/samples/client/petstore/typescript-angular/api/Tag.ts b/samples/client/petstore/typescript-angular/API/Client/Tag.ts similarity index 86% rename from samples/client/petstore/typescript-angular/api/Tag.ts rename to samples/client/petstore/typescript-angular/API/Client/Tag.ts index 33f0ffaa1e2..2ec9b456f27 100644 --- a/samples/client/petstore/typescript-angular/api/Tag.ts +++ b/samples/client/petstore/typescript-angular/API/Client/Tag.ts @@ -1,6 +1,6 @@ /// -module api { +module API.Client { 'use strict'; export class Tag { diff --git a/samples/client/petstore/typescript-angular/api/User.ts b/samples/client/petstore/typescript-angular/API/Client/User.ts similarity index 94% rename from samples/client/petstore/typescript-angular/api/User.ts rename to samples/client/petstore/typescript-angular/API/Client/User.ts index 57385044943..ca8ac57c7a3 100644 --- a/samples/client/petstore/typescript-angular/api/User.ts +++ b/samples/client/petstore/typescript-angular/API/Client/User.ts @@ -1,6 +1,6 @@ /// -module api { +module API.Client { 'use strict'; export class User { diff --git a/samples/client/petstore/typescript-angular/api/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts similarity index 73% rename from samples/client/petstore/typescript-angular/api/UserApi.ts rename to samples/client/petstore/typescript-angular/API/Client/UserApi.ts index 40d82f73852..eb04f4b31f0 100644 --- a/samples/client/petstore/typescript-angular/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -2,12 +2,11 @@ /* tslint:disable:no-unused-variable member-ordering */ -module api { +module API.Client { 'use strict'; - export class UserApi { - private basePath = 'http://petstore.swagger.io/v2'; + private basePath = '/v2'; static $inject: string[] = ['$http']; @@ -16,15 +15,13 @@ module api { this.basePath = basePath; } } - - public createUser (body: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public createUser (body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -32,11 +29,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -45,15 +42,13 @@ module api { return this.$http(httpRequestParams); } - - public createUsersWithArrayInput (body: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public createUsersWithArrayInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/createWithArray'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -61,11 +56,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -74,15 +69,13 @@ module api { return this.$http(httpRequestParams); } - - public createUsersWithListInput (body: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public createUsersWithListInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/createWithList'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'POST', url: path, @@ -90,11 +83,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -103,30 +96,32 @@ module api { return this.$http(httpRequestParams); } - - public loginUser (username: string, password: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public loginUser (username?: string, password?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/user/login'; - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + if (username !== undefined) { queryParameters['username'] = username; - }if (password !== undefined) { + } + + if (password !== undefined) { queryParameters['password'] = password; } - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -135,26 +130,24 @@ module api { return this.$http(httpRequestParams); } - - public logoutUser ( extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public logoutUser (extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/logout'; - + var queryParameters: any = {}; - var headers: any = {}; - - - + var headerParams: any = {}; + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -163,33 +156,31 @@ module api { return this.$http(httpRequestParams); } - - public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + + public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { var path = this.basePath + '/user/{username}'; - + path = path.replace('{' + 'username' + '}', String(username)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling getUserByName'); } - - - + var httpRequestParams: any = { method: 'GET', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -198,22 +189,20 @@ module api { return this.$http(httpRequestParams); } - - public updateUser (username: string, body: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public updateUser (username: string, body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/{username}'; - + path = path.replace('{' + 'username' + '}', String(username)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling updateUser'); } - - - + var httpRequestParams: any = { method: 'PUT', url: path, @@ -221,11 +210,11 @@ module api { data: body, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -234,33 +223,31 @@ module api { return this.$http(httpRequestParams); } - - public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + + public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { var path = this.basePath + '/user/{username}'; - + path = path.replace('{' + 'username' + '}', String(username)); - + var queryParameters: any = {}; - var headers: any = {}; - + var headerParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling deleteUser'); } - - - + var httpRequestParams: any = { method: 'DELETE', url: path, json: true, params: queryParameters, - headers: headers + headers: headerParams }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } @@ -269,9 +256,5 @@ module api { return this.$http(httpRequestParams); } - } - - angular.module('api_UserApi', ['$http']) - .service('UserApi', UserApi); } diff --git a/samples/client/petstore/typescript-angular/api/api.d.ts b/samples/client/petstore/typescript-angular/API/Client/api.d.ts similarity index 100% rename from samples/client/petstore/typescript-angular/api/api.d.ts rename to samples/client/petstore/typescript-angular/API/Client/api.d.ts diff --git a/samples/client/petstore/typescript-angular/README.md b/samples/client/petstore/typescript-angular/README.md new file mode 100644 index 00000000000..3a4e49be9e8 --- /dev/null +++ b/samples/client/petstore/typescript-angular/README.md @@ -0,0 +1,19 @@ +# SwaggerClient + +Sample of TypeScript AngularJS petstore client + +## Testing the generated code + +``` +npm install +npm test +``` + +To clean the workspace run: +``` +npm run clean +``` + +## Author + +mads@maetzke-tandrup.dk \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular/package.json b/samples/client/petstore/typescript-angular/package.json new file mode 100644 index 00000000000..f50b782c09f --- /dev/null +++ b/samples/client/petstore/typescript-angular/package.json @@ -0,0 +1,20 @@ +{ + "name": "petstore-typescript-node-sample", + "version": "1.0.0", + "description": "Sample of generated TypeScript petstore client", + "main": "api.js", + "scripts": { + "postinstall": "tsd reinstall --overwrite", + "test": "tsc", + "clean": "rm -Rf node_modules/ typings/ *.js" + }, + "author": "Mads M. Tandrup", + "license": "Apache 2.0", + "dependencies": { + "angular": "^1.4.3" + }, + "devDependencies": { + "tsd": "^0.6.3", + "typescript": "^1.5.3" + } +} diff --git a/samples/client/petstore/typescript-angular/tsconfig.json b/samples/client/petstore/typescript-angular/tsconfig.json new file mode 100644 index 00000000000..c389d5011ff --- /dev/null +++ b/samples/client/petstore/typescript-angular/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "noImplicitAny": true, + "out": "client.js" + }, + "files": [ + "API/Client/Category.ts", + "API/Client/Pet.ts", + "API/Client/StoreApi.ts", + "API/Client/User.ts", + "API/Client/api.d.ts", + "API/Client/Order.ts", + "API/Client/PetApi.ts", + "API/Client/Tag.ts", + "API/Client/UserApi.ts", + "typings/tsd.d.ts" + ] +} diff --git a/samples/client/petstore/typescript-angular/tsd.json b/samples/client/petstore/typescript-angular/tsd.json new file mode 100644 index 00000000000..182b9f68fa2 --- /dev/null +++ b/samples/client/petstore/typescript-angular/tsd.json @@ -0,0 +1,15 @@ +{ + "version": "v4", + "repo": "borisyankov/DefinitelyTyped", + "ref": "master", + "path": "typings", + "bundle": "typings/tsd.d.ts", + "installed": { + "angularjs/angular.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + }, + "jquery/jquery.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + } + } +} diff --git a/samples/client/petstore/typescript-node/.gitignore b/samples/client/petstore/typescript-node/.gitignore new file mode 100644 index 00000000000..5c06ad7bc24 --- /dev/null +++ b/samples/client/petstore/typescript-node/.gitignore @@ -0,0 +1,3 @@ +/node_modules +/typings +/*.js diff --git a/samples/client/petstore/typescript-node/README.md b/samples/client/petstore/typescript-node/README.md new file mode 100644 index 00000000000..82225d3260a --- /dev/null +++ b/samples/client/petstore/typescript-node/README.md @@ -0,0 +1,22 @@ +# SwaggerClient + +Sample of TypeScript Node.js petstore client + +## Testing the generated code + +``` +npm install +npm test +``` + +This will compile the code and run a small test application that will do some simple test calls to the Swagger Petstore API. + +To clean the workspace run: +``` +npm run clean +``` + + +## Author + +mads@maetzke-tandrup.dk \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts new file mode 100644 index 00000000000..0b7089fdaae --- /dev/null +++ b/samples/client/petstore/typescript-node/api.ts @@ -0,0 +1,1199 @@ +import request = require('request'); +import promise = require('bluebird'); +import http = require('http'); + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + +/* tslint:disable:no-unused-variable */ + +export class User { + id: number; + username: string; + firstName: string; + lastName: string; + email: string; + password: string; + phone: string; + /** + * User Status + */ + userStatus: number; +} + +export class Category { + id: number; + name: string; +} + +export class Pet { + id: number; + category: Category; + name: string; + photoUrls: Array; + tags: Array; + /** + * pet status in the store + */ + status: Pet.StatusEnum; +} + +export module Pet { + export enum StatusEnum { + available = 'available', + pending = 'pending', + sold = 'sold', + } +} +export class Tag { + id: number; + name: string; +} + +export class Order { + id: number; + petId: number; + quantity: number; + shipDate: Date; + /** + * Order Status + */ + status: Order.StatusEnum; + complete: boolean; +} + +export module Order { + export enum StatusEnum { + placed = 'placed', + approved = 'approved', + delivered = 'delivered', + } +} + +interface Authentication { + /** + * Apply authentication settings to header and query params. + */ + applyToRequest(requestOptions: request.Options): void; +} + +class HttpBasicAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + requestOptions.auth = { + username: this.username, password: this.password + } + } +} + +class ApiKeyAuth implements Authentication { + public apiKey: string; + + constructor(private location: string, private paramName: string) { + } + + applyToRequest(requestOptions: request.Options): void { + if (this.location == "query") { + (requestOptions.qs)[this.paramName] = this.apiKey; + } else if (this.location == "header") { + requestOptions.headers[this.paramName] = this.apiKey; + } + } +} + +class OAuth implements Authentication { + applyToRequest(requestOptions: request.Options): void { + // TODO: support oauth + } +} + +class VoidAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + // Do nothing + } +} + +export class UserApi { + private basePath = '/v2'; + public authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } + + constructor(url: string, basePath?: string); + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + + public createUser (body?: User) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/createWithArray'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/createWithList'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { + var path = this.url + this.basePath + '/user/login'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + if (username !== undefined) { + queryParameters['username'] = username; + } + + if (password !== undefined) { + queryParameters['password'] = password; + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public logoutUser () : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/logout'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public getUserByName (username: string) : Promise<{ response: http.ClientResponse; body: User; }> { + var path = this.url + this.basePath + '/user/{username}'; + + path = path.replace('{' + 'username' + '}', String(username)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling getUserByName'); + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public updateUser (username: string, body?: User) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/{username}'; + + path = path.replace('{' + 'username' + '}', String(username)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling updateUser'); + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public deleteUser (username: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/user/{username}'; + + path = path.replace('{' + 'username' + '}', String(username)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'username' is set + if (!username) { + throw new Error('Missing required parameter username when calling deleteUser'); + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +} +export class PetApi { + private basePath = '/v2'; + public authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } + + constructor(url: string, basePath?: string); + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + + public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { + var path = this.url + this.basePath + '/pet/findByStatus'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + if (status !== undefined) { + queryParameters['status'] = status; + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { + var path = this.url + this.basePath + '/pet/findByTags'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + if (tags !== undefined) { + queryParameters['tags'] = tags; + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { + var path = this.url + this.basePath + '/pet/{petId}'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling getPetById'); + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.api_key.applyToRequest(requestOptions); + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public updatePetWithForm (petId: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling updatePetWithForm'); + } + + var useFormData = false; + + if (name !== undefined) { + formParams['name'] = name; + } + + if (status !== undefined) { + formParams['status'] = status; + } + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling deletePet'); + } + + headerParams['apiKey'] = apiKey; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public uploadFile (petId: number, additionalMetadata?: string, file?: any) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}/uploadImage'; + + path = path.replace('{' + 'petId' + '}', String(petId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling uploadFile'); + } + + var useFormData = false; + + if (additionalMetadata !== undefined) { + formParams['additionalMetadata'] = additionalMetadata; + } + + if (file !== undefined) { + formParams['file'] = file; + } + useFormData = true; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.petstore_auth.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +} +export class StoreApi { + private basePath = '/v2'; + public authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } + + constructor(url: string, basePath?: string); + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + + public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { + var path = this.url + this.basePath + '/store/inventory'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.api_key.applyToRequest(requestOptions); + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { + var path = this.url + this.basePath + '/store/order'; + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + var requestOptions: request.Options = { + method: 'POST', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + body: body, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { + var path = this.url + this.basePath + '/store/order/{orderId}'; + + path = path.replace('{' + 'orderId' + '}', String(orderId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling getOrderById'); + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + + var requestOptions: request.Options = { + method: 'GET', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } + + public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/store/order/{orderId}'; + + path = path.replace('{' + 'orderId' + '}', String(orderId)); + + var queryParameters: any = {}; + var headerParams: any = {}; + var formParams: any = {}; + + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); + } + + var useFormData = false; + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); + + var requestOptions: request.Options = { + method: 'DELETE', + qs: queryParameters, + headers: headerParams, + uri: path, + json: true, + } + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + + request(requestOptions, (error, response, body) => { + if (error) { + deferred.reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + deferred.resolve({ response: response, body: body }); + } else { + deferred.reject({ response: response, body: body }); + } + } + }); + + return deferred.promise; + } +} diff --git a/samples/client/petstore/typescript-node/api/PetApi.ts b/samples/client/petstore/typescript-node/api/PetApi.ts deleted file mode 100644 index 02605f2c8a8..00000000000 --- a/samples/client/petstore/typescript-node/api/PetApi.ts +++ /dev/null @@ -1,378 +0,0 @@ -/* tslint:disable:no-unused-variable */ - -export class PetApi { - private basePath = 'http://petstore.swagger.io/v2'; - - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - - public updatePet (body: Pet ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'PUT', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public addPet (body: Pet ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public findPetsByStatus (status: Array ) : Promise<{ response: http.ClientResponse; body: Array; }> { - var path = this.url + this.basePath + '/pet/findByStatus'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - if (status !== undefined) { - queryParameters['status'] = status; - } - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public findPetsByTags (tags: Array ) : Promise<{ response: http.ClientResponse; body: Array; }> { - var path = this.url + this.basePath + '/pet/findByTags'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - if (tags !== undefined) { - queryParameters['tags'] = tags; - } - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public getPetById (petId: number ) : Promise<{ response: http.ClientResponse; body: Pet; }> { - var path = this.url + this.basePath + '/pet/{petId}'; - - - path = path.replace('{' + 'petId' + '}', String(petId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public updatePetWithForm (petId: string, name: string, status: string ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}'; - - - path = path.replace('{' + 'petId' + '}', String(petId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public deletePet (apiKey: string, petId: number ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}'; - - - path = path.replace('{' + 'petId' + '}', String(petId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling deletePet'); - } - - - - - headerParams['apiKey'] = apiKey; - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'DELETE', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public uploadFile (petId: number, additionalMetadata: string, file: file ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}/uploadImage'; - - - path = path.replace('{' + 'petId' + '}', String(petId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling uploadFile'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - -} diff --git a/samples/client/petstore/typescript-node/api/StoreApi.ts b/samples/client/petstore/typescript-node/api/StoreApi.ts deleted file mode 100644 index 71cfe106fca..00000000000 --- a/samples/client/petstore/typescript-node/api/StoreApi.ts +++ /dev/null @@ -1,192 +0,0 @@ -/* tslint:disable:no-unused-variable */ - -export class StoreApi { - private basePath = 'http://petstore.swagger.io/v2'; - - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - - public getInventory ( ) : Promise<{ response: http.ClientResponse; body: map; }> { - var path = this.url + this.basePath + '/store/inventory'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: map; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public placeOrder (body: Order ) : Promise<{ response: http.ClientResponse; body: Order; }> { - var path = this.url + this.basePath + '/store/order'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public getOrderById (orderId: string ) : Promise<{ response: http.ClientResponse; body: Order; }> { - var path = this.url + this.basePath + '/store/order/{orderId}'; - - - path = path.replace('{' + 'orderId' + '}', String(orderId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling getOrderById'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public deleteOrder (orderId: string ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/store/order/{orderId}'; - - - path = path.replace('{' + 'orderId' + '}', String(orderId)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'DELETE', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - -} diff --git a/samples/client/petstore/typescript-node/api/UserApi.ts b/samples/client/petstore/typescript-node/api/UserApi.ts deleted file mode 100644 index ca6fd41c593..00000000000 --- a/samples/client/petstore/typescript-node/api/UserApi.ts +++ /dev/null @@ -1,372 +0,0 @@ -/* tslint:disable:no-unused-variable */ - -export class UserApi { - private basePath = 'http://petstore.swagger.io/v2'; - - constructor(private url: string, private username: string, private password: string, basePath?: string) { - if (basePath) { - this.basePath = basePath; - } - } - - - public createUser (body: User ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public createUsersWithArrayInput (body: Array ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/createWithArray'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public createUsersWithListInput (body: Array ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/createWithList'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'POST', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public loginUser (username: string, password: string ) : Promise<{ response: http.ClientResponse; body: string; }> { - var path = this.url + this.basePath + '/user/login'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - if (username !== undefined) { - queryParameters['username'] = username; - } - if (password !== undefined) { - queryParameters['password'] = password; - } - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: string; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public logoutUser ( ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/logout'; - - - - var queryParameters: any = {}; - var headers: any = {}; - - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public getUserByName (username: string ) : Promise<{ response: http.ClientResponse; body: User; }> { - var path = this.url + this.basePath + '/user/{username}'; - - - path = path.replace('{' + 'username' + '}', String(username)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling getUserByName'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); - - request({ - method: 'GET', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public updateUser (username: string, body: User ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/{username}'; - - - path = path.replace('{' + 'username' + '}', String(username)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling updateUser'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'PUT', - qs: queryParameters, - uri: path, - json: true, - body: body, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - - public deleteUser (username: string ) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/user/{username}'; - - - path = path.replace('{' + 'username' + '}', String(username)); - - - var queryParameters: any = {}; - var headers: any = {}; - - - // verify required parameter 'username' is set - if (!username) { - throw new Error('Missing required parameter username when calling deleteUser'); - } - - - - - - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); - - request({ - method: 'DELETE', - qs: queryParameters, - uri: path, - json: true, - - auth: { - username: this.username, password: this.password - } - }, (error, response, body) => { - if (error) { - deferred.reject(error); - } else { - if (response.statusCode >= 200 && response.statusCode <= 299) { - deferred.resolve({ response: response, body: body }); - } else { - deferred.reject({ response: response, body: body }); - } - } - }); - - return deferred.promise; - } - - -} diff --git a/samples/client/petstore/typescript-node/client.ts b/samples/client/petstore/typescript-node/client.ts new file mode 100644 index 00000000000..111c76f03c7 --- /dev/null +++ b/samples/client/petstore/typescript-node/client.ts @@ -0,0 +1,51 @@ +import api = require('./api'); +import fs = require('fs'); + +var petApi = new api.PetApi('http://petstore.swagger.io'); +petApi.apiKey = 'special-key'; + +var pet = new api.Pet(); +pet.name = 'TypeScriptDoggie'; + +var petId: any; + +var exitCode = 0; + +// Test various API calls to the petstore +petApi.addPet(pet) +.then((res) => { + var newPet = (res.response).body; + petId = (res.response).body.id; + console.log(`Created pet with ID ${petId}`); + newPet.status = api.Pet.StatusEnum.available; + return petApi.updatePet(newPet); +}) +.then((res) => { + console.log('Updated pet using POST body'); + return petApi.updatePetWithForm(petId, undefined, "pending"); +}) +.then((res) => { + console.log('Updated pet using POST form'); + return petApi.uploadFile(petId, undefined, fs.createReadStream('sample.png')); +}) +.then((res) => { + console.log('Uploaded image'); + return petApi.getPetById(petId); +}) +.then((res) => { + console.log('Got pet by ID: ' + JSON.stringify(res.body)); + if (res.body.status != api.Pet.StatusEnum.pending) { + throw new Error("Unexpected pet status"); + } +}) +.catch((err:any) => { + console.error(err); + exitCode = 1; +}) +.finally(() => { + return petApi.deletePet(petId); +}) +.then((res) => { + console.log('Deleted pet'); + process.exit(exitCode); +}); diff --git a/samples/client/petstore/typescript-node/model/Category.ts b/samples/client/petstore/typescript-node/model/Category.ts deleted file mode 100644 index fc4b2874e93..00000000000 --- a/samples/client/petstore/typescript-node/model/Category.ts +++ /dev/null @@ -1,7 +0,0 @@ -export class Category { - - id: number; - - name: string; -} - diff --git a/samples/client/petstore/typescript-node/model/Order.ts b/samples/client/petstore/typescript-node/model/Order.ts deleted file mode 100644 index b46ad4570a0..00000000000 --- a/samples/client/petstore/typescript-node/model/Order.ts +++ /dev/null @@ -1,26 +0,0 @@ -export class Order { - - id: number; - - petId: number; - - quantity: number; - - shipDate: DateTime; - - /** - * Order Status - */ - status: Order.StatusEnum; - - complete: boolean; -} - -export module Order { - - export enum StatusEnum { - placed = 'placed', - approved = 'approved', - delivered = 'delivered', - } -} diff --git a/samples/client/petstore/typescript-node/model/Pet.ts b/samples/client/petstore/typescript-node/model/Pet.ts deleted file mode 100644 index 4a3faa129ed..00000000000 --- a/samples/client/petstore/typescript-node/model/Pet.ts +++ /dev/null @@ -1,26 +0,0 @@ -export class Pet { - - id: number; - - category: Category; - - name: string; - - photoUrls: Array; - - tags: Array; - - /** - * pet status in the store - */ - status: Pet.StatusEnum; -} - -export module Pet { - - export enum StatusEnum { - available = 'available', - pending = 'pending', - sold = 'sold', - } -} diff --git a/samples/client/petstore/typescript-node/model/Tag.ts b/samples/client/petstore/typescript-node/model/Tag.ts deleted file mode 100644 index 6ae0d4ef576..00000000000 --- a/samples/client/petstore/typescript-node/model/Tag.ts +++ /dev/null @@ -1,7 +0,0 @@ -export class Tag { - - id: number; - - name: string; -} - diff --git a/samples/client/petstore/typescript-node/model/User.ts b/samples/client/petstore/typescript-node/model/User.ts deleted file mode 100644 index fee31563d13..00000000000 --- a/samples/client/petstore/typescript-node/model/User.ts +++ /dev/null @@ -1,22 +0,0 @@ -export class 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-node/package.json b/samples/client/petstore/typescript-node/package.json new file mode 100644 index 00000000000..ee598dcc6c2 --- /dev/null +++ b/samples/client/petstore/typescript-node/package.json @@ -0,0 +1,21 @@ +{ + "name": "petstore-typescript-node-sample", + "version": "1.0.0", + "description": "Sample of generated TypeScript petstore client", + "main": "api.js", + "scripts": { + "postinstall": "tsd reinstall --overwrite", + "test": "tsc && node client.js", + "clean": "rm -Rf node_modules/ typings/ *.js" + }, + "author": "Mads M. Tandrup", + "license": "Apache 2.0", + "dependencies": { + "bluebird": "^2.9.34", + "request": "^2.60.0" + }, + "devDependencies": { + "tsd": "^0.6.3", + "typescript": "^1.5.3" + } +} diff --git a/samples/client/petstore/typescript-node/sample.png b/samples/client/petstore/typescript-node/sample.png new file mode 100644 index 00000000000..c5916f28970 Binary files /dev/null and b/samples/client/petstore/typescript-node/sample.png differ diff --git a/samples/client/petstore/typescript-node/tsconfig.json b/samples/client/petstore/typescript-node/tsconfig.json new file mode 100644 index 00000000000..572228f6356 --- /dev/null +++ b/samples/client/petstore/typescript-node/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "module": "commonjs", + "noImplicitAny": true, + "target": "ES5" + }, + "files": [ + "api.ts", + "client.ts", + "typings/tsd.d.ts" + ] +} diff --git a/samples/client/petstore/typescript-node/tsd.json b/samples/client/petstore/typescript-node/tsd.json new file mode 100644 index 00000000000..89e4861f949 --- /dev/null +++ b/samples/client/petstore/typescript-node/tsd.json @@ -0,0 +1,21 @@ +{ + "version": "v4", + "repo": "borisyankov/DefinitelyTyped", + "ref": "master", + "path": "typings", + "bundle": "typings/tsd.d.ts", + "installed": { + "bluebird/bluebird.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + }, + "request/request.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + }, + "form-data/form-data.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + }, + "node/node.d.ts": { + "commit": "f6c8ca47193fb67947944a3170912672ac3e908e" + } + } +}