diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java index 1edad97316f..5d618422416 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenResponse.java @@ -28,6 +28,7 @@ public class CodegenResponse implements IJsonSchemaValidationProperties { public boolean is4xx; public boolean is5xx; public String message; + public boolean isSuccessCode; public boolean hasMore; public List> examples; public String dataType; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 82cebbf0224..14be4a36623 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -3686,6 +3686,7 @@ public class DefaultCodegen implements CodegenConfig { default: throw new RuntimeException("Invalid response code " + responseCode); } + r.isSuccessCode = r.code.startsWith("2"); } Schema responseSchema; if (this.openAPI != null && this.openAPI.getComponents() != null) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java index 736245f3894..70d65171e1a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptClientCodegen.java @@ -121,6 +121,9 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("tsconfig.mustache", "", "tsconfig.json")); + // Util + supportingFiles.add(new SupportingFile("util.mustache", "", "util.ts")); + supportingFiles.add(new SupportingFile("api/exception.mustache", "apis", "exception.ts")); // http supportingFiles.add(new SupportingFile("http" + File.separator + "http.mustache", "http", "http.ts")); supportingFiles.add(new SupportingFile("http" + File.separator + "isomorphic-fetch.mustache", "http", "isomorphic-fetch.ts")); @@ -155,9 +158,7 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo } @Override - public Map postProcessOperations(Map operations) { - Map objs = (Map) operations.get("operations"); - + public Map postProcessOperations(Map operations) { // Add additional filename information for model imports in the apis List> imports = (List>) operations.get("imports"); @@ -165,9 +166,48 @@ public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenCo im.put("filename", ((String) im.get("import")).replace('.', '/')); im.put("classname", getModelnameFromModelFilename(im.get("import").toString())); } + + @SuppressWarnings("unchecked") + Map operationsMap = (Map) operations.get("operations"); + List operationList = (List) operationsMap.get("operation"); + for (CodegenOperation operation: operationList) { + List responses = operation.responses; + operation.returnType = this.getReturnType(responses); + } return operations; } + private String getReturnType(List responses) { + StringBuilder returnType = new StringBuilder(); + boolean firstReturnType = true; + boolean atLeastOneSuccess = false; + boolean addVoid = false; + System.out.println(responses); + for (CodegenResponse response: responses) { + // TODO: we should probably catch an exception here + if (response.isSuccessCode) { + if (response.dataType != null) { + if (!firstReturnType) { + returnType.append(" | "); + } + returnType.append(response.dataType); + firstReturnType = false; + atLeastOneSuccess = true; + } else { + addVoid = true; + } + } + } + if (!atLeastOneSuccess) { + return null; + } else if (addVoid) { + returnType.append(" | void"); + } + + System.out.println("Return Type: " + returnType); + return returnType.toString(); + } + private String getModelnameFromModelFilename(String filename) { String name = filename.substring((modelPackage() + File.separator).length()); return camelize(name); diff --git a/modules/openapi-generator/src/main/resources/typescript/api/api.mustache b/modules/openapi-generator/src/main/resources/typescript/api/api.mustache index 4a216f08bb9..218b0636e71 100644 --- a/modules/openapi-generator/src/main/resources/typescript/api/api.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/api/api.mustache @@ -3,6 +3,9 @@ import { BaseAPIRequestFactory, RequiredError } from './baseapi'; import { RequestContext, HttpMethod, ResponseContext} from '../http/http'; import * as FormData from "form-data"; import {ObjectSerializer} from '../models/ObjectSerializer'; +import {ApiException} from './exception'; +import {isCodeInRange} from '../util'; + {{#imports}} import { {{classname}} } from '..{{filename}}'; {{/imports}} @@ -114,26 +117,44 @@ export class {{classname}}ResponseProcessor { {{#operation}} /** * - * @throws {{{returnType}}} if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public {{nickname}}(response: ResponseContext): {{#returnType}} {{{returnType}}}{{/returnType}} {{^returnType}} void {{/returnType}} { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - {{#returnType}} - const body: {{{returnType}}} = ObjectSerializer.deserialize(jsonBody, "{{{returnType}}}") as {{{returnType}}}; - if (responseOK) { - return body; - } else { - // TODO: deal with different errors based on httpStatusCode - throw body + public {{nickname}}(response: ResponseContext): {{#returnType}} {{{returnType}}}{{/returnType}} {{^returnType}} void {{/returnType}} { + {{#responses}} + if (isCodeInRange("{{code}}", response.httpStatusCode)) { + {{#dataType}} + const jsonBody = JSON.parse(response.body); + const body: {{{dataType}}} = ObjectSerializer.deserialize(jsonBody, "{{{dataType}}}") as {{{dataType}}}; + {{#isSuccessCode}} + return body; + {{/isSuccessCode}} + {{^isSuccessCode}} + throw new ApiException<{{{dataType}}}>({{code}}, body); + {{/isSuccessCode}} + {{/dataType}} + {{^dataType}} + {{#isSuccessCode}} + return; + {{/isSuccessCode}} + {{^isSuccessCode}} + throw new ApiException(response.httpStatusCode, "{{message}}"); + {{/isSuccessCode}} + {{/dataType}} } - {{/returnType}} - {{^returnType}} - // TODO: make this based on status code! - if (!responseOK) { - throw new Error("Invalid status code: " + response.httpStatusCode + "!"); + {{/responses}} + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + {{#returnType}} + const jsonBody = JSON.parse(response.body); + const body: {{{returnType}}} = ObjectSerializer.deserialize(jsonBody, "{{{returnType}}}") as {{{returnType}}}; + return body; + {{/returnType}} + {{^returnType}} + return; + {{/returnType}} } - {{/returnType}} + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/typescript/api/exception.mustache b/modules/openapi-generator/src/main/resources/typescript/api/exception.mustache new file mode 100644 index 00000000000..327ac516a31 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript/api/exception.mustache @@ -0,0 +1,5 @@ +export class ApiException extends Error { + public constructor(public code: number, public body: T) { + super("Got HTTP Status Code " + code) + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript/generators/fetch/index.mustache b/modules/openapi-generator/src/main/resources/typescript/generators/fetch/index.mustache index 2bcea78b8ca..e7c7bd4e5a9 100644 --- a/modules/openapi-generator/src/main/resources/typescript/generators/fetch/index.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/generators/fetch/index.mustache @@ -5,3 +5,4 @@ export * from './middleware'; export * from './models/all'; export { Configuration} from './configuration' export * from './PromiseAPI'; +export * from './apis/exception'; \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript/util.mustache b/modules/openapi-generator/src/main/resources/typescript/util.mustache new file mode 100644 index 00000000000..af9085e7cbf --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript/util.mustache @@ -0,0 +1,20 @@ +export function isCodeInRange(codeRange: string, code: number): boolean { + // This is how the default value is encoded in OAG + if (codeRange === "0") { + return true; + } + if (codeRange == code.toString()) { + return true; + } else { + const codeString = code.toString(); + if (codeString.length != codeRange.length) { + return false; + } + for (let i = 0; i < codeString.length; i++) { + if (codeRange.charAt(i) != "X" && codeRange.charAt(i) != codeString.charAt(i)) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/samples/client/petstore/typescript/builds/default/apis/PetApi.ts b/samples/client/petstore/typescript/builds/default/apis/PetApi.ts index 049a3a820dd..a417d3b75c2 100644 --- a/samples/client/petstore/typescript/builds/default/apis/PetApi.ts +++ b/samples/client/petstore/typescript/builds/default/apis/PetApi.ts @@ -3,6 +3,9 @@ import { BaseAPIRequestFactory, RequiredError } from './baseapi'; import { RequestContext, HttpMethod, ResponseContext} from '../http/http'; import * as FormData from "form-data"; import {ObjectSerializer} from '../models/ObjectSerializer'; +import {ApiException} from './exception'; +import {isCodeInRange} from '../util'; + import { ApiResponse } from '../models/ApiResponse'; import { Pet } from '../models/Pet'; @@ -316,118 +319,164 @@ export class PetApiResponseProcessor { /** * - * @throws if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public addPet(response: ResponseContext): void { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - // TODO: make this based on status code! - if (!responseOK) { - throw new Error("Invalid status code: " + response.httpStatusCode + "!"); + public addPet(response: ResponseContext): void { + if (isCodeInRange("405", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid input"); } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public deletePet(response: ResponseContext): void { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - // TODO: make this based on status code! - if (!responseOK) { - throw new Error("Invalid status code: " + response.httpStatusCode + "!"); + public deletePet(response: ResponseContext): void { + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid pet value"); } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws Array if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public findPetsByStatus(response: ResponseContext): Array { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - const body: Array = ObjectSerializer.deserialize(jsonBody, "Array") as Array; - if (responseOK) { - return body; - } else { - // TODO: deal with different errors based on httpStatusCode - throw body + public findPetsByStatus(response: ResponseContext): Array { + if (isCodeInRange("200", response.httpStatusCode)) { + const jsonBody = JSON.parse(response.body); + const body: Array = ObjectSerializer.deserialize(jsonBody, "Array") as Array; + return body; } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid status value"); + } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const jsonBody = JSON.parse(response.body); + const body: Array = ObjectSerializer.deserialize(jsonBody, "Array") as Array; + return body; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws Array if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public findPetsByTags(response: ResponseContext): Array { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - const body: Array = ObjectSerializer.deserialize(jsonBody, "Array") as Array; - if (responseOK) { - return body; - } else { - // TODO: deal with different errors based on httpStatusCode - throw body + public findPetsByTags(response: ResponseContext): Array { + if (isCodeInRange("200", response.httpStatusCode)) { + const jsonBody = JSON.parse(response.body); + const body: Array = ObjectSerializer.deserialize(jsonBody, "Array") as Array; + return body; } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid tag value"); + } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const jsonBody = JSON.parse(response.body); + const body: Array = ObjectSerializer.deserialize(jsonBody, "Array") as Array; + return body; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws Pet if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public getPetById(response: ResponseContext): Pet { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - const body: Pet = ObjectSerializer.deserialize(jsonBody, "Pet") as Pet; - if (responseOK) { - return body; - } else { - // TODO: deal with different errors based on httpStatusCode - throw body + public getPetById(response: ResponseContext): Pet { + if (isCodeInRange("200", response.httpStatusCode)) { + const jsonBody = JSON.parse(response.body); + const body: Pet = ObjectSerializer.deserialize(jsonBody, "Pet") as Pet; + return body; } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid ID supplied"); + } + if (isCodeInRange("404", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Pet not found"); + } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const jsonBody = JSON.parse(response.body); + const body: Pet = ObjectSerializer.deserialize(jsonBody, "Pet") as Pet; + return body; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public updatePet(response: ResponseContext): void { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - // TODO: make this based on status code! - if (!responseOK) { - throw new Error("Invalid status code: " + response.httpStatusCode + "!"); + public updatePet(response: ResponseContext): void { + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid ID supplied"); } + if (isCodeInRange("404", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Pet not found"); + } + if (isCodeInRange("405", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Validation exception"); + } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public updatePetWithForm(response: ResponseContext): void { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - // TODO: make this based on status code! - if (!responseOK) { - throw new Error("Invalid status code: " + response.httpStatusCode + "!"); + public updatePetWithForm(response: ResponseContext): void { + if (isCodeInRange("405", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid input"); } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws ApiResponse if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public uploadFile(response: ResponseContext): ApiResponse { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - const body: ApiResponse = ObjectSerializer.deserialize(jsonBody, "ApiResponse") as ApiResponse; - if (responseOK) { - return body; - } else { - // TODO: deal with different errors based on httpStatusCode - throw body + public uploadFile(response: ResponseContext): ApiResponse { + if (isCodeInRange("200", response.httpStatusCode)) { + const jsonBody = JSON.parse(response.body); + const body: ApiResponse = ObjectSerializer.deserialize(jsonBody, "ApiResponse") as ApiResponse; + return body; } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const jsonBody = JSON.parse(response.body); + const body: ApiResponse = ObjectSerializer.deserialize(jsonBody, "ApiResponse") as ApiResponse; + return body; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } } diff --git a/samples/client/petstore/typescript/builds/default/apis/StoreApi.ts b/samples/client/petstore/typescript/builds/default/apis/StoreApi.ts index 41ca20d0b2a..c73dee8b6c2 100644 --- a/samples/client/petstore/typescript/builds/default/apis/StoreApi.ts +++ b/samples/client/petstore/typescript/builds/default/apis/StoreApi.ts @@ -3,6 +3,9 @@ import { BaseAPIRequestFactory, RequiredError } from './baseapi'; import { RequestContext, HttpMethod, ResponseContext} from '../http/http'; import * as FormData from "form-data"; import {ObjectSerializer} from '../models/ObjectSerializer'; +import {ApiException} from './exception'; +import {isCodeInRange} from '../util'; + import { Order } from '../models/Order'; export class StoreApiRequestFactory extends BaseAPIRequestFactory { @@ -133,63 +136,90 @@ export class StoreApiResponseProcessor { /** * - * @throws if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public deleteOrder(response: ResponseContext): void { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - // TODO: make this based on status code! - if (!responseOK) { - throw new Error("Invalid status code: " + response.httpStatusCode + "!"); + public deleteOrder(response: ResponseContext): void { + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid ID supplied"); } + if (isCodeInRange("404", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Order not found"); + } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws { [key: string]: number; } if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public getInventory(response: ResponseContext): { [key: string]: number; } { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - const body: { [key: string]: number; } = ObjectSerializer.deserialize(jsonBody, "{ [key: string]: number; }") as { [key: string]: number; }; - if (responseOK) { - return body; - } else { - // TODO: deal with different errors based on httpStatusCode - throw body + public getInventory(response: ResponseContext): { [key: string]: number; } { + if (isCodeInRange("200", response.httpStatusCode)) { + const jsonBody = JSON.parse(response.body); + const body: { [key: string]: number; } = ObjectSerializer.deserialize(jsonBody, "{ [key: string]: number; }") as { [key: string]: number; }; + return body; } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const jsonBody = JSON.parse(response.body); + const body: { [key: string]: number; } = ObjectSerializer.deserialize(jsonBody, "{ [key: string]: number; }") as { [key: string]: number; }; + return body; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws Order if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public getOrderById(response: ResponseContext): Order { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - const body: Order = ObjectSerializer.deserialize(jsonBody, "Order") as Order; - if (responseOK) { - return body; - } else { - // TODO: deal with different errors based on httpStatusCode - throw body + public getOrderById(response: ResponseContext): Order { + if (isCodeInRange("200", response.httpStatusCode)) { + const jsonBody = JSON.parse(response.body); + const body: Order = ObjectSerializer.deserialize(jsonBody, "Order") as Order; + return body; } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid ID supplied"); + } + if (isCodeInRange("404", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Order not found"); + } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const jsonBody = JSON.parse(response.body); + const body: Order = ObjectSerializer.deserialize(jsonBody, "Order") as Order; + return body; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws Order if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public placeOrder(response: ResponseContext): Order { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - const body: Order = ObjectSerializer.deserialize(jsonBody, "Order") as Order; - if (responseOK) { - return body; - } else { - // TODO: deal with different errors based on httpStatusCode - throw body + public placeOrder(response: ResponseContext): Order { + if (isCodeInRange("200", response.httpStatusCode)) { + const jsonBody = JSON.parse(response.body); + const body: Order = ObjectSerializer.deserialize(jsonBody, "Order") as Order; + return body; } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid Order"); + } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const jsonBody = JSON.parse(response.body); + const body: Order = ObjectSerializer.deserialize(jsonBody, "Order") as Order; + return body; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } } diff --git a/samples/client/petstore/typescript/builds/default/apis/UserApi.ts b/samples/client/petstore/typescript/builds/default/apis/UserApi.ts index 428bcd845b1..aed2f93c4b7 100644 --- a/samples/client/petstore/typescript/builds/default/apis/UserApi.ts +++ b/samples/client/petstore/typescript/builds/default/apis/UserApi.ts @@ -3,6 +3,9 @@ import { BaseAPIRequestFactory, RequiredError } from './baseapi'; import { RequestContext, HttpMethod, ResponseContext} from '../http/http'; import * as FormData from "form-data"; import {ObjectSerializer} from '../models/ObjectSerializer'; +import {ApiException} from './exception'; +import {isCodeInRange} from '../util'; + import { User } from '../models/User'; export class UserApiRequestFactory extends BaseAPIRequestFactory { @@ -268,112 +271,153 @@ export class UserApiResponseProcessor { /** * - * @throws if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public createUser(response: ResponseContext): void { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - // TODO: make this based on status code! - if (!responseOK) { - throw new Error("Invalid status code: " + response.httpStatusCode + "!"); + public createUser(response: ResponseContext): void { + if (isCodeInRange("0", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "successful operation"); } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public createUsersWithArrayInput(response: ResponseContext): void { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - // TODO: make this based on status code! - if (!responseOK) { - throw new Error("Invalid status code: " + response.httpStatusCode + "!"); + public createUsersWithArrayInput(response: ResponseContext): void { + if (isCodeInRange("0", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "successful operation"); } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public createUsersWithListInput(response: ResponseContext): void { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - // TODO: make this based on status code! - if (!responseOK) { - throw new Error("Invalid status code: " + response.httpStatusCode + "!"); + public createUsersWithListInput(response: ResponseContext): void { + if (isCodeInRange("0", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "successful operation"); } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public deleteUser(response: ResponseContext): void { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - // TODO: make this based on status code! - if (!responseOK) { - throw new Error("Invalid status code: " + response.httpStatusCode + "!"); + public deleteUser(response: ResponseContext): void { + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid username supplied"); } + if (isCodeInRange("404", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "User not found"); + } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws User if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public getUserByName(response: ResponseContext): User { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - const body: User = ObjectSerializer.deserialize(jsonBody, "User") as User; - if (responseOK) { - return body; - } else { - // TODO: deal with different errors based on httpStatusCode - throw body + public getUserByName(response: ResponseContext): User { + if (isCodeInRange("200", response.httpStatusCode)) { + const jsonBody = JSON.parse(response.body); + const body: User = ObjectSerializer.deserialize(jsonBody, "User") as User; + return body; } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid username supplied"); + } + if (isCodeInRange("404", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "User not found"); + } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const jsonBody = JSON.parse(response.body); + const body: User = ObjectSerializer.deserialize(jsonBody, "User") as User; + return body; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws string if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public loginUser(response: ResponseContext): string { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - const body: string = ObjectSerializer.deserialize(jsonBody, "string") as string; - if (responseOK) { - return body; - } else { - // TODO: deal with different errors based on httpStatusCode - throw body + public loginUser(response: ResponseContext): string { + if (isCodeInRange("200", response.httpStatusCode)) { + const jsonBody = JSON.parse(response.body); + const body: string = ObjectSerializer.deserialize(jsonBody, "string") as string; + return body; } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid username/password supplied"); + } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const jsonBody = JSON.parse(response.body); + const body: string = ObjectSerializer.deserialize(jsonBody, "string") as string; + return body; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public logoutUser(response: ResponseContext): void { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - // TODO: make this based on status code! - if (!responseOK) { - throw new Error("Invalid status code: " + response.httpStatusCode + "!"); + public logoutUser(response: ResponseContext): void { + if (isCodeInRange("0", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "successful operation"); } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } /** * - * @throws if the httpStatusCode is not in [200, 299] + * @throws ApiException if the response code was not in [200, 299] */ - public updateUser(response: ResponseContext): void { - const jsonBody = JSON.parse(response.body); - const responseOK = response.httpStatusCode && response.httpStatusCode >= 200 && response.httpStatusCode <= 299; - // TODO: make this based on status code! - if (!responseOK) { - throw new Error("Invalid status code: " + response.httpStatusCode + "!"); + public updateUser(response: ResponseContext): void { + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid user supplied"); } + if (isCodeInRange("404", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "User not found"); + } + + // Work around for incorrect api specification in petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!"); } } diff --git a/samples/client/petstore/typescript/builds/default/apis/exception.ts b/samples/client/petstore/typescript/builds/default/apis/exception.ts new file mode 100644 index 00000000000..327ac516a31 --- /dev/null +++ b/samples/client/petstore/typescript/builds/default/apis/exception.ts @@ -0,0 +1,5 @@ +export class ApiException extends Error { + public constructor(public code: number, public body: T) { + super("Got HTTP Status Code " + code) + } +} \ No newline at end of file diff --git a/samples/client/petstore/typescript/builds/default/index.ts b/samples/client/petstore/typescript/builds/default/index.ts index 2bcea78b8ca..e7c7bd4e5a9 100644 --- a/samples/client/petstore/typescript/builds/default/index.ts +++ b/samples/client/petstore/typescript/builds/default/index.ts @@ -5,3 +5,4 @@ export * from './middleware'; export * from './models/all'; export { Configuration} from './configuration' export * from './PromiseAPI'; +export * from './apis/exception'; \ No newline at end of file diff --git a/samples/client/petstore/typescript/builds/default/util.ts b/samples/client/petstore/typescript/builds/default/util.ts new file mode 100644 index 00000000000..af9085e7cbf --- /dev/null +++ b/samples/client/petstore/typescript/builds/default/util.ts @@ -0,0 +1,20 @@ +export function isCodeInRange(codeRange: string, code: number): boolean { + // This is how the default value is encoded in OAG + if (codeRange === "0") { + return true; + } + if (codeRange == code.toString()) { + return true; + } else { + const codeString = code.toString(); + if (codeString.length != codeRange.length) { + return false; + } + for (let i = 0; i < codeString.length; i++) { + if (codeRange.charAt(i) != "X" && codeRange.charAt(i) != codeString.charAt(i)) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/samples/client/petstore/typescript/tests/default/dist/test.js b/samples/client/petstore/typescript/tests/default/dist/test.js deleted file mode 100644 index 5ebd748a5a9..00000000000 --- a/samples/client/petstore/typescript/tests/default/dist/test.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var ts_petstore_client_1 = require("ts-petstore-client"); -var MiddlewareA = /** @class */ (function () { - function MiddlewareA() { - } - MiddlewareA.prototype.pre = function (request) { - console.log(request); - return Promise.resolve(request); - }; - MiddlewareA.prototype.post = function (response) { - console.log(response); - return Promise.resolve(response); - }; - return MiddlewareA; -}()); -var config = new ts_petstore_client_1.Configuration({ - middleware: [ - new MiddlewareA() - ] -}); -var api = new ts_petstore_client_1.PetApi(config); -api.getPetById(3).then(function (pet) { - console.log(pet); -}).catch(function (err) { - console.log(err); -}); diff --git a/samples/client/petstore/typescript/tests/default/dist/test/api/PetApi.test.js b/samples/client/petstore/typescript/tests/default/dist/test/api/PetApi.test.js deleted file mode 100644 index 41e07205f98..00000000000 --- a/samples/client/petstore/typescript/tests/default/dist/test/api/PetApi.test.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var ts_petstore_client_1 = require("ts-petstore-client"); -var chai_1 = require("chai"); -var configuration = new ts_petstore_client_1.Configuration(); -var petApi = new ts_petstore_client_1.PetApi(configuration); -describe("PetApi", function () { - it("addPet", function (done) { - var pet = new ts_petstore_client_1.Pet(); - pet.id = Math.floor(Math.random() * 100000); - pet.name = "PetName"; - pet.photoUrls = []; - pet.status = ts_petstore_client_1.Pet.StatusEnum.Available; - pet.tags = []; - pet.category = undefined; - petApi.addPet(pet).then(function () { - return petApi.getPetById(pet.id); - }).then(function (createdPet) { - chai_1.expect(createdPet).to.deep.equal(pet); - done(); - }).catch(function (err) { - done(err); - }); - }); -}); diff --git a/samples/client/petstore/typescript/tests/default/dist/test/auth/auth.test.js b/samples/client/petstore/typescript/tests/default/dist/test/auth/auth.test.js deleted file mode 100644 index e0e55de464a..00000000000 --- a/samples/client/petstore/typescript/tests/default/dist/test/auth/auth.test.js +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var ts_petstore_client_1 = require("ts-petstore-client"); -var ts_petstore_client_2 = require("ts-petstore-client"); -var chai_1 = require("chai"); -describe("Security Authentication", function () { - describe("No Authentication", function () { - it("No Authentication", function () { - var ctx = new ts_petstore_client_2.RequestContext("http://google.com", ts_petstore_client_2.HttpMethod.GET); - var noAuth = new ts_petstore_client_1.NoAuthentication(); - noAuth.applySecurityAuthentication(ctx); - chai_1.expect(ctx.getUrl()).to.equal("http://google.com"); - chai_1.expect(ctx.getHeaders()).to.deep.equal({}); - chai_1.expect(ctx.getBody()).to.equal(""); - }); - }); - describe("API Key Authentication", function () { - // TODO: make all params const variables - it("Header API Key", function () { - var ctx = new ts_petstore_client_2.RequestContext("http://google.com", ts_petstore_client_2.HttpMethod.GET); - var auth = new ts_petstore_client_1.APIKeyAuthentication("my_name", "paramName", "header", "apiKey"); - auth.applySecurityAuthentication(ctx); - chai_1.expect(ctx.getUrl()).to.equal("http://google.com"); - chai_1.expect(ctx.getHeaders()).to.have.property("paramName"); - chai_1.expect(ctx.getHeaders()["paramName"]).to.equal("apiKey"); - chai_1.expect(ctx.getBody()).to.equal(""); - }); - it("Query API Key", function () { - var ctx = new ts_petstore_client_2.RequestContext("http://google.com?a=b", ts_petstore_client_2.HttpMethod.GET); - var auth = new ts_petstore_client_1.APIKeyAuthentication("my_name", "paramName", "query", "apiKey"); - auth.applySecurityAuthentication(ctx); - chai_1.expect(ctx.getUrl()).to.contain("paramName=apiKey"); - chai_1.expect(ctx.getHeaders()).to.deep.equal({}); - chai_1.expect(ctx.getBody()).to.equal(""); - }); - it("Cookie API Key", function () { - var ctx = new ts_petstore_client_2.RequestContext("http://google.com", ts_petstore_client_2.HttpMethod.GET); - var auth = new ts_petstore_client_1.APIKeyAuthentication("my_name", "paramName", "cookie", "apiKey"); - auth.applySecurityAuthentication(ctx); - chai_1.expect(ctx.getUrl()).to.equal("http://google.com"); - chai_1.expect(ctx.getHeaders()).to.have.property("Cookie"); - chai_1.expect(ctx.getHeaders()["Cookie"]).to.contain("paramName=apiKey; "); - chai_1.expect(ctx.getBody()).to.equal(""); - }); - }); -}); diff --git a/samples/client/petstore/typescript/tests/default/dist/test/http/isomorphic-fetch.test.js b/samples/client/petstore/typescript/tests/default/dist/test/http/isomorphic-fetch.test.js deleted file mode 100644 index bca167ad867..00000000000 --- a/samples/client/petstore/typescript/tests/default/dist/test/http/isomorphic-fetch.test.js +++ /dev/null @@ -1,64 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var ts_petstore_client_1 = require("ts-petstore-client"); -var chai_1 = require("chai"); -var FormData = require("form-data"); -var libs = { - "isomorphic-fetch": new ts_petstore_client_1.IsomorphicFetchHttpLibrary() -}; -var _loop_1 = function (libName) { - var lib = libs[libName]; - describe("Isomorphic Fetch", function () { - it("GET-Request", function (done) { - var requestContext = new ts_petstore_client_1.RequestContext("http://httpbin.org/get", ts_petstore_client_1.HttpMethod.GET); - requestContext.setHeaderParam("X-Test-Token", "Test-Token"); - requestContext.addCookie("test-cookie", "cookie-value"); - lib.send(requestContext).then(function (resp) { - chai_1.expect(resp.httpStatusCode, "Expected status code to be 200").to.eq(200); - var body = JSON.parse(resp.body); - chai_1.expect(body["headers"]).to.exist; - chai_1.expect(body["headers"]["X-Test-Token"]).to.equal("Test-Token"); - chai_1.expect(body["headers"]["Cookie"]).to.equal("test-cookie=cookie-value;"); - done(); - }).catch(function (e) { - done(e); - }); - }); - it("POST-Request", function (done) { - var requestContext = new ts_petstore_client_1.RequestContext("http://httpbin.org/post", ts_petstore_client_1.HttpMethod.POST); - requestContext.setHeaderParam("X-Test-Token", "Test-Token"); - requestContext.addCookie("test-cookie", "cookie-value"); - var formData = new FormData(); - formData.append("test", "test2"); - formData.append("testFile", Buffer.from("abc"), "fileName.json"); - requestContext.setBody(formData); - lib.send(requestContext).then(function (resp) { - chai_1.expect(resp.httpStatusCode, "Expected status code to be 200").to.eq(200); - var body = JSON.parse(resp.body); - chai_1.expect(body["headers"]).to.exist; - chai_1.expect(body["headers"]["X-Test-Token"]).to.equal("Test-Token"); - chai_1.expect(body["headers"]["Cookie"]).to.equal("test-cookie=cookie-value;"); - chai_1.expect(body["files"]["testFile"]).to.equal("abc"); - chai_1.expect(body["form"]["test"]).to.equal("test2"); - done(); - }).catch(function (e) { - done(e); - }); - }); - it("Cookies-Request", function (done) { - var requestContext = new ts_petstore_client_1.RequestContext("http://httpbin.org/cookies", ts_petstore_client_1.HttpMethod.GET); - requestContext.addCookie("test-cookie", "cookie-value"); - lib.send(requestContext).then(function (resp) { - chai_1.expect(resp.httpStatusCode, "Expected status code to be 200").to.eq(200); - var body = JSON.parse(resp.body); - chai_1.expect(body["cookies"]["test-cookie"]).to.equal("cookie-value"); - done(); - }).catch(function (e) { - done(e); - }); - }); - }); -}; -for (var libName in libs) { - _loop_1(libName); -} diff --git a/samples/client/petstore/typescript/tests/default/dist/test/models/ObjectSerializer.test.js b/samples/client/petstore/typescript/tests/default/dist/test/models/ObjectSerializer.test.js deleted file mode 100644 index 0a7f6547ffd..00000000000 --- a/samples/client/petstore/typescript/tests/default/dist/test/models/ObjectSerializer.test.js +++ /dev/null @@ -1,193 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var rewire = require("rewire"); -var chai_1 = require("chai"); -var ts_petstore_client_1 = require("ts-petstore-client"); -var objectSerializerFile = rewire(__dirname + "/../../node_modules/ts-petstore-client/models/ObjectSerializer.ts"); -var ObjectSerializer = objectSerializerFile.__get__("ObjectSerializer"); -describe("ObjectSerializer", function () { - describe("Serialize", function () { - it("String", function () { - var input = "test string"; - chai_1.expect(ObjectSerializer.serialize(input, "string")).to.equal("test string"); - }); - it("Number", function () { - var input = 1337; - chai_1.expect(ObjectSerializer.serialize(input, "number")).to.equal(1337); - }); - it("String Array", function () { - var input = ["a", "b", "c"]; - chai_1.expect(ObjectSerializer.serialize(input, "Array")).to.deep.equal(["a", "b", "c"]); - }); - it("Number Array", function () { - var input = [1337, 42, 0]; - chai_1.expect(ObjectSerializer.serialize(input, "Array")).to.deep.equal([1337, 42, 0]); - }); - it("Date", function () { - var input = new Date(1543777609696); - chai_1.expect(ObjectSerializer.serialize(input, "Date")).to.equal(input.toISOString()); - }); - it("Object", function () { - var input = { "a": "test", "b": { "test": 5 } }; - chai_1.expect(ObjectSerializer.serialize(input, "Object")).to.deep.equal({ a: "test", "b": { "test": 5 } }); - }); - it("Class", function () { - var input = new ts_petstore_client_1.Category(); - input.id = 4; - input.name = "Test"; - chai_1.expect(ObjectSerializer.serialize(input, "Category")).to.deep.equal({ "id": input.id, "name": input.name }); - }); - it("Enum", function () { - var input = ts_petstore_client_1.Pet.StatusEnum.Available; - chai_1.expect(ObjectSerializer.serialize(input, "Pet.StatusEnum")).to.equal("available"); - }); - it("Complex Class", function () { - var tags = []; - var tagResult = []; - for (var i = 0; i < 2; i++) { - var tag = new ts_petstore_client_1.Tag(); - tag.id = i; - tag.name = "Tag" + i; - tags.push(tag); - tagResult.push({ - "id": tag.id, - "name": tag.name - }); - } - var category = new ts_petstore_client_1.Category(); - category.id = 4; - category.name = "TestCat"; - var pet = new ts_petstore_client_1.Pet(); - pet.id = 145; - pet.category = category; - pet.name = "PetName"; - pet.photoUrls = ["url", "other url"]; - pet.status = ts_petstore_client_1.Pet.StatusEnum.Available; - pet.tags = tags; - chai_1.expect(ObjectSerializer.serialize(pet, "Pet")).to.deep.equal({ - "id": pet.id, - "name": pet.name, - "category": { - "id": category.id, - "name": category.name - }, - "photoUrls": ["url", "other url"], - "status": "available", - "tags": tagResult - }); - }); - it("Array of Class", function () { - var categories = []; - var result = []; - for (var i = 0; i < 2; i++) { - var category = new ts_petstore_client_1.Category(); - category.id = i; - category.name = "Cat" + i; - categories.push(category); - result.push({ - "id": category.id, - "name": category.name - }); - } - chai_1.expect(ObjectSerializer.serialize(categories, "Array")).to.deep.equal(result); - }); - }); - describe("Deserialize", function () { - it("String", function () { - var input = "test string"; - chai_1.expect(ObjectSerializer.deserialize(input, "string")).to.equal("test string"); - }); - it("Number", function () { - var input = 1337; - chai_1.expect(ObjectSerializer.deserialize(input, "number")).to.equal(1337); - }); - it("String Array", function () { - var input = ["a", "b", "c"]; - chai_1.expect(ObjectSerializer.deserialize(input, "Array")).to.deep.equal(["a", "b", "c"]); - }); - it("Number Array", function () { - var input = [1337, 42, 0]; - chai_1.expect(ObjectSerializer.deserialize(input, "Array")).to.deep.equal([1337, 42, 0]); - }); - it("Date", function () { - var input = new Date(1543777609696); - chai_1.expect(ObjectSerializer.deserialize(input.toISOString(), "Date").getTime()).to.equal(input.getTime()); - }); - it("Object", function () { - var input = { "a": "test", "b": { "test": 5 } }; - chai_1.expect(ObjectSerializer.deserialize(input, "Object")).to.deep.equal({ a: "test", "b": { "test": 5 } }); - }); - it("Class", function () { - var input = new ts_petstore_client_1.Category(); - input.id = 4; - input.name = "Test"; - var deserialized = ObjectSerializer.deserialize({ "id": 4, "name": "Test" }, "Category"); - chai_1.expect(deserialized.constructor.name).to.equal("Category"); - chai_1.expect(deserialized).to.deep.equal(input); - }); - it("Enum", function () { - var input = ts_petstore_client_1.Pet.StatusEnum.Available; - chai_1.expect(ObjectSerializer.deserialize("available", "Pet.StatusEnum")).to.equal(input); - }); - it("Complex Class", function () { - var tags = []; - var tagResult = []; - for (var i = 0; i < 2; i++) { - var tag = new ts_petstore_client_1.Tag(); - tag.id = i; - tag.name = "Tag" + i; - tags.push(tag); - tagResult.push({ - "id": tag.id, - "name": tag.name - }); - } - var category = new ts_petstore_client_1.Category(); - category.id = 4; - category.name = "TestCat"; - var pet = new ts_petstore_client_1.Pet(); - pet.id = 145; - pet.category = category; - pet.name = "PetName"; - pet.photoUrls = ["url", "other url"]; - pet.status = ts_petstore_client_1.Pet.StatusEnum.Available; - pet.tags = tags; - var deserialized = ObjectSerializer.deserialize({ - "id": pet.id, - "name": pet.name, - "category": { - "id": category.id, - "name": category.name - }, - "photoUrls": ["url", "other url"], - "status": "available", - "tags": tagResult - }, "Pet"); - chai_1.expect(deserialized.constructor.name).to.equal("Pet"); - chai_1.expect(deserialized.category.constructor.name).to.equal("Category"); - for (var i = 0; i < deserialized.tags.length; i++) { - chai_1.expect(deserialized.tags[i].constructor.name).to.equal("Tag"); - } - chai_1.expect(deserialized).to.deep.equal(pet); - }); - it("Array of Class", function () { - var categories = []; - var result = []; - for (var i = 0; i < 2; i++) { - var category = new ts_petstore_client_1.Category(); - category.id = i; - category.name = "Cat" + i; - categories.push(category); - result.push({ - "id": category.id, - "name": category.name - }); - } - var deserialized = ObjectSerializer.deserialize(result, "Array"); - for (var i = 0; i < categories.length; i++) { - chai_1.expect(deserialized[i].constructor.name).to.equal("Category"); - } - chai_1.expect(deserialized).to.deep.equal(categories); - }); - }); -}); diff --git a/samples/client/petstore/typescript/tests/default/test/api/PetApi.test.ts b/samples/client/petstore/typescript/tests/default/test/api/PetApi.test.ts index d243f18abf1..5f963a302a5 100644 --- a/samples/client/petstore/typescript/tests/default/test/api/PetApi.test.ts +++ b/samples/client/petstore/typescript/tests/default/test/api/PetApi.test.ts @@ -1,18 +1,20 @@ -import {PetApi, Configuration, Pet} from 'ts-petstore-client' +import {PetApi, Configuration, Pet, ApiException} from 'ts-petstore-client' import { expect, assert } from "chai"; const configuration = new Configuration() const petApi = new PetApi(configuration) +const pet = new Pet() +pet.id = Math.floor(Math.random() * 100000) +pet.name = "PetName" +pet.photoUrls = [] +pet.status = Pet.StatusEnum.Available +pet.tags = [] +pet.category = undefined + describe("PetApi", () =>{ it("addPet", (done) => { - const pet = new Pet() - pet.id = Math.floor(Math.random() * 100000) - pet.name = "PetName" - pet.photoUrls = [] - pet.status = Pet.StatusEnum.Available - pet.tags = [] - pet.category = undefined + petApi.addPet(pet).then(() => { return petApi.getPetById(pet.id) @@ -23,4 +25,20 @@ describe("PetApi", () =>{ done(err) }) }) + + it("deletePet", (done) => { + petApi.addPet(pet).then(() => { + return petApi.deletePet(pet.id) + }).then(() => { + return petApi.getPetById(pet.id) + }).then((pet: Pet) => { + done("Pet with id " + pet.id + " was not deleted!"); + }).catch((err: any) => { + if (err instanceof ApiException && err.code == 404) { + done(); + } else { + done(err) + } + }) + }) }) \ No newline at end of file diff --git a/samples/client/petstore/typescript/tests/default/tsconfig.json b/samples/client/petstore/typescript/tests/default/tsconfig.json index 3470aabd0c3..4596f6e40bc 100644 --- a/samples/client/petstore/typescript/tests/default/tsconfig.json +++ b/samples/client/petstore/typescript/tests/default/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { "module": "commonjs", - "target": "es5", + "target": "es6", "noImplicitAny": true, "sourceMap": false, "outDir": "dist",