Compare commits

...

65 Commits

Author SHA1 Message Date
Tino Fuhrmann
03ee3b2f1a Updated typescript docs 2020-05-05 22:58:04 +02:00
Tino Fuhrmann
226f8f7585 Removed this where not required 2020-05-04 23:59:51 +02:00
Tino Fuhrmann
670559077c Added options for npm version, repository, name and updated readme 2020-05-04 23:59:50 +02:00
Tino Fuhrmann
934f226098
[TS-Refactor] Top-level exports for fetch & jquery (#6138)
* Added top-level exports
* Updated generator README
* Updated typescript generator docs
2020-05-04 23:58:38 +02:00
Tino Fuhrmann
07dd1efb7a Removed whitespace 2020-05-03 20:58:07 +02:00
Tino Fuhrmann
5a2561f520 Mark typescript client codegen as experimental 2020-05-02 22:03:56 +02:00
Tino Fuhrmann
d704a4ffba Readded missing change 2020-05-02 19:21:57 +02:00
Tino Fuhrmann
bfc14c82e5 Removed tab from DefaultCodegen 2020-04-27 01:12:35 +02:00
Bodo Graumann
9afb8ff12a Typescript refactor: Platform select for browser and node (#4500)
* Use string form of filename parameter

This works for the form-data library and is also compatible with the
browser FormData object.

* Add new option to select platform node or browser

When no platform is selected, a default is chosen by the framework
option and likewise the file data type option is implied by the
platform.

* Remove redundant import of node dns module

* Only use form-data library for node platform

* Generate npm package from npmName option

* Use method convertPropertyToBooleanAndWriteBack

* Generate typescript samples with ensure-up-to-date
2020-04-27 00:57:36 +02:00
Bodo Graumann
0000342d77 Typescript refactor: stub rxjs (#4424)
* Remove unused supportsES6 field from codegen

* Add a new switch for RXJS

* Remove redundant npm dependency on rxjs4 types

* Fix return type of PromiseMiddleware methods

* Install webpack dependency to run jquery tests

* Update form-data to 2.5 which includes typings

* Add missing dependency on node typings

* Fix test artifact name typo

* Stub rxjs when it is not explicitly enabled
2020-04-27 00:54:36 +02:00
Bodo Graumann
0f3ad99d72 Refactor typescript merge master (#4319)
Merge master into ts-refactor
2020-04-27 00:54:36 +02:00
Tino Fuhrmann
4f461f948a Updated typescript docs 2020-04-27 00:09:32 +02:00
Tino Fuhrmann
68241f8c33 Fixed missing fetch definition in TS default tests 2020-04-27 00:09:32 +02:00
Tino Fuhrmann
5fd3be29bd Ensured up to date 2020-04-27 00:09:32 +02:00
Tino Fuhrmann
e4a0855db9 Fixed a couple issues with pom.xml 2020-04-27 00:09:31 +02:00
Tino Fuhrmann
9297e59053 Removed tabs in TypeScriptClientCodegen 2020-04-27 00:09:31 +02:00
Tino Fuhrmann
6c37c7180d Added pom.xmls, fixed packagejsons and hopefully webppack 2020-04-27 00:09:31 +02:00
Tino Fuhrmann
fb6f8c5344 Added jquery library 2020-04-27 00:09:31 +02:00
Tino Fuhrmann
8d8e57f1f9 Added gitignore and git_push 2020-04-27 00:09:31 +02:00
Tino Fuhrmann
495ce938f8 Updated docs 2020-04-27 00:09:31 +02:00
Tino Fuhrmann
99c3dceae7 Added typescript to docs/generators 2020-04-27 00:09:18 +02:00
Tino Fuhrmann
fcbecc4dbd Fixed compilation issues in TypeScriptClientCodegen 2020-04-27 00:08:46 +02:00
Tino Fuhrmann
40f3c4f4dd Removed accidentally created generated code 2020-04-27 00:08:46 +02:00
Tino Fuhrmann
c330a9f872 Ignore openapi-generator-cli/bin 2020-04-27 00:08:46 +02:00
Tino Fuhrmann
a481d0ce83 Added comments 2020-04-27 00:08:46 +02:00
Tino Fuhrmann
35d3cc20c9 Added comments & license info 2020-04-27 00:08:46 +02:00
Tino Fuhrmann
7a372acbed Fixed date-time and date handling 2020-04-27 00:08:46 +02:00
Tino Fuhrmann
56ca583b2e Set discriminator value automatically 2020-04-27 00:08:29 +02:00
Tino Fuhrmann
c8c58b4f5e Configure discriminator correctly 2020-04-27 00:08:28 +02:00
Tino Fuhrmann
861f774c56 Made discriminator and attributeTypeMap readonly 2020-04-27 00:08:28 +02:00
Tino Fuhrmann
df970ae8b1 Added promise based middleware 2020-04-27 00:08:28 +02:00
Tino Fuhrmann
1d27563a41 Use observables internally 2020-04-27 00:08:28 +02:00
Tino Fuhrmann
aeef285190 Restructured module layout 2020-04-27 00:08:28 +02:00
Tino Fuhrmann
8068315f79 Remove tab 2020-04-27 00:08:28 +02:00
Tino Fuhrmann
e11a5a9395 Use string union for enums 2020-04-27 00:08:28 +02:00
Tino Fuhrmann
a00e342505 Made api call configuration separately settable 2020-04-27 00:08:28 +02:00
Tino Fuhrmann
7786f2e9fb Fixed file uploads 2020-04-27 00:08:28 +02:00
Tino Fuhrmann
1c2943dcc8 Additional tests for pet store api 2020-04-27 00:08:28 +02:00
Tino Fuhrmann
c5c9a59060 Removed tabs in DefaultCodegen 2020-04-27 00:08:28 +02:00
Tino Fuhrmann
8bfb88cd76 Removed tabs in TypeScriptClientCodegen 2020-04-27 00:08:02 +02:00
Tino Fuhrmann
35b98cf2bc Added handling for different http status codes and test for deletePet 2020-04-27 00:08:02 +02:00
Tino Fuhrmann
9b0bb9a399 Fixed ObjectSerializer test 2020-04-27 00:07:33 +02:00
Tino Fuhrmann
e41df36261 Added simple test for PetApi 2020-04-27 00:07:33 +02:00
Tino Fuhrmann
c2b7422a81 [TS-Refactor] Added tests for Object Serializer 2020-04-27 00:07:33 +02:00
Tino Fuhrmann
525f48d694 Added server variable configuration to ts-refactor 2020-04-27 00:07:33 +02:00
Tino Fuhrmann
0867522b0a Added ts client codegen to root pom.xml and travis 2020-04-27 00:07:33 +02:00
Tino Fuhrmann
988df1f7a5 Removed tabs from TypeScriptClientCodegen 2020-04-27 00:07:21 +02:00
Tino Fuhrmann
4c11314a7b Added pom.xml files to TypeScript PetStore client samples 2020-04-27 00:07:21 +02:00
Tino Fuhrmann
3eaa5e54ef Removed TODOs 2020-04-27 00:07:21 +02:00
Tino Fuhrmann
7909cbaec7 Reverted: http library.send returns string again 2020-04-27 00:07:21 +02:00
Tino Fuhrmann
a6560e5530 Restructured TypeScript generator 2020-04-27 00:07:21 +02:00
Tino Fuhrmann
61a1bbdabe Added middleware to fetch 2020-04-27 00:07:21 +02:00
Tino Fuhrmann
a7de49110e Ignore dist folder in typescript client sample 2020-04-27 00:07:21 +02:00
Tino Fuhrmann
e40d94984f Implemented fetch client 2020-04-27 00:07:21 +02:00
Tino Fuhrmann
a8ec866117 Implemented RequestFactory and Processor completely 2020-04-27 00:07:21 +02:00
Tino Fuhrmann
f5b062957d WIP: api modeling 2020-04-27 00:07:21 +02:00
Tino Fuhrmann
d4fa8c7f72 Updated auth 2020-04-27 00:07:21 +02:00
Tino Fuhrmann
6b2a2289f2 WIP: Models & API 2020-04-27 00:07:20 +02:00
Tino Fuhrmann
b89646a223 Added sample for typescript client 2020-04-27 00:07:20 +02:00
Tino Fuhrmann
276d7d47e5 Added servers 2020-04-27 00:07:20 +02:00
Tino Fuhrmann
1cc6fb0421 Added auth module 2020-04-27 00:07:20 +02:00
Tino Fuhrmann
1a31c48ceb Added model generation with imports 2020-04-27 00:07:20 +02:00
Tino Fuhrmann
6638cef37a Modified http lib, added config & middleware definition to ts-fetch 2020-04-27 00:07:20 +02:00
Tino Fuhrmann
05f64c6732 Added generic enum 2020-04-27 00:07:20 +02:00
Tino Fuhrmann
06d9556f13 Added http module draft 2020-04-27 00:07:20 +02:00
128 changed files with 17890 additions and 5 deletions

View File

@ -21,6 +21,7 @@ cache:
- $HOME/samples/client/petstore/php/OpenAPIToolsClient-php/vendor
- $HOME/samples/client/petstore/ruby/vendor/bundle
- $HOME/samples/client/petstore/python/.venv/
- $HOME/samples/client/petstore/typescript/tests/default/node_modules
- $HOME/samples/client/petstore/typescript-node/npm/node_modules
- $HOME/samples/client/petstore/typescript-node/npm/typings/
- $HOME/samples/client/petstore/typescript-fetch/tests/default/node_modules

37
bin/typescript.sh Executable file
View File

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

View File

@ -50,6 +50,7 @@ declare -a samples=(
#"${root}/bin/php-slim4-server-petstore.sh"
"${root}/bin/php-ze-ph-petstore-server.sh"
"${root}/bin/openapi3/php-petstore.sh"
"${root}/bin/typescript.sh"
"${root}/bin/typescript-angularjs-petstore.sh"
"${root}/bin/typescript-angular-petstore-all.sh"
"${root}/bin/typescript-aurelia-petstore.sh"

View File

@ -62,6 +62,7 @@ The following generators are available:
* [swift3-deprecated (deprecated)](generators/swift3-deprecated.md)
* [swift4](generators/swift4.md)
* [swift5 (beta)](generators/swift5.md)
* [typescript (experimental)](generators/typescript.md)
* [typescript-angular](generators/typescript-angular.md)
* [typescript-angularjs](generators/typescript-angularjs.md)
* [typescript-aurelia](generators/typescript-aurelia.md)

View File

@ -0,0 +1,247 @@
---
title: Config Options for typescript
sidebar_label: typescript
---
| Option | Description | Values | Default |
| ------ | ----------- | ------ | ------- |
|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
|fileContentDataType|Specifies the type to use for the content of a file - i.e. Blob (Browser) / Buffer (node)| |Buffer|
|framework|Specify the framework which should be used in the client code.|<dl><dt>**fetch-api**</dt><dd>fetch-api</dd><dt>**jquery**</dt><dd>jquery</dd></dl>|fetch-api|
|legacyDiscriminatorBehavior|This flag is used by OpenAPITools codegen to influence the processing of the discriminator attribute in OpenAPI documents. This flag has no impact if the OAS document does not use the discriminator attribute. The default value of this flag is set in each language-specific code generator (e.g. Python, Java, go...)using the method toModelName.
When this flag is set to false:
- The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document.
- Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
When this flag is set to true:
- The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
Note to developers supporting a language generator in OpenAPITools: to fully support the discriminator attribute as defined in the OAS specification 3.x, language generators should set this flag to true by default; however this requires updating the mustache templates to generate a language-specific discriminator lookup function that iterates over {{#mappedModels}} and does not iterate over {{children}}, {{#anyOf}}, or {{#oneOf}}.| |true|
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase|
|npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null|
|npmRepository|Use this property to set an url your private npmRepo in the package.json| |null|
|npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0|
|platform|Specifies the platform the code should run on. The default is 'node' for the 'request' framework and 'browser' otherwise.| |null|
|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
|snapshot|When setting this property to true, the version will be suffixed with -SNAPSHOT.yyyyMMddHHmm| |false|
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|supportsES6|Generate code that conforms to ES6.| |false|
|useRxJS|Enable this to internally use rxjs observables. If disabled, a stub is used instead. This is required for the 'angular' framework.| |false|
## IMPORT MAPPING
| Type/Alias | Imports |
| ---------- | ------- |
## INSTANTIATION TYPES
| Type/Alias | Instantiated By |
| ---------- | --------------- |
|array|Array|
## LANGUAGE PRIMITIVES
<ul class="column-ul">
<li>Array</li>
<li>Boolean</li>
<li>Date</li>
<li>Double</li>
<li>Error</li>
<li>File</li>
<li>Float</li>
<li>Integer</li>
<li>Long</li>
<li>Map</li>
<li>Object</li>
<li>String</li>
<li>any</li>
<li>boolean</li>
<li>number</li>
<li>string</li>
</ul>
## RESERVED WORDS
<ul class="column-ul">
<li>abstract</li>
<li>await</li>
<li>boolean</li>
<li>break</li>
<li>byte</li>
<li>case</li>
<li>catch</li>
<li>char</li>
<li>class</li>
<li>const</li>
<li>continue</li>
<li>debugger</li>
<li>default</li>
<li>delete</li>
<li>do</li>
<li>double</li>
<li>else</li>
<li>enum</li>
<li>export</li>
<li>extends</li>
<li>false</li>
<li>final</li>
<li>finally</li>
<li>float</li>
<li>for</li>
<li>formParams</li>
<li>function</li>
<li>goto</li>
<li>headerParams</li>
<li>if</li>
<li>implements</li>
<li>import</li>
<li>in</li>
<li>instanceof</li>
<li>int</li>
<li>interface</li>
<li>let</li>
<li>long</li>
<li>native</li>
<li>new</li>
<li>null</li>
<li>package</li>
<li>private</li>
<li>protected</li>
<li>public</li>
<li>queryParameters</li>
<li>requestOptions</li>
<li>return</li>
<li>short</li>
<li>static</li>
<li>super</li>
<li>switch</li>
<li>synchronized</li>
<li>this</li>
<li>throw</li>
<li>transient</li>
<li>true</li>
<li>try</li>
<li>typeof</li>
<li>useFormData</li>
<li>var</li>
<li>varLocalDeferred</li>
<li>varLocalPath</li>
<li>void</li>
<li>volatile</li>
<li>while</li>
<li>with</li>
<li>yield</li>
</ul>
## FEATURE SET
### Client Modification Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasePath|✗|ToolingExtension
|Authorizations|✗|ToolingExtension
|UserAgent|✗|ToolingExtension
### Data Type Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Custom|✗|OAS2,OAS3
|Int32|✓|OAS2,OAS3
|Int64|✓|OAS2,OAS3
|Float|✓|OAS2,OAS3
|Double|✓|OAS2,OAS3
|Decimal|✓|ToolingExtension
|String|✓|OAS2,OAS3
|Byte|✓|OAS2,OAS3
|Binary|✓|OAS2,OAS3
|Boolean|✓|OAS2,OAS3
|Date|✓|OAS2,OAS3
|DateTime|✓|OAS2,OAS3
|Password|✓|OAS2,OAS3
|File|✓|OAS2
|Array|✓|OAS2,OAS3
|Maps|✓|ToolingExtension
|CollectionFormat|✓|OAS2
|CollectionFormatMulti|✓|OAS2
|Enum|✓|OAS2,OAS3
|ArrayOfEnum|✓|ToolingExtension
|ArrayOfModel|✓|ToolingExtension
|ArrayOfCollectionOfPrimitives|✓|ToolingExtension
|ArrayOfCollectionOfModel|✓|ToolingExtension
|ArrayOfCollectionOfEnum|✓|ToolingExtension
|MapOfEnum|✓|ToolingExtension
|MapOfModel|✓|ToolingExtension
|MapOfCollectionOfPrimitives|✓|ToolingExtension
|MapOfCollectionOfModel|✓|ToolingExtension
|MapOfCollectionOfEnum|✓|ToolingExtension
### Documentation Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Readme|✗|ToolingExtension
|Model|✓|ToolingExtension
|Api|✓|ToolingExtension
### Global Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Host|✓|OAS2,OAS3
|BasePath|✓|OAS2,OAS3
|Info|✓|OAS2,OAS3
|Schemes|✗|OAS2,OAS3
|PartialSchemes|✓|OAS2,OAS3
|Consumes|✓|OAS2
|Produces|✓|OAS2
|ExternalDocumentation|✓|OAS2,OAS3
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer|✗|OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✓|OAS3
|LinkObjects|✗|OAS3
### Parameter Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Path|✓|OAS2,OAS3
|Query|✓|OAS2,OAS3
|Header|✓|OAS2,OAS3
|Body|✓|OAS2
|FormUnencoded|✓|OAS2
|FormMultipart|✓|OAS2
|Cookie|✓|OAS3
### Schema Support Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Simple|✓|OAS2,OAS3
|Composite|✓|OAS2,OAS3
|Polymorphism|✓|OAS2,OAS3
|Union|✗|OAS3
### Security Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|BasicAuth|✓|OAS2,OAS3
|ApiKey|✓|OAS2,OAS3
|OpenIDConnect|✗|OAS3
|BearerToken|✓|OAS3
|OAuth2_Implicit|✓|OAS2,OAS3
|OAuth2_Password|✓|OAS2,OAS3
|OAuth2_ClientCredentials|✓|OAS2,OAS3
|OAuth2_AuthorizationCode|✓|OAS2,OAS3
### Wire Format Feature
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|JSON|✓|OAS2,OAS3
|XML|✓|OAS2,OAS3
|PROTOBUF|✗|ToolingExtension
|Custom|✗|OAS2,OAS3

View File

@ -30,8 +30,8 @@ public class CodegenOperation {
isResponseBinary = false, isResponseFile = false, hasReference = false,
isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy,
isRestful, isDeprecated, isCallbackRequest;
public String path, operationId, returnType, httpMethod, returnBaseType,
returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse;
public String path, operationId, returnType, returnFormat, httpMethod, returnBaseType,
returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse;
public CodegenDiscriminator discriminator;
public List<Map<String, String>> consumes, produces, prioritizedContentTypes;
public List<CodegenServer> servers = new ArrayList<CodegenServer>();

View File

@ -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<Map<String, Object>> examples;
public String dataType;

View File

@ -3327,8 +3327,9 @@ public class DefaultCodegen implements CodegenConfig {
op.examples = new ExampleGenerator(schemas, this.openAPI).generateFromResponseSchema(exampleStatusCode, responseSchema, getProducesInfo(this.openAPI, operation));
op.defaultResponse = toDefaultValue(responseSchema);
op.returnType = cm.dataType;
op.hasReference = schemas.containsKey(op.returnBaseType);
op.returnFormat = cm.dataFormat;
op.hasReference = schemas != null && schemas.containsKey(op.returnBaseType);
// lookup discriminator
Schema schema = schemas.get(op.returnBaseType);
if (schema != null) {
@ -3686,6 +3687,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) {
@ -4208,7 +4210,7 @@ public class DefaultCodegen implements CodegenConfig {
return false;
}
}
// TODO revise below as it should be replaced by ModelUtils.isFileSchema(parameterSchema)
public boolean isDataTypeFile(String dataType) {
if (dataType != null) {

View File

@ -0,0 +1,870 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.NumberSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class TypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptClientCodegen.class);
private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value";
private static final String UNDEFINED_VALUE = "undefined";
private static final String FRAMEWORK_SWITCH = "framework";
private static final String FRAMEWORK_SWITCH_DESC = "Specify the framework which should be used in the client code.";
private static final String[] FRAMEWORKS = { "fetch-api", "jquery" };
private static final String PLATFORM_SWITCH = "platform";
private static final String PLATFORM_SWITCH_DESC = "Specifies the platform the code should run on. The default is 'node' for the 'request' framework and 'browser' otherwise.";
private static final String[] PLATFORMS = { "browser", "node" };
private static final String FILE_CONTENT_DATA_TYPE= "fileContentDataType";
private static final String FILE_CONTENT_DATA_TYPE_DESC = "Specifies the type to use for the content of a file - i.e. Blob (Browser) / Buffer (node)";
private static final String USE_RXJS_SWITCH = "useRxJS";
private static final String USE_RXJS_SWITCH_DESC = "Enable this to internally use rxjs observables. If disabled, a stub is used instead. This is required for the 'angular' framework.";
private final Map<String, String> frameworkToHttpLibMap;
// NPM Options
private static final String SNAPSHOT = "snapshot";
@SuppressWarnings("squid:S5164")
protected static final ThreadLocal<SimpleDateFormat> SNAPSHOT_SUFFIX_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT));
private static final String NPM_REPOSITORY = "npmRepository";
private static final String NPM_NAME = "npmName";
private static final String NPM_VERSION = "npmVersion";
// NPM Option Values
protected String npmRepository = null;
protected String snapshot = null;
protected String npmName = null;
protected String npmVersion = "1.0.0";
protected String modelPropertyNaming = "camelCase";
protected HashSet<String> languageGenericTypes;
public TypeScriptClientCodegen() {
super();
this.frameworkToHttpLibMap = new HashMap<>();
this.frameworkToHttpLibMap.put("fetch-api", "isomorphic-fetch");
this.frameworkToHttpLibMap.put("jquery", "jquery");
this.generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata).stability(Stability.EXPERIMENTAL).build();
// clear import mapping (from default generator) as TS does not use it
// at the moment
importMapping.clear();
outputFolder = "generated-code/typescript";
embeddedTemplateDir = templateDir = "typescript";
supportsInheritance = true;
// NOTE: TypeScript uses camel cased reserved words, while models are title cased. We don't want lowercase comparisons.
reservedWords.addAll(Arrays.asList(
// local variable names used in API methods (endpoints)
"varLocalPath", "queryParameters", "headerParams", "formParams", "useFormData", "varLocalDeferred",
"requestOptions",
// Typescript reserved words
"abstract", "await", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", "yield"));
languageSpecificPrimitives = new HashSet<>(Arrays.asList(
"string",
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"Object",
"Array",
"Date",
"number",
"any",
"File",
"Error",
"Map"
));
languageGenericTypes = new HashSet<String>(Arrays.asList(
"Array"
));
instantiationTypes.put("array", "Array");
typeMapping = new HashMap<String, String>();
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("date", "string");
typeMapping.put("DateTime", "Date");
typeMapping.put("binary", "any");
// TODO: allow other types for file e.g. Blob
typeMapping.put("File", "any");
typeMapping.put("ByteArray", "string");
typeMapping.put("UUID", "string");
typeMapping.put("Error", "Error");
cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package." +
" Required to generate a full package"));
cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package. If not provided, using the version from the OpenAPI specification file.").defaultValue(this.getNpmVersion()));
cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json"));
cliOptions.add(CliOption.newBoolean(SNAPSHOT,
"When setting this property to true, the version will be suffixed with -SNAPSHOT." + this.SNAPSHOT_SUFFIX_FORMAT.get().toPattern(),
false));
cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue("camelCase"));
cliOptions.add(new CliOption(CodegenConstants.SUPPORTS_ES6, CodegenConstants.SUPPORTS_ES6_DESC).defaultValue("false"));
cliOptions.add(new CliOption(TypeScriptClientCodegen.FILE_CONTENT_DATA_TYPE, TypeScriptClientCodegen.FILE_CONTENT_DATA_TYPE_DESC).defaultValue("Buffer"));
cliOptions.add(new CliOption(TypeScriptClientCodegen.USE_RXJS_SWITCH, TypeScriptClientCodegen.USE_RXJS_SWITCH_DESC).defaultValue("false"));
CliOption frameworkOption = new CliOption(TypeScriptClientCodegen.FRAMEWORK_SWITCH, TypeScriptClientCodegen.FRAMEWORK_SWITCH_DESC);
for (String option: TypeScriptClientCodegen.FRAMEWORKS) {
// TODO: improve description?
frameworkOption.addEnum(option, option);
}
frameworkOption.defaultValue(FRAMEWORKS[0]);
cliOptions.add(new CliOption(TypeScriptClientCodegen.PLATFORM_SWITCH, TypeScriptClientCodegen.PLATFORM_SWITCH_DESC));
CliOption platformOption = new CliOption(TypeScriptClientCodegen.PLATFORM_SWITCH, TypeScriptClientCodegen.PLATFORM_SWITCH_DESC);
for (String option: TypeScriptClientCodegen.PLATFORMS) {
// TODO: improve description?
platformOption.addEnum(option, option);
}
platformOption.defaultValue(PLATFORMS[0]);
cliOptions.add(frameworkOption);
// TODO: gen package.json?
//Documentation
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("tsconfig.mustache", "", "tsconfig.json"));
supportingFiles.add(new SupportingFile(".gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
// 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/servers.mustache", "servers.ts"));
supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.ts"));
supportingFiles.add(new SupportingFile("auth" + File.separator + "auth.mustache", "auth", "auth.ts"));
supportingFiles.add(new SupportingFile("model/models_all.mustache", "models", "all.ts"));
// TODO: add supporting files depending on cli parameter e.g. fetch vs angular
supportingFiles.add(new SupportingFile("generators/types/PromiseAPI.mustache", "types", "PromiseAPI.ts"));
supportingFiles.add(new SupportingFile("generators/types/ObservableAPI.mustache", "types", "ObservableAPI.ts"));
// models
// TODO: properly set model and api packages
this.setModelPackage("");
supportingFiles.add(new SupportingFile("model/ObjectSerializer.mustache", "models", "ObjectSerializer.ts"));
modelTemplateFiles.put("model/model.mustache", ".ts");
// api
this.setApiPackage("");
supportingFiles.add(new SupportingFile("api/middleware.mustache", "", "middleware.ts"));
this.supportingFiles.add(new SupportingFile("api/baseapi.mustache", "apis", "baseapi.ts"));
this.apiTemplateFiles.put("api/api.mustache", ".ts");
}
public String getNpmName() {
return npmName;
}
public void setNpmName(String npmName) {
this.npmName = npmName;
}
public String getNpmRepository() {
return npmRepository;
}
public void setNpmRepository(String npmRepository) {
this.npmRepository = npmRepository;
}
public String getNpmVersion() {
return npmVersion;
}
public void setNpmVersion(String npmVersion) {
this.npmVersion = npmVersion;
}
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
if (additionalProperties.containsKey(NPM_NAME)) {
// If no npmVersion is provided in additional properties, version from API specification is used.
// If none of them is provided then fallbacks to default version
if (additionalProperties.containsKey(NPM_VERSION)) {
this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString());
} else if (openAPI.getInfo() != null && openAPI.getInfo().getVersion() != null) {
this.setNpmVersion(openAPI.getInfo().getVersion());
}
if (additionalProperties.containsKey(SNAPSHOT) && Boolean.parseBoolean(additionalProperties.get(SNAPSHOT).toString())) {
if (npmVersion.toUpperCase(Locale.ROOT).matches("^.*-SNAPSHOT$")) {
this.setNpmVersion(npmVersion + "." + SNAPSHOT_SUFFIX_FORMAT.get().format(new Date()));
} else {
this.setNpmVersion(npmVersion + "-SNAPSHOT." + SNAPSHOT_SUFFIX_FORMAT.get().format(new Date()));
}
}
additionalProperties.put(NPM_VERSION, npmVersion);
}
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
final Object propFramework = additionalProperties.get(FRAMEWORK_SWITCH);
Map<String, Boolean> frameworks = new HashMap<>();
for (String framework: FRAMEWORKS) {
frameworks.put(framework, framework.equals(propFramework));
}
objs.put("framework", propFramework);
objs.put("frameworks", frameworks);
objs.put("fileContentDataType", additionalProperties.get(FILE_CONTENT_DATA_TYPE));
return objs;
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> operations, List<Object> models) {
// Add additional filename information for model imports in the apis
List<Map<String, Object>> imports = (List<Map<String, Object>>) operations.get("imports");
for (Map<String, Object> im : imports) {
im.put("filename", ((String) im.get("import")).replace('.', '/'));
im.put("classname", getModelnameFromModelFilename(im.get("import").toString()));
}
@SuppressWarnings("unchecked")
Map<String, Object> operationsMap = (Map<String, Object>) operations.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operationsMap.get("operation");
for (CodegenOperation operation: operationList) {
List<CodegenResponse> responses = operation.responses;
operation.returnType = this.getReturnType(responses);
}
return operations;
}
private String getReturnType(List<CodegenResponse> 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);
}
@Override
public String escapeReservedWord(String name) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@Override
public String toParamName(String name) {
// should be the same as variable name
return toVarName(name);
}
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name);
if ("_".equals(name)) {
name = "_u";
}
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;
}
name = getNameUsingModelPropertyNaming(name);
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toModelName(String name) {
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}
if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}
// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
String modelName = camelize("model_" + name);
LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
// model name starts with number
if (name.matches("^\\d.*")) {
String modelName = camelize("model_" + name); // e.g. 200Response => Model200Response (after camelize)
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName);
return modelName;
}
if (languageSpecificPrimitives.contains(name)) {
String modelName = camelize("model_" + name);
LOGGER.warn(name + " (model name matches existing language type) cannot be used as a model name. Renamed to " + modelName);
return modelName;
}
// 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
protected String getParameterDataType(Parameter parameter, Schema p) {
// handle enums of various data types
Schema inner;
if (ModelUtils.isArraySchema(p)) {
ArraySchema mp1 = (ArraySchema) p;
inner = mp1.getItems();
return this.getSchemaType(p) + "<" + this.getParameterDataType(parameter, inner) + ">";
} else if (ModelUtils.isMapSchema(p)) {
inner = (Schema) p.getAdditionalProperties();
return "{ [key: string]: " + this.getParameterDataType(parameter, inner) + "; }";
} else if (ModelUtils.isStringSchema(p)) {
// Handle string enums
if (p.getEnum() != null) {
return enumValuesToEnumTypeUnion(p.getEnum(), "string");
}
} else if (ModelUtils.isIntegerSchema(p)) {
// Handle integer enums
if (p.getEnum() != null) {
return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
}
} else if (ModelUtils.isNumberSchema(p)) {
// Handle double enums
if (p.getEnum() != null) {
return numericEnumValuesToEnumTypeUnion(new ArrayList<Number>(p.getEnum()));
}
}
/* TODO revise the logic below
else if (ModelUtils.isDateSchema(p)) {
// Handle date enums
DateSchema sp = (DateSchema) p;
if (sp.getEnum() != null) {
return enumValuesToEnumTypeUnion(sp.getEnum(), "string");
}
} else if (ModelUtils.isDateTimeSchema(p)) {
// Handle datetime enums
DateTimeSchema sp = (DateTimeSchema) p;
if (sp.getEnum() != null) {
return enumValuesToEnumTypeUnion(sp.getEnum(), "string");
}
}*/
return this.getTypeDeclaration(p);
}
/**
* Converts a list of strings to a literal union for representing enum values as a type.
* Example output: 'available' | 'pending' | 'sold'
*
* @param values list of allowed enum values
* @param dataType either "string" or "number"
* @return a literal union for representing enum values as a type
*/
protected String enumValuesToEnumTypeUnion(List<String> values, String dataType) {
StringBuilder b = new StringBuilder();
boolean isFirst = true;
for (String value : values) {
if (!isFirst) {
b.append(" | ");
}
b.append(toEnumValue(value.toString(), dataType));
isFirst = false;
}
return b.toString();
}
/**
* Converts a list of numbers to a literal union for representing enum values as a type.
* Example output: 3 | 9 | 55
*
* @param values a list of numbers
* @return a literal union for representing enum values as a type
*/
protected String numericEnumValuesToEnumTypeUnion(List<Number> values) {
List<String> stringValues = new ArrayList<>();
for (Number value : values) {
stringValues.add(value.toString());
}
return enumValuesToEnumTypeUnion(stringValues, "number");
}
@Override
public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) {
return UNDEFINED_VALUE;
} else if (ModelUtils.isDateSchema(p)) {
return UNDEFINED_VALUE;
} else if (ModelUtils.isDateTimeSchema(p)) {
return UNDEFINED_VALUE;
} else if (ModelUtils.isNumberSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
return UNDEFINED_VALUE;
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
}
return UNDEFINED_VALUE;
} else if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "'" + (String) p.getDefault() + "'";
}
return UNDEFINED_VALUE;
} else {
return UNDEFINED_VALUE;
}
}
@Override
protected boolean isReservedWord(String word) {
// NOTE: This differs from super's implementation in that TypeScript does _not_ want case insensitive matching.
return reservedWords.contains(word);
}
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
String type = null;
if (typeMapping.containsKey(openAPIType)) {
type = typeMapping.get(openAPIType);
if (languageSpecificPrimitives.contains(type))
return type;
} else
type = openAPIType;
return toModelName(type);
}
@Override
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
throw new RuntimeException("Empty method name (operationId) not allowed");
}
// method name cannot use reserved keyword, e.g. return
// append _ at the beginning, e.g. _return
if (isReservedWord(operationId)) {
return escapeReservedWord(camelize(sanitizeName(operationId), true));
}
return camelize(sanitizeName(operationId), true);
}
public void setModelPropertyNaming(String naming) {
if ("original".equals(naming) || "camelCase".equals(naming) ||
"PascalCase".equals(naming) || "snake_case".equals(naming)) {
this.modelPropertyNaming = naming;
} else {
throw new IllegalArgumentException("Invalid model property naming '" +
naming + "'. Must be 'original', 'camelCase', " +
"'PascalCase' or 'snake_case'");
}
}
public String getModelPropertyNaming() {
return this.modelPropertyNaming;
}
public String getNameUsingModelPropertyNaming(String name) {
switch (CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.valueOf(getModelPropertyNaming())) {
case original:
return name;
case camelCase:
return camelize(name, true);
case PascalCase:
return camelize(name);
case snake_case:
return underscore(name);
default:
throw new IllegalArgumentException("Invalid model property naming '" +
name + "'. Must be 'original', 'camelCase', " +
"'PascalCase' or 'snake_case'");
}
}
@Override
public String toEnumValue(String value, String datatype) {
if ("number".equals(datatype)) {
return value;
} else {
return "\'" + escapeText(value) + "\'";
}
}
@Override
public String toEnumDefaultValue(String value, String datatype) {
return datatype + "_" + value;
}
@Override
public String toEnumVarName(String name, String datatype) {
if (name.length() == 0) {
return "Empty";
}
// for symbol, e.g. $, #
if (getSymbolName(name) != null) {
return camelize(getSymbolName(name));
}
// number
if ("number".equals(datatype)) {
String varName = "NUMBER_" + name;
varName = varName.replaceAll("-", "MINUS_");
varName = varName.replaceAll("\\+", "PLUS_");
varName = varName.replaceAll("\\.", "_DOT_");
return varName;
}
// string
String enumName = sanitizeName(name);
enumName = enumName.replaceFirst("^_", "");
enumName = enumName.replaceFirst("_$", "");
// camelize the enum variable name
// ref: https://basarat.gitbooks.io/typescript/content/docs/enums.html
enumName = camelize(enumName);
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public String toEnumName(CodegenProperty property) {
String enumName = toModelName(property.name) + "Enum";
if (enumName.matches("\\d.*")) { // starts with number
return "_" + enumName;
} else {
return enumName;
}
}
@Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) {
// process enum in models
List<Map<String, Object>> models = (List<Map<String, Object>>) postProcessModelsEnum(objs).get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
cm.imports = new TreeSet(cm.imports);
// name enum with model name, e.g. StatusEnum => Pet.StatusEnum
for (CodegenProperty var : cm.vars) {
if (Boolean.TRUE.equals(var.isEnum)) {
var.datatypeWithEnum = var.datatypeWithEnum.replace(var.enumName, cm.classname + var.enumName);
}
}
if (cm.parent != null) {
for (CodegenProperty var : cm.allVars) {
if (Boolean.TRUE.equals(var.isEnum)) {
var.datatypeWithEnum = var.datatypeWithEnum
.replace(var.enumName, cm.classname + var.enumName);
}
}
}
}
for (Map<String, Object> mo : models) {
CodegenModel cm = (CodegenModel) mo.get("model");
// Add additional filename information for imports
mo.put("tsImports", toTsImports(cm, cm.imports));
}
return objs;
}
private List<Map<String, String>> toTsImports(CodegenModel cm, Set<String> imports) {
List<Map<String, String>> tsImports = new ArrayList<>();
for (String im : imports) {
if (!im.equals(cm.classname)) {
HashMap<String, String> tsImport = new HashMap<>();
// TVG: This is used as class name in the import statements of the model file
tsImport.put("classname", im);
tsImport.put("filename", toModelFilename(im));
tsImports.add(tsImport);
}
}
return tsImports;
}
@Override
public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
Map<String, Object> result = super.postProcessAllModels(objs);
for (Map.Entry<String, Object> entry : result.entrySet()) {
Map<String, Object> inner = (Map<String, Object>) entry.getValue();
List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models");
for (Map<String, Object> mo : models) {
CodegenModel cm = (CodegenModel) mo.get("model");
if (cm.discriminator != null && cm.children != null) {
for (CodegenModel child : cm.children) {
this.setDiscriminatorValue(child, cm.discriminator.getPropertyName(), this.getDiscriminatorValue(child));
}
}
}
}
return result;
}
private void setDiscriminatorValue(CodegenModel model, String baseName, String value) {
for (CodegenProperty prop : model.allVars) {
if (prop.baseName.equals(baseName)) {
prop.discriminatorValue = value;
}
}
if (model.children != null) {
final boolean newDiscriminator = model.discriminator != null;
for (CodegenModel child : model.children) {
this.setDiscriminatorValue(child, baseName, newDiscriminator ? value : this.getDiscriminatorValue(child));
}
}
}
private String getDiscriminatorValue(CodegenModel model) {
return model.vendorExtensions.containsKey(X_DISCRIMINATOR_TYPE) ?
(String) model.vendorExtensions.get(X_DISCRIMINATOR_TYPE) : model.classname;
}
@Override
public String escapeQuotationMark(String input) {
// remove ', " to avoid code injection
return input.replace("\"", "").replace("'", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@Override
public String getName() {
return "typescript";
}
@Override
public String getHelp() {
return "Generates a TypeScript client library using Fetch API (beta).";
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) {
setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING));
}
convertPropertyToBooleanAndWriteBack(CodegenConstants.SUPPORTS_ES6);
// change package names
apiPackage = this.apiPackage + ".apis";
modelPackage = this.modelPackage + ".models";
testPackage = this.testPackage + ".tests";
additionalProperties.putIfAbsent(FRAMEWORK_SWITCH, FRAMEWORKS[0]);
supportingFiles.add(new SupportingFile(
"generators" + File.separator + additionalProperties.get(FRAMEWORK_SWITCH) + ".mustache",
"index.ts"
));
String httpLibName = this.getHttpLibForFramework(additionalProperties.get(FRAMEWORK_SWITCH).toString());
supportingFiles.add(new SupportingFile(
"http" + File.separator + httpLibName + ".mustache",
"http", httpLibName + ".ts"
));
Object propPlatform = additionalProperties.get(PLATFORM_SWITCH);
if (propPlatform == null) {
propPlatform = "browser";
additionalProperties.put("platform", propPlatform);
}
Map<String, Boolean> platforms = new HashMap<>();
for (String platform: PLATFORMS) {
platforms.put(platform, platform.equals(propPlatform));
}
additionalProperties.put("platforms", platforms);
additionalProperties.putIfAbsent(FILE_CONTENT_DATA_TYPE, propPlatform.equals("node") ? "Buffer" : "Blob");
final boolean useRxJS = convertPropertyToBooleanAndWriteBack(USE_RXJS_SWITCH);
if (!useRxJS) {
supportingFiles.add(new SupportingFile("rxjsStub.mustache", "", "rxjsStub.ts"));
}
// NPM Settings
if (additionalProperties.containsKey(NPM_NAME)) {
setNpmName(additionalProperties.get(NPM_NAME).toString());
}
if (additionalProperties.containsKey(NPM_VERSION)) {
setNpmVersion(additionalProperties.get(NPM_VERSION).toString());
}
if (additionalProperties.containsKey(NPM_REPOSITORY)) {
setNpmRepository(additionalProperties.get(NPM_REPOSITORY).toString());
}
}
private String getHttpLibForFramework(String object) {
return this.frameworkToHttpLibMap.get(object);
}
@Override
public String getTypeDeclaration(Schema p) {
Schema inner;
if (ModelUtils.isArraySchema(p)) {
inner = ((ArraySchema) p).getItems();
return this.getSchemaType(p) + "<" + this.getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) {
inner = (Schema) p.getAdditionalProperties();
return "{ [key: string]: " + this.getTypeDeclaration(inner) + "; }";
} else if (ModelUtils.isFileSchema(p)) {
// TODO: Change type declaration
return "HttpFile";
} else if (ModelUtils.isBinarySchema(p)) {
return "any";
} else {
return super.getTypeDeclaration(p);
}
}
@Override
protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) {
codegenModel.additionalPropertiesType = getTypeDeclaration((Schema) schema.getAdditionalProperties());
addImport(codegenModel, codegenModel.additionalPropertiesType);
}
}

View File

@ -113,6 +113,7 @@ org.openapitools.codegen.languages.SwiftClientCodegen
org.openapitools.codegen.languages.Swift3Codegen
org.openapitools.codegen.languages.Swift4Codegen
org.openapitools.codegen.languages.Swift5ClientCodegen
org.openapitools.codegen.languages.TypeScriptClientCodegen
org.openapitools.codegen.languages.TypeScriptAngularClientCodegen
org.openapitools.codegen.languages.TypeScriptAngularJsClientCodegen
org.openapitools.codegen.languages.TypeScriptAureliaClientCodegen

View File

@ -0,0 +1 @@
dist

View File

@ -0,0 +1,30 @@
## {{npmName}}@{{npmVersion}}
This generator creates TypeScript/JavaScript client that utilizes {{framework}}.
### Building
To build and compile the typescript sources to javascript use:
```
npm install
npm run build
```
### Publishing
First build the package then run ```npm publish```
### Consuming
navigate to the folder of your consuming project and run one of the following commands.
_published:_
```
npm install {{npmName}}@{{npmVersion}} --save
```
_unPublished (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE --save

View File

@ -0,0 +1,190 @@
// TODO: better import syntax?
import { BaseAPIRequestFactory, RequiredError } from './baseapi';
import {Configuration} from '../configuration';
import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http';
{{#platforms}}
{{#node}}
import * as FormData from "form-data";
{{/node}}
{{/platforms}}
import {ObjectSerializer} from '../models/ObjectSerializer';
import {ApiException} from './exception';
import {isCodeInRange} from '../util';
{{#imports}}
import { {{classname}} } from '..{{filename}}';
{{/imports}}
{{#operations}}
/**
* {{#description}}{{{description}}}{{/description}}{{^description}}no description{{/description}}
*/
export class {{classname}}RequestFactory extends BaseAPIRequestFactory {
{{#operation}}
/**
{{#notes}}
* {{&notes}}
{{/notes}}
{{#summary}}
* {{&summary}}
{{/summary}}
{{#allParams}}
* @param {{paramName}} {{description}}
{{/allParams}}
*/
public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: Configuration): RequestContext {
let config = options || this.configuration;
{{#allParams}}
{{#required}}
// verify required parameter '{{paramName}}' is not null or undefined
if ({{paramName}} === null || {{paramName}} === undefined) {
throw new RequiredError('Required parameter {{paramName}} was null or undefined when calling {{nickname}}.');
}
{{/required}}
{{/allParams}}
// Path Params
const localVarPath = '{{{path}}}'{{#pathParams}}
.replace('{' + '{{baseName}}' + '}', encodeURIComponent(String({{paramName}}))){{/pathParams}};
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.{{httpMethod}});
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
{{#queryParams}}
if ({{paramName}} !== undefined) {
requestContext.setQueryParam("{{baseName}}", ObjectSerializer.serialize({{paramName}}, "{{{dataType}}}", "{{dataFormat}}"));
}
{{/queryParams}}
// Header Params
{{#headerParams}}
requestContext.setHeaderParam("{{baseName}}", ObjectSerializer.serialize({{paramName}}, "{{{dataType}}}", "{{dataFormat}}"));
{{/headerParams}}
// Form Params
{{#hasFormParams}}
let localVarFormParams = new FormData();
{{/hasFormParams}}
{{#formParams}}
{{#isListContainer}}
if ({{paramName}}) {
{{#isCollectionFormatMulti}}
{{paramName}}.forEach((element) => {
localVarFormParams.append('{{baseName}}', element as any);
})
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
// TODO: replace .append with .set
localVarFormParams.append('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]));
{{/isCollectionFormatMulti}}
}
{{/isListContainer}}
{{^isListContainer}}
if ({{paramName}} !== undefined) {
// TODO: replace .append with .set
{{^isFile}}
localVarFormParams.append('{{baseName}}', {{paramName}} as any);
{{/isFile}}
{{#isFile}}
localVarFormParams.append('{{baseName}}', {{paramName}}.data, {{paramName}}.name);
{{/isFile}}
}
{{/isListContainer}}
{{/formParams}}
{{#hasFormParams}}
requestContext.setBody(localVarFormParams);
{{/hasFormParams}}
// Body Params
{{#bodyParam}}
{{^consumes}}
requestContext.setHeaderParam("Content-Type", "application/json");
{{/consumes}}
{{#consumes.0}}
requestContext.setHeaderParam("Content-Type", "{{{mediaType}}}");
{{/consumes.0}}
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"{{dataType}}" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify({{paramName}} || {}) : ({{paramName}}.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
{{/bodyParam}}
{{#hasAuthMethods}}
let authMethod = null;
{{/hasAuthMethods}}
// Apply auth methods
{{#authMethods}}
authMethod = config.authMethods["{{name}}"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
{{/authMethods}}
return requestContext;
}
{{/operation}}
}
{{/operations}}
{{#operations}}
export class {{classname}}ResponseProcessor {
{{#operation}}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to {{nicknam}}
* @throws ApiException if the response code was not in [200, 299]
*/
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}}}", "{{returnFormat}}") as {{{dataType}}};
{{#isSuccessCode}}
return body;
{{/isSuccessCode}}
{{^isSuccessCode}}
throw new ApiException<{{{dataType}}}>({{code}}, body);
{{/isSuccessCode}}
{{/dataType}}
{{^dataType}}
{{#isSuccessCode}}
return;
{{/isSuccessCode}}
{{^isSuccessCode}}
throw new ApiException<string>(response.httpStatusCode, "{{message}}");
{{/isSuccessCode}}
{{/dataType}}
}
{{/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}}}", "{{returnFormat}}") as {{{returnType}}};
return body;
{{/returnType}}
{{^returnType}}
return;
{{/returnType}}
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
{{/operation}}
}
{{/operations}}

View File

@ -0,0 +1,37 @@
import { Configuration } from '../configuration'
/**
*
* @export
*/
export const COLLECTION_FORMATS = {
csv: ",",
ssv: " ",
tsv: "\t",
pipes: "|",
};
/**
*
* @export
* @class BaseAPI
*/
export class BaseAPIRequestFactory {
constructor(protected configuration: Configuration) {
}
};
/**
*
* @export
* @class RequiredError
* @extends {Error}
*/
export class RequiredError extends Error {
name: "RequiredError" = "RequiredError";
constructor(public field: string, msg?: string) {
super(msg);
}
}

View File

@ -0,0 +1,14 @@
/**
* Represents an error caused by an api call i.e. it has attributes for a HTTP status code
* and the returned body object.
*
* Example
* API returns a ErrorMessageObject whenever HTTP status code is not in [200, 299]
* => ApiException(404, someErrorMessageObject)
*
*/
export class ApiException<T> extends Error {
public constructor(public code: number, public body: T) {
super("HTTP-Code: " + code + "\nMessage: " + JSON.stringify(body))
}
}

View File

@ -0,0 +1,66 @@
import {RequestContext, ResponseContext} from './http/http';
import { Observable, from } from {{#useRxJS}}'rxjs'{{/useRxJS}}{{^useRxJS}}'./rxjsStub'{{/useRxJS}};
/**
* Defines the contract for a middleware intercepting requests before
* they are sent (but after the RequestContext was created)
* and before the ResponseContext is unwrapped.
*
*/
export interface Middleware {
/**
* Modifies the request before the request is sent.
*
* @param context RequestContext of a request which is about to be sent to the server
* @returns an observable of the updated request context
*
*/
pre(context: RequestContext): Observable<RequestContext>;
/**
* Modifies the returned response before it is deserialized.
*
* @param context ResponseContext of a sent request
* @returns an observable of the modified response context
*/
post(context: ResponseContext): Observable<ResponseContext>;
}
export class PromiseMiddlewareWrapper implements Middleware {
public constructor(private middleware: PromiseMiddleware) {
}
pre(context: RequestContext): Observable<RequestContext> {
return from(this.middleware.pre(context));
}
post(context: ResponseContext): Observable<ResponseContext> {
return from(this.middleware.post(context));
}
}
/**
* Defines the contract for a middleware intercepting requests before
* they are sent (but after the RequestContext was created)
* and before the ResponseContext is unwrapped.
*
*/
export interface PromiseMiddleware {
/**
* Modifies the request before the request is sent.
*
* @param context RequestContext of a request which is about to be sent to the server
* @returns an observable of the updated request context
*
*/
pre(context: RequestContext): Promise<RequestContext>;
/**
* Modifies the returned response before it is deserialized.
*
* @param context ResponseContext of a sent request
* @returns an observable of the modified response context
*/
post(context: ResponseContext): Promise<ResponseContext>;
}

View File

@ -0,0 +1,152 @@
import {RequestContext} from '../http/http';
// typings for btoa are incorrect
//@ts-ignore
import * as btoa from "btoa";
/**
* Base class for all authentication schemes.
*
*/
export abstract class SecurityAuthentication {
public constructor(private name: string) {
}
/*
*
* @return returns the name of the security authentication as specified in OAI
*/
public getName(): string {
return this.name;
}
/**
* Applies the authentication scheme to the request context
*
* @params context the request context which should use this authentication scheme
*/
public abstract applySecurityAuthentication(context: RequestContext): void;
}
/**
* Applies no authentication.
*
*/
export class NoAuthentication extends SecurityAuthentication {
public constructor() {
super("_no_auth");
}
public applySecurityAuthentication(_context: RequestContext) {
}
}
/**
* Applies an api key to the request context.
*
*/
export class APIKeyAuthentication extends SecurityAuthentication {
/**
* Configures this api key authentication with the necessary properties
*
* @param authName: name of this authentication scheme as specified in the swagger.json
* @param paramName: Parameter name used for the api key
* @param keyLocation: Parameter location, either query, header or cookie.
* @param apiKey: The api key to be used for every request
*/
public constructor(authName: string, private paramName: string, private keyLocation: "query" | "header" | "cookie", private apiKey: string) {
super(authName);
}
public applySecurityAuthentication(context: RequestContext) {
if (this.keyLocation === "header") {
context.setHeaderParam(this.paramName, this.apiKey);
} else if (this.keyLocation === "cookie") {
context.addCookie(this.paramName, this.apiKey);
} else if (this.keyLocation === "query") {
context.setQueryParam(this.paramName, this.apiKey);
}
}
}
/**
* Applies basic http authentication to a request.
*
*/
export class HttpBasicAuthentication extends SecurityAuthentication {
/**
* Configures the http authentication with the required details.
*
*
* @param authName name of the authentication scheme as defined in swagger json
* @param username username for http basic authentication
* @param password password for http basic authentication
*/
public constructor(authName: string, private username: string, private password: string) {
super(authName);
}
public applySecurityAuthentication(context: RequestContext) {
let comb = this.username + ":" + this.password;
context.setHeaderParam("Authentication", "Basic " + btoa(comb));
}
}
// TODO: How to handle oauth2 authentication!
export class OAuth2Authentication extends SecurityAuthentication {
public constructor(authName: string) {
super(authName);
}
public applySecurityAuthentication(context: RequestContext) {
// TODO
}
}
export type AuthMethods = {
{{#authMethods}}
"{{name}}"?: {{#isApiKey}}APIKeyAuthentication{{/isApiKey}}{{#isHttp}}HttpBasicAuthentication{{/isHttp}}{{#isOAuth}}OAuth2Authentication{{/isOAuth}},
{{/authMethods}}
}
export type ApiKeyConfiguration = string;
export type HttpBasicConfiguration = { "username": string, "password": string };
export type OAuth2Configuration = string;
export type AuthMethodsConfiguration = { {{#authMethods}}"{{name}}"?:{{#isApiKey}}ApiKeyConfiguration{{/isApiKey}}{{#isHttp}}HttpBasicConfiguration{{/isHttp}}{{#isOAuth}}OAuth2Configuration{{/isOAuth}}, {{/authMethods}} }
/**
* Creates the authentication methods from a swagger description.
*
*/
export function configureAuthMethods(conf: AuthMethodsConfiguration | undefined): AuthMethods {
let authMethods: AuthMethods = {
}
if (!conf) {
return authMethods;
}
{{#authMethods}}
if (conf["{{name}}"]) {
{{#isApiKey}}
authMethods["{{name}}"] = new APIKeyAuthentication("{{name}}", "{{keyParamName}}", {{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, <string> conf["{{name}}"]);
{{/isApiKey}}
{{#isBasic}}
authMethods["{{name}}"] = new HttpBasicAuthentication("{{name}}", config["{{name}}"]["username"], config["{{name}}"]["password"]);
{{/isBasic}}
{{#isOAuth}}
authMethods["{{name}}"] = new OAuth2Authentication("{{name}}");
{{/isOAuth}}
}
{{/authMethods}}
return authMethods;
}

View File

@ -0,0 +1,67 @@
import {HttpLibrary} from './http/http';
import {Middleware, PromiseMiddleware, PromiseMiddlewareWrapper} from './middleware';
{{#frameworks}}
{{#fetch-api}}
import {IsomorphicFetchHttpLibrary} from "./http/isomorphic-fetch";
{{/fetch-api}}
{{#jquery}}
import {JQueryHttpLibrary} from "./http/jquery";
{{/jquery}}
{{/frameworks}}
import {ServerConfiguration, server1} from './servers';
import {configureAuthMethods, AuthMethods, AuthMethodsConfiguration} from './auth/auth';
/**
* Inetrface with which a configuration object can be configured.
*
*/
export interface ConfigurationParameters {
/**
* Default server to use
*/
baseServer?: ServerConfiguration<any>;
/**
* HTTP library to use e.g. IsomorphicFetch
*/
httpApi?: HttpLibrary;
/**
* The middlewares which will be applied to requests and responses
*/
middleware?: Middleware[]; // middleware to apply before/after fetch requests
/**
* configures all middlewares using the promise api instead of observables (which Middleware uses)
*/
promiseMiddleware?: PromiseMiddleware[];
/**
* Configuration for the available authentication methods
*/
authMethods?: AuthMethodsConfiguration
}
export class Configuration {
baseServer: ServerConfiguration<any>;
httpApi: HttpLibrary;
middleware: Middleware[];
authMethods: AuthMethods;
/**
* Creates a new configuration object based on the given configuration.
* If a property is not included in conf, a default is used:
* - baseServer: server1
* - httpApi: IsomorphicFetchHttpLibrary
* - middleware: []
* - promiseMiddleware: []
* - authMethods: {}
* @param conf particial configuration
*/
constructor(conf: ConfigurationParameters = {}) {
this.baseServer = conf.baseServer !== undefined ? conf.baseServer : server1;
this.httpApi = conf.httpApi || {{#frameworks}}{{#fetch-api}}new IsomorphicFetchHttpLibrary(){{/fetch-api}}{{#jquery}}new JQueryHttpLibrary{{/jquery}}{{/frameworks}}; // TODO: replace with window.fetch if available?
this.middleware = conf.middleware || [];
this.authMethods = configureAuthMethods(conf.authMethods);
if (conf.promiseMiddleware) {
conf.promiseMiddleware.forEach(m => this.middleware.push(new PromiseMiddlewareWrapper(m)));
}
}
}

View File

@ -0,0 +1,7 @@
export * from './http/http';
export * from './auth/auth';
export {Middleware, PromiseMiddleware} from './middleware';
export * from './models/all';
export { Configuration} from './configuration'
export * from './types/PromiseAPI';
export * from './apis/exception';

View File

@ -0,0 +1,7 @@
export * from './http/http';
export * from './auth/auth';
export {Middleware, PromiseMiddleware} from './middleware';
export * from './models/all';
export { Configuration} from './configuration'
export * from './types/PromiseAPI';
export * from './apis/exception';

View File

@ -0,0 +1,67 @@
import { ResponseContext, RequestContext, HttpFile } from '../http/http';
import * as models from '../models/all';
import { Configuration} from '../configuration'
import { Observable, of } from {{#useRxJS}}'rxjs'{{/useRxJS}}{{^useRxJS}}'../rxjsStub'{{/useRxJS}};
import {mergeMap, map} from {{#useRxJS}}'rxjs/operators'{{/useRxJS}}{{^useRxJS}}'../rxjsStub'{{/useRxJS}};
{{#models}}
{{#model}}
import { {{name}} } from '../models/{{name}}';
{{/model}}
{{/models}}
{{#apiInfo}}
{{#apis}}
{{#operations}}
import { {{classname}}RequestFactory, {{classname}}ResponseProcessor} from "../apis/{{classname}}";
export class Observable{{classname}} {
private requestFactory: {{classname}}RequestFactory;
private responseProcessor: {{classname}}ResponseProcessor;
private configuration: Configuration;
public constructor(configuration: Configuration, requestFactory?: {{classname}}RequestFactory, responseProcessor?: {{classname}}ResponseProcessor) {
this.configuration = configuration;
this.requestFactory = requestFactory || new {{classname}}RequestFactory(configuration);
this.responseProcessor = responseProcessor || new {{classname}}ResponseProcessor();
}
{{#operation}}
/**
{{#notes}}
* {{&notes}}
{{/notes}}
{{#summary}}
* {{&summary}}
{{/summary}}
{{#allParams}}
* @param {{paramName}} {{description}}
{{/allParams}}
*/
public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: Configuration): Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {
const requestContext = this.requestFactory.{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.{{nickname}}(rsp)));
}));
}
{{/operation}}
}
{{/operations}}
{{/apis}}
{{/apiInfo}}

View File

@ -0,0 +1,49 @@
import { ResponseContext, RequestContext, HttpFile } from '../http/http';
import * as models from '../models/all';
import { Configuration} from '../configuration'
{{#models}}
{{#model}}
import { {{name}} } from '../models/{{name}}';
{{/model}}
{{/models}}
{{#apiInfo}}
{{#apis}}
import { Observable{{classname}} } from './ObservableAPI';
{{#operations}}
import { {{classname}}RequestFactory, {{classname}}ResponseProcessor} from "../apis/{{classname}}";
export class Promise{{classname}} {
private api: Observable{{classname}}
public constructor(configuration: Configuration, requestFactory?: {{classname}}RequestFactory, responseProcessor?: {{classname}}ResponseProcessor) {
this.api = new Observable{{classname}}(configuration, requestFactory, responseProcessor);
}
{{#operation}}
/**
{{#notes}}
* {{&notes}}
{{/notes}}
{{#summary}}
* {{&summary}}
{{/summary}}
{{#allParams}}
* @param {{paramName}} {{description}}
{{/allParams}}
*/
public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}options?: Configuration): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {
const result = this.api.{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options);
return result.toPromise();
}
{{/operation}}
}
{{/operations}}
{{/apis}}
{{/apiInfo}}

View File

@ -0,0 +1,52 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update"
git_user_id=$1
git_repo_id=$2
release_note=$3
if [ "$git_user_id" = "" ]; then
git_user_id="{{{gitUserId}}}"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="{{{gitRepoId}}}"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="{{{releaseNote}}}"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -0,0 +1,151 @@
{{#platforms}}
{{#node}}
// TODO: evaluate if we can easily get rid of this library
import * as FormData from "form-data";
{{/node}}
{{/platforms}}
// typings of url-parse are incorrect...
// @ts-ignore
import * as URLParse from "url-parse";
import { Observable } from {{#useRxJS}}'rxjs'{{/useRxJS}}{{^useRxJS}}'../rxjsStub'{{/useRxJS}};
{{#frameworks}}
{{#fetch-api}}
export * from './isomorphic-fetch';
{{/fetch-api}}
{{#jquery}}
export * from './jquery';
{{/jquery}}
{{/frameworks}}
/**
* Represents a HTTP Method.
*/
export enum HttpMethod {
GET = "GET",
HEAD = "HEAD",
POST = "POST",
PUT = "PUT",
DELETE = "DELETE",
CONNECT = "CONNECT",
OPTIONS = "OPTIONS",
TRACE = "TRACE",
PATCH = "PATCH"
}
/**
* Represents a http file which will be uploaded to a server.
*/
export interface HttpFile {
data: {{{fileContentDataType}}};
name: string;
}
export class HttpException extends Error {
public constructor(msg: string) {
super(msg);
}
}
/**
* Represents a HTTP request context
*
*/
export class RequestContext {
private headers: { [key: string]: string } = {};
private body: string | FormData = "";
private url: URLParse;
/**
* Creates the request context using a http method and request resource url
*
* @param url url of the requested resource
* @param httpMethod http method
*/
public constructor(url: string, private httpMethod: HttpMethod) {
this.url = URLParse(url, true);
}
/*
* Returns the url set in the constructor including the query string
*
*/
public getUrl(): string {
return this.url.toString();
}
/**
* Replaces the url set in the constructor with this url.
*
*/
public setUrl(url: string) {
this.url = URLParse(url, true);
}
/**
* Sets the body of the http request either as a string or FormData
* Setting a body on a HTTP GET request is disallowed under HTTP-Spec 1.1. Section
* 4.3 and this method throws an HttpException accordingly.
*
* @param body the body of the request
*/
public setBody(body: string | FormData) {
// HTTP-Spec 1.1 Section 4.3
if (this.httpMethod === HttpMethod.GET) {
throw new HttpException("Body should not be included in GET-Requests!");
}
// TODO: other http methods
// post is fine either formData or string
this.body = body;
}
public getHttpMethod(): HttpMethod {
return this.httpMethod;
}
public getHeaders(): { [key: string]: string } {
return this.headers;
}
public getBody(): string | FormData {
return this.body;
}
public setQueryParam(name: string, value: string) {
let queryObj = this.url.query;
queryObj[name] = value;
this.url.set("query", queryObj);
}
/**
* Sets a cookie with the name and value. NO check for duplicate cookies is performed
*
*/
public addCookie(name: string, value: string): void {
if (!this.headers["Cookie"]) {
this.headers["Cookie"] = "";
}
this.headers["Cookie"] += name + "=" + value + "; ";
}
public setHeaderParam(key: string, value: string): void {
this.headers[key] = value;
}
}
export class ResponseContext {
public constructor(public httpStatusCode: number,
public headers: { [key: string]: string }, public body: string) {
}
}
export interface HttpLibrary {
send(request: RequestContext): Observable<ResponseContext>;
}

View File

@ -0,0 +1,35 @@
declare var fetch: any;
import {HttpLibrary, RequestContext, ResponseContext} from './http';
import * as e6p from 'es6-promise'
import { from, Observable } from {{#useRxJS}}'rxjs'{{/useRxJS}}{{^useRxJS}}'../rxjsStub'{{/useRxJS}};
e6p.polyfill();
import 'isomorphic-fetch';
export class IsomorphicFetchHttpLibrary implements HttpLibrary {
public send(request: RequestContext): Observable<ResponseContext> {
let method = request.getHttpMethod().toString();
let body = request.getBody();
const resultPromise = fetch(request.getUrl(), {
method: method,
body: body as any,
headers: request.getHeaders(),
credentials: "same-origin"
}).then((resp: any) => {
// hack
let headers = (resp.headers as any)._headers;
for (let key in headers) {
headers[key] = (headers[key] as Array<string>).join("; ");
}
return resp.text().then((body: string) => {
return new ResponseContext(resp.status, headers, body)
});
});
return from<Promise<ResponseContext>>(resultPromise);
}
}

View File

@ -0,0 +1,79 @@
import {HttpLibrary, RequestContext, ResponseContext, HttpException} from './http';
import * as e6p from 'es6-promise'
import { from, Observable } from {{#useRxJS}}'rxjs'{{/useRxJS}}{{^useRxJS}}'../rxjsStub'{{/useRxJS}};
e6p.polyfill();
import * as $ from 'jquery';
{{#platforms}}
{{#node}}
import * as FormData from "form-data";
{{/node}}
{{/platforms}}
export class JQueryHttpLibrary implements HttpLibrary {
public send(request: RequestContext): Observable<ResponseContext> {
let method = request.getHttpMethod().toString();
let body = request.getBody();
let headerParams = request.getHeaders()
let requestOptions: any = {
url: request.getUrl(),
type: method,
headers: request.getHeaders(),
processData: false,
xhrFields: { withCredentials: true },
data: body
};
if (request.getHeaders()['Content-Type']) {
requestOptions.contentType = headerParams['Content-Type'];
}
requestOptions.dataFilter = ((headerParams: { [key:string]: string}) => {
return (data: string, type: string) => {
if (headerParams["Accept"] == "application/json" && data == "") {
return "{}"
} else {
return data
}
}
})(headerParams);
if (request.getHeaders()["Cookie"]) {
throw new HttpException("Setting the \"Cookie\"-Header field is blocked by every major browser when using jquery.ajax requests. Please switch to another library like fetch to enable this option");
}
if (body.constructor.name == "FormData") {
requestOptions.contentType = false;
}
const sentRequest = $.ajax(requestOptions);
const resultPromise = new Promise<ResponseContext>((resolve, reject) => {
sentRequest.done((resp, _, jqXHR) => {
const headers = this.getResponseHeaders(jqXHR)
const result = new ResponseContext(jqXHR.status, headers, JSON.stringify(resp));
resolve(result);
})
sentRequest.fail((jqXHR: any) => {
const headers = this.getResponseHeaders(jqXHR)
const result = new ResponseContext(jqXHR.status, headers, jqXHR.responseText);
resolve(result);
})
})
return from(resultPromise);
}
private getResponseHeaders(jqXHR: any): { [key: string]: string } {
const responseHeaders: { [key: string]: string } = {};
var headers = jqXHR.getAllResponseHeaders();
headers = headers.split("\n");
headers.forEach(function (header: any) {
header = header.split(": ");
var key = header.shift();
if (key.length == 0) return
// chrome60+ force lowercase, other browsers can be different
key = key.toLowerCase();
responseHeaders[key] = header.join(": ");
});
return responseHeaders
}
}

View File

@ -0,0 +1,57 @@
import {RequestContext, HttpMethod} from './http/http';
/**
*
* Represents the configuration of a server including its
* url template and variable configuration based on the url.
*
*/
export class ServerConfiguration<T> {
public constructor(private url: string, private variableConfiguration: T) {
}
/**
* Sets the value of the variables of this server.
*
* @param variableConfiguration a partial variable configuration for the variables contained in the url
*/
public setVariables(variableConfiguration: Partial<T>) {
for (const key in variableConfiguration) {
const val = variableConfiguration[key]
// We know that val isn't undefined here - hopefully
if (val !== undefined) {
this.variableConfiguration[key] = val as T[Extract<keyof T, string>];
}
}
}
public getConfiguration(): T {
return this.variableConfiguration
}
private getUrl() {
let replacedUrl = this.url;
for (const key in this.variableConfiguration) {
var re = new RegExp("{" + key + "}","g");
replacedUrl = replacedUrl.replace(re, this.variableConfiguration[key].toString());
}
return replacedUrl
}
/**
* Creates a new request context for this server using the url with variables
* replaced with their respective values and the endpoint of the request appended.
*
* @param endpoint the endpoint to be queried on the server
* @param httpMethod httpMethod to be used
*
*/
public makeRequestContext(endpoint: string, httpMethod: HttpMethod): RequestContext {
return new RequestContext(this.getUrl() + endpoint, httpMethod);
}
}
{{#servers}}
export const server{{-index}} = new ServerConfiguration<{ {{#variables}} "{{name}}": {{#enumValues}}"{{.}}"{{^-last}} | {{/-last}}{{/enumValues}}{{^enumValues}}string{{/enumValues}}{{^-last}},{{/-last}} {{/variables}} }>("{{url}}", { {{#variables}} "{{name}}": "{{defaultValue}}" {{^-last}},{{/-last}}{{/variables}} })
{{/servers}}

View File

@ -0,0 +1,11 @@
/**
* {{{appName}}}
* {{{appDescription}}}
*
* {{#version}}OpenAPI spec version: {{{version}}}{{/version}}
* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/

View File

@ -0,0 +1,165 @@
{{#models}}
{{#model}}
export * from './{{{ classFilename }}}';
{{/model}}
{{/models}}
{{#models}}
{{#model}}
import { {{classname}}{{#hasEnums}}{{#vars}}{{#isEnum}}, {{classname}}{{enumName}} {{/isEnum}} {{/vars}}{{/hasEnums}} } from './{{{ classFilename }}}';
{{/model}}
{{/models}}
/* tslint:disable:no-unused-variable */
let primitives = [
"string",
"boolean",
"double",
"integer",
"long",
"float",
"number",
"any"
];
let enumsMap: Set<string> = new Set<string>([
{{#models}}
{{#model}}
{{#hasEnums}}
{{#vars}}
{{#isEnum}}
"{{classname}}{{enumName}}",
{{/isEnum}}
{{/vars}}
{{/hasEnums}}
{{/model}}
{{/models}}
]);
let typeMap: {[index: string]: any} = {
{{#models}}
{{#model}}
"{{classname}}": {{classname}},
{{/model}}
{{/models}}
}
export class ObjectSerializer {
public static findCorrectType(data: any, expectedType: string) {
if (data == undefined) {
return expectedType;
} else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) {
return expectedType;
} else if (expectedType === "Date") {
return expectedType;
} else {
if (enumsMap.has(expectedType)) {
return expectedType;
}
if (!typeMap[expectedType]) {
return expectedType; // w/e we don't know the type
}
// Check the discriminator
let discriminatorProperty = typeMap[expectedType].discriminator;
if (discriminatorProperty == null) {
return expectedType; // the type does not have a discriminator. use it.
} else {
if (data[discriminatorProperty]) {
var discriminatorType = data[discriminatorProperty];
if(typeMap[discriminatorType]){
return discriminatorType; // use the type given in the discriminator
} else {
return expectedType; // discriminator did not map to a type
}
} else {
return expectedType; // discriminator was not present (or an empty string)
}
}
}
}
public static serialize(data: any, type: string, format: string) {
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index in data) {
let date = data[index];
transformedData.push(ObjectSerializer.serialize(date, subType, format));
}
return transformedData;
} else if (type === "Date") {
if (format == "date") {
let month = data.getMonth()+1
month = month < 10 ? "0" + month.toString() : month.toString()
let day = data.getDate();
day = day < 10 ? "0" + day.toString() : day.toString();
return data.getFullYear() + "-" + month + "-" + day;
} else {
return data.toISOString();
}
} else {
if (enumsMap.has(type)) {
return data;
}
if (!typeMap[type]) { // in case we dont know the type
return data;
}
// Get the actual type of this object
type = this.findCorrectType(data, type);
// get the map for the correct type.
let attributeTypes = typeMap[type].getAttributeTypeMap();
let instance: {[index: string]: any} = {};
for (let index in attributeTypes) {
let attributeType = attributeTypes[index];
instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type, attributeType.format);
}
return instance;
}
}
public static deserialize(data: any, type: string, format: string) {
// polymorphism may change the actual type.
type = ObjectSerializer.findCorrectType(data, type);
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index in data) {
let date = data[index];
transformedData.push(ObjectSerializer.deserialize(date, subType, format));
}
return transformedData;
} else if (type === "Date") {
return new Date(data);
} else {
if (enumsMap.has(type)) {// is Enum
return data;
}
if (!typeMap[type]) { // dont know the type
return data;
}
let instance = new typeMap[type]();
let attributeTypes = typeMap[type].getAttributeTypeMap();
for (let index in attributeTypes) {
let attributeType = attributeTypes[index];
instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type, attributeType.format);
}
return instance;
}
}
}

View File

@ -0,0 +1,78 @@
{{>licenseInfo}}
{{#models}}
{{#model}}
{{#tsImports}}
import { {{classname}} } from './{{filename}}';
{{/tsImports}}
{{#description}}
/**
* {{{description}}}
*/
{{/description}}
export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{
{{#vars}}
{{#description}}
/**
* {{{description}}}
*/
{{/description}}
'{{name}}'{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}};
{{/vars}}
{{#discriminator}}
static readonly discriminator: string | undefined = "{{discriminatorName}}";
{{/discriminator}}
{{^discriminator}}
static readonly discriminator: string | undefined = undefined;
{{/discriminator}}
{{^isArrayModel}}
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{{#vars}}
{
"name": "{{name}}",
"baseName": "{{baseName}}",
"type": "{{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}",
"format": "{{dataFormat}}"
}{{#hasMore}},
{{/hasMore}}
{{/vars}}
];
static getAttributeTypeMap() {
{{#parent}}
return super.getAttributeTypeMap().concat({{classname}}.attributeTypeMap);
{{/parent}}
{{^parent}}
return {{classname}}.attributeTypeMap;
{{/parent}}
}
{{/isArrayModel}}
public constructor() {
{{#parent}}
super();
{{/parent}}
{{#allVars}}
{{#discriminatorValue}}
this.{{name}} = "{{discriminatorValue}}";
{{/discriminatorValue}}
{{/allVars}}
{{#discriminatorName}}
this.{{discriminatorName}} = "{{classname}}";
{{/discriminatorName}}
}
}
{{#hasEnums}}
{{#vars}}
{{#isEnum}}
export type {{classname}}{{enumName}} ={{#allowableValues}}{{#values}} "{{.}}" {{^-last}}|{{/-last}}{{/values}}{{/allowableValues}};
{{/isEnum}}
{{/vars}}
{{/hasEnums}}
{{/model}}
{{/models}}

View File

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

View File

@ -0,0 +1,51 @@
{
"name": "{{npmName}}",
"version": "{{npmVersion}}",
"description": "OpenAPI client for {{npmName}}",
"author": "OpenAPI-Generator Contributors",
"keywords": [
"fetch",
"typescript",
"openapi-client",
"openapi-generator"
],
"license": "Unlicense",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"scripts": {
"build": "tsc",
"prepublishOnly": "npm run build"
},
"dependencies": {
{{#frameworks}}
{{#fetch-api}}
"isomorphic-fetch": "^2.2.1",
"@types/isomorphic-fetch": "0.0.34",
{{/fetch-api}}
{{#jquery}}
"@types/jquery": "^3.3.29",
"jquery": "^3.4.1",
{{/jquery}}
{{/frameworks}}
{{#platforms}}
{{#node}}
"@types/node": "*",
"form-data": "^2.5.0",
{{/node}}
{{/platforms}}
{{#useRxJS}}
"rxjs": "^6.4.0",
{{/useRxJS}}
"btoa": "^1.2.1",
"es6-promise": "^4.2.4",
"url-parse": "^1.4.3"
},
"devDependencies": {
"typescript": "^2.9.2"
}{{#npmRepository}},{{/npmRepository}}
{{#npmRepository}}
"publishConfig":{
"registry":"{{npmRepository}}"
}
{{/npmRepository}}
}

View File

@ -0,0 +1,27 @@
export class Observable<T> {
constructor(private promise: Promise<T>) {}
toPromise() {
return this.promise;
}
pipe<S>(callback: (value: T) => S | Promise<S>): Observable<S> {
return new Observable(this.promise.then(callback));
}
}
export function from<T>(promise: Promise<any>) {
return new Observable(promise);
}
export function of<T>(value: T) {
return new Observable<T>(Promise.resolve(value));
}
export function mergeMap<T, S>(callback: (value: T) => Observable<S>) {
return (value: T) => callback(value).toPromise();
}
export function map(callback: any) {
return callback;
}

View File

@ -0,0 +1,29 @@
{
"compilerOptions": {
"strict": true,
/* Basic Options */
"target": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}es5{{/supportsES6}}",
"module": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}commonjs{{/supportsES6}}",
"declaration": true,
/* Additional Checks */
"noUnusedLocals": false, /* Report errors on unused locals. */ // TODO: reenable (unused imports!)
"noUnusedParameters": false, /* Report errors on unused parameters. */ // TODO: set to true again
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
"noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
"removeComments": true,
"sourceMap": true,
"outDir": "./dist",
"noLib": false,
"lib": [ "es6", "dom" ]
},
"exclude": [
"dist",
"node_modules"
],
"filesGlob": [
"./**/*.ts",
]
}

View File

@ -0,0 +1,28 @@
/**
* Returns if a specific http code is in a given code range
* where the code range is defined as a combination of digits
* and "X" (the letter X) with a length of 3
*
* @param codeRange string with length 3 consisting of digits and "X" (the letter X)
* @param code the http status code to be checked against the code range
*/
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;
}
}

14
pom.xml
View File

@ -991,6 +991,18 @@
<module>samples/server/petstore/jaxrs-spec-interface-response</module>
</modules>
</profile>
<profile>
<id>typescript-client-tests-default</id>
<activation>
<property>
<name>env</name>
<value>java</value>
</property>
</activation>
<modules>
<module>samples/client/petstore/typescript/tests/default</module>
</modules>
</profile>
<profile>
<id>typescript-fetch-client-tests-default</id>
<activation>
@ -1260,6 +1272,8 @@
<module>samples/client/petstore/python-tornado</module>
<module>samples/openapi3/client/petstore/python</module>
<module>samples/openapi3/client/petstore/python-experimental</module>
<module>samples/client/petstore/typescript/builds/default</module>
<module>samples/client/petstore/typescript/tests/default</module>
<module>samples/client/petstore/typescript-fetch/builds/default</module>
<module>samples/client/petstore/typescript-fetch/builds/es6-target</module>
<module>samples/client/petstore/typescript-fetch/builds/with-npm-version</module>

View File

@ -0,0 +1 @@
dist

View File

@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -0,0 +1 @@
4.3.1-SNAPSHOT

View File

@ -0,0 +1,30 @@
## ts-petstore-client@1.0.0
This generator creates TypeScript/JavaScript client that utilizes fetch-api.
### Building
To build and compile the typescript sources to javascript use:
```
npm install
npm run build
```
### Publishing
First build the package then run ```npm publish```
### Consuming
navigate to the folder of your consuming project and run one of the following commands.
_published:_
```
npm install ts-petstore-client@1.0.0 --save
```
_unPublished (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE --save

View File

@ -0,0 +1,584 @@
// TODO: better import syntax?
import { BaseAPIRequestFactory, RequiredError } from './baseapi';
import {Configuration} from '../configuration';
import { RequestContext, HttpMethod, ResponseContext, HttpFile} 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';
/**
* no description
*/
export class PetApiRequestFactory extends BaseAPIRequestFactory {
/**
* Add a new pet to the store
* @param body Pet object that needs to be added to the store
*/
public addPet(body: Pet, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('Required parameter body was null or undefined when calling addPet.');
}
// Path Params
const localVarPath = '/pet';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
requestContext.setHeaderParam("Content-Type", "application/json");
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"Pet" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify(body || {}) : (body.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["petstore_auth"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* Deletes a pet
* @param petId Pet id to delete
* @param apiKey
*/
public deletePet(petId: number, apiKey?: string, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new RequiredError('Required parameter petId was null or undefined when calling deletePet.');
}
// Path Params
const localVarPath = '/pet/{petId}'
.replace('{' + 'petId' + '}', encodeURIComponent(String(petId)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
requestContext.setHeaderParam("api_key", ObjectSerializer.serialize(apiKey, "string", ""));
// Form Params
// Body Params
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["petstore_auth"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* Multiple status values can be provided with comma separated strings
* Finds Pets by status
* @param status Status values that need to be considered for filter
*/
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'status' is not null or undefined
if (status === null || status === undefined) {
throw new RequiredError('Required parameter status was null or undefined when calling findPetsByStatus.');
}
// Path Params
const localVarPath = '/pet/findByStatus';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
if (status !== undefined) {
requestContext.setQueryParam("status", ObjectSerializer.serialize(status, "Array<'available' | 'pending' | 'sold'>", ""));
}
// Header Params
// Form Params
// Body Params
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["petstore_auth"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* Finds Pets by tags
* @param tags Tags to filter by
*/
public findPetsByTags(tags: Array<string>, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'tags' is not null or undefined
if (tags === null || tags === undefined) {
throw new RequiredError('Required parameter tags was null or undefined when calling findPetsByTags.');
}
// Path Params
const localVarPath = '/pet/findByTags';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
if (tags !== undefined) {
requestContext.setQueryParam("tags", ObjectSerializer.serialize(tags, "Array<string>", ""));
}
// Header Params
// Form Params
// Body Params
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["petstore_auth"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* Returns a single pet
* Find pet by ID
* @param petId ID of pet to return
*/
public getPetById(petId: number, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new RequiredError('Required parameter petId was null or undefined when calling getPetById.');
}
// Path Params
const localVarPath = '/pet/{petId}'
.replace('{' + 'petId' + '}', encodeURIComponent(String(petId)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["api_key"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* Update an existing pet
* @param body Pet object that needs to be added to the store
*/
public updatePet(body: Pet, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('Required parameter body was null or undefined when calling updatePet.');
}
// Path Params
const localVarPath = '/pet';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
requestContext.setHeaderParam("Content-Type", "application/json");
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"Pet" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify(body || {}) : (body.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["petstore_auth"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* Updates a pet in the store with form data
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
*/
public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new RequiredError('Required parameter petId was null or undefined when calling updatePetWithForm.');
}
// Path Params
const localVarPath = '/pet/{petId}'
.replace('{' + 'petId' + '}', encodeURIComponent(String(petId)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
let localVarFormParams = new FormData();
if (name !== undefined) {
// TODO: replace .append with .set
localVarFormParams.append('name', name as any);
}
if (status !== undefined) {
// TODO: replace .append with .set
localVarFormParams.append('status', status as any);
}
requestContext.setBody(localVarFormParams);
// Body Params
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["petstore_auth"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* uploads an image
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new RequiredError('Required parameter petId was null or undefined when calling uploadFile.');
}
// Path Params
const localVarPath = '/pet/{petId}/uploadImage'
.replace('{' + 'petId' + '}', encodeURIComponent(String(petId)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
let localVarFormParams = new FormData();
if (additionalMetadata !== undefined) {
// TODO: replace .append with .set
localVarFormParams.append('additionalMetadata', additionalMetadata as any);
}
if (file !== undefined) {
// TODO: replace .append with .set
localVarFormParams.append('file', file.data, file.name);
}
requestContext.setBody(localVarFormParams);
// Body Params
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["petstore_auth"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
}
export class PetApiResponseProcessor {
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public addPet(response: ResponseContext): void {
if (isCodeInRange("405", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Invalid input");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public deletePet(response: ResponseContext): void {
if (isCodeInRange("400", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Invalid pet value");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public findPetsByStatus(response: ResponseContext): Array<Pet> {
if (isCodeInRange("200", response.httpStatusCode)) {
const jsonBody = JSON.parse(response.body);
const body: Array<Pet> = ObjectSerializer.deserialize(jsonBody, "Array<Pet>", "") as Array<Pet>;
return body;
}
if (isCodeInRange("400", response.httpStatusCode)) {
throw new ApiException<string>(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<Pet> = ObjectSerializer.deserialize(jsonBody, "Array<Pet>", "") as Array<Pet>;
return body;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public findPetsByTags(response: ResponseContext): Array<Pet> {
if (isCodeInRange("200", response.httpStatusCode)) {
const jsonBody = JSON.parse(response.body);
const body: Array<Pet> = ObjectSerializer.deserialize(jsonBody, "Array<Pet>", "") as Array<Pet>;
return body;
}
if (isCodeInRange("400", response.httpStatusCode)) {
throw new ApiException<string>(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<Pet> = ObjectSerializer.deserialize(jsonBody, "Array<Pet>", "") as Array<Pet>;
return body;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
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<string>(response.httpStatusCode, "Invalid ID supplied");
}
if (isCodeInRange("404", response.httpStatusCode)) {
throw new ApiException<string>(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;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public updatePet(response: ResponseContext): void {
if (isCodeInRange("400", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Invalid ID supplied");
}
if (isCodeInRange("404", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Pet not found");
}
if (isCodeInRange("405", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Validation exception");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public updatePetWithForm(response: ResponseContext): void {
if (isCodeInRange("405", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Invalid input");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
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;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
}

View File

@ -0,0 +1,271 @@
// TODO: better import syntax?
import { BaseAPIRequestFactory, RequiredError } from './baseapi';
import {Configuration} from '../configuration';
import { RequestContext, HttpMethod, ResponseContext, HttpFile} 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';
/**
* no description
*/
export class StoreApiRequestFactory extends BaseAPIRequestFactory {
/**
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* Delete purchase order by ID
* @param orderId ID of the order that needs to be deleted
*/
public deleteOrder(orderId: string, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'orderId' is not null or undefined
if (orderId === null || orderId === undefined) {
throw new RequiredError('Required parameter orderId was null or undefined when calling deleteOrder.');
}
// Path Params
const localVarPath = '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
// Apply auth methods
return requestContext;
}
/**
* Returns a map of status codes to quantities
* Returns pet inventories by status
*/
public getInventory(options?: Configuration): RequestContext {
let config = options || this.configuration;
// Path Params
const localVarPath = '/store/inventory';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["api_key"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* Find purchase order by ID
* @param orderId ID of pet that needs to be fetched
*/
public getOrderById(orderId: number, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'orderId' is not null or undefined
if (orderId === null || orderId === undefined) {
throw new RequiredError('Required parameter orderId was null or undefined when calling getOrderById.');
}
// Path Params
const localVarPath = '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
// Apply auth methods
return requestContext;
}
/**
* Place an order for a pet
* @param body order placed for purchasing the pet
*/
public placeOrder(body: Order, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('Required parameter body was null or undefined when calling placeOrder.');
}
// Path Params
const localVarPath = '/store/order';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
requestContext.setHeaderParam("Content-Type", "application/json");
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"Order" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify(body || {}) : (body.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
// Apply auth methods
return requestContext;
}
}
export class StoreApiResponseProcessor {
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public deleteOrder(response: ResponseContext): void {
if (isCodeInRange("400", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Invalid ID supplied");
}
if (isCodeInRange("404", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Order not found");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
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; }", "int32") 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; }", "int32") as { [key: string]: number; };
return body;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
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<string>(response.httpStatusCode, "Invalid ID supplied");
}
if (isCodeInRange("404", response.httpStatusCode)) {
throw new ApiException<string>(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;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
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<string>(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;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
}

View File

@ -0,0 +1,517 @@
// TODO: better import syntax?
import { BaseAPIRequestFactory, RequiredError } from './baseapi';
import {Configuration} from '../configuration';
import { RequestContext, HttpMethod, ResponseContext, HttpFile} 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';
/**
* no description
*/
export class UserApiRequestFactory extends BaseAPIRequestFactory {
/**
* This can only be done by the logged in user.
* Create user
* @param body Created user object
*/
public createUser(body: User, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('Required parameter body was null or undefined when calling createUser.');
}
// Path Params
const localVarPath = '/user';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
requestContext.setHeaderParam("Content-Type", "application/json");
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"User" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify(body || {}) : (body.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
// Apply auth methods
return requestContext;
}
/**
* Creates list of users with given input array
* @param body List of user object
*/
public createUsersWithArrayInput(body: Array<User>, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('Required parameter body was null or undefined when calling createUsersWithArrayInput.');
}
// Path Params
const localVarPath = '/user/createWithArray';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
requestContext.setHeaderParam("Content-Type", "application/json");
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"Array&lt;User&gt;" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify(body || {}) : (body.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
// Apply auth methods
return requestContext;
}
/**
* Creates list of users with given input array
* @param body List of user object
*/
public createUsersWithListInput(body: Array<User>, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('Required parameter body was null or undefined when calling createUsersWithListInput.');
}
// Path Params
const localVarPath = '/user/createWithList';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
requestContext.setHeaderParam("Content-Type", "application/json");
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"Array&lt;User&gt;" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify(body || {}) : (body.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
// Apply auth methods
return requestContext;
}
/**
* This can only be done by the logged in user.
* Delete user
* @param username The name that needs to be deleted
*/
public deleteUser(username: string, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new RequiredError('Required parameter username was null or undefined when calling deleteUser.');
}
// Path Params
const localVarPath = '/user/{username}'
.replace('{' + 'username' + '}', encodeURIComponent(String(username)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
// Apply auth methods
return requestContext;
}
/**
* Get user by user name
* @param username The name that needs to be fetched. Use user1 for testing.
*/
public getUserByName(username: string, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new RequiredError('Required parameter username was null or undefined when calling getUserByName.');
}
// Path Params
const localVarPath = '/user/{username}'
.replace('{' + 'username' + '}', encodeURIComponent(String(username)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
// Apply auth methods
return requestContext;
}
/**
* Logs user into the system
* @param username The user name for login
* @param password The password for login in clear text
*/
public loginUser(username: string, password: string, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new RequiredError('Required parameter username was null or undefined when calling loginUser.');
}
// verify required parameter 'password' is not null or undefined
if (password === null || password === undefined) {
throw new RequiredError('Required parameter password was null or undefined when calling loginUser.');
}
// Path Params
const localVarPath = '/user/login';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
if (username !== undefined) {
requestContext.setQueryParam("username", ObjectSerializer.serialize(username, "string", ""));
}
if (password !== undefined) {
requestContext.setQueryParam("password", ObjectSerializer.serialize(password, "string", ""));
}
// Header Params
// Form Params
// Body Params
// Apply auth methods
return requestContext;
}
/**
* Logs out current logged in user session
*/
public logoutUser(options?: Configuration): RequestContext {
let config = options || this.configuration;
// Path Params
const localVarPath = '/user/logout';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
// Apply auth methods
return requestContext;
}
/**
* This can only be done by the logged in user.
* Updated user
* @param username name that need to be deleted
* @param body Updated user object
*/
public updateUser(username: string, body: User, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new RequiredError('Required parameter username was null or undefined when calling updateUser.');
}
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('Required parameter body was null or undefined when calling updateUser.');
}
// Path Params
const localVarPath = '/user/{username}'
.replace('{' + 'username' + '}', encodeURIComponent(String(username)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
requestContext.setHeaderParam("Content-Type", "application/json");
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"User" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify(body || {}) : (body.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
// Apply auth methods
return requestContext;
}
}
export class UserApiResponseProcessor {
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public createUser(response: ResponseContext): void {
if (isCodeInRange("0", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "successful operation");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public createUsersWithArrayInput(response: ResponseContext): void {
if (isCodeInRange("0", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "successful operation");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public createUsersWithListInput(response: ResponseContext): void {
if (isCodeInRange("0", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "successful operation");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public deleteUser(response: ResponseContext): void {
if (isCodeInRange("400", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Invalid username supplied");
}
if (isCodeInRange("404", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "User not found");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
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<string>(response.httpStatusCode, "Invalid username supplied");
}
if (isCodeInRange("404", response.httpStatusCode)) {
throw new ApiException<string>(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;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
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<string>(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;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public logoutUser(response: ResponseContext): void {
if (isCodeInRange("0", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "successful operation");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public updateUser(response: ResponseContext): void {
if (isCodeInRange("400", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Invalid user supplied");
}
if (isCodeInRange("404", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "User not found");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
}

View File

@ -0,0 +1,37 @@
import { Configuration } from '../configuration'
/**
*
* @export
*/
export const COLLECTION_FORMATS = {
csv: ",",
ssv: " ",
tsv: "\t",
pipes: "|",
};
/**
*
* @export
* @class BaseAPI
*/
export class BaseAPIRequestFactory {
constructor(protected configuration: Configuration) {
}
};
/**
*
* @export
* @class RequiredError
* @extends {Error}
*/
export class RequiredError extends Error {
name: "RequiredError" = "RequiredError";
constructor(public field: string, msg?: string) {
super(msg);
}
}

View File

@ -0,0 +1,14 @@
/**
* Represents an error caused by an api call i.e. it has attributes for a HTTP status code
* and the returned body object.
*
* Example
* API returns a ErrorMessageObject whenever HTTP status code is not in [200, 299]
* => ApiException(404, someErrorMessageObject)
*
*/
export class ApiException<T> extends Error {
public constructor(public code: number, public body: T) {
super("HTTP-Code: " + code + "\nMessage: " + JSON.stringify(body))
}
}

View File

@ -0,0 +1,145 @@
import {RequestContext} from '../http/http';
// typings for btoa are incorrect
//@ts-ignore
import * as btoa from "btoa";
/**
* Base class for all authentication schemes.
*
*/
export abstract class SecurityAuthentication {
public constructor(private name: string) {
}
/*
*
* @return returns the name of the security authentication as specified in OAI
*/
public getName(): string {
return this.name;
}
/**
* Applies the authentication scheme to the request context
*
* @params context the request context which should use this authentication scheme
*/
public abstract applySecurityAuthentication(context: RequestContext): void;
}
/**
* Applies no authentication.
*
*/
export class NoAuthentication extends SecurityAuthentication {
public constructor() {
super("_no_auth");
}
public applySecurityAuthentication(_context: RequestContext) {
}
}
/**
* Applies an api key to the request context.
*
*/
export class APIKeyAuthentication extends SecurityAuthentication {
/**
* Configures this api key authentication with the necessary properties
*
* @param authName: name of this authentication scheme as specified in the swagger.json
* @param paramName: Parameter name used for the api key
* @param keyLocation: Parameter location, either query, header or cookie.
* @param apiKey: The api key to be used for every request
*/
public constructor(authName: string, private paramName: string, private keyLocation: "query" | "header" | "cookie", private apiKey: string) {
super(authName);
}
public applySecurityAuthentication(context: RequestContext) {
if (this.keyLocation === "header") {
context.setHeaderParam(this.paramName, this.apiKey);
} else if (this.keyLocation === "cookie") {
context.addCookie(this.paramName, this.apiKey);
} else if (this.keyLocation === "query") {
context.setQueryParam(this.paramName, this.apiKey);
}
}
}
/**
* Applies basic http authentication to a request.
*
*/
export class HttpBasicAuthentication extends SecurityAuthentication {
/**
* Configures the http authentication with the required details.
*
*
* @param authName name of the authentication scheme as defined in swagger json
* @param username username for http basic authentication
* @param password password for http basic authentication
*/
public constructor(authName: string, private username: string, private password: string) {
super(authName);
}
public applySecurityAuthentication(context: RequestContext) {
let comb = this.username + ":" + this.password;
context.setHeaderParam("Authentication", "Basic " + btoa(comb));
}
}
// TODO: How to handle oauth2 authentication!
export class OAuth2Authentication extends SecurityAuthentication {
public constructor(authName: string) {
super(authName);
}
public applySecurityAuthentication(context: RequestContext) {
// TODO
}
}
export type AuthMethods = {
"api_key"?: APIKeyAuthentication,
"petstore_auth"?: OAuth2Authentication,
}
export type ApiKeyConfiguration = string;
export type HttpBasicConfiguration = { "username": string, "password": string };
export type OAuth2Configuration = string;
export type AuthMethodsConfiguration = { "api_key"?:ApiKeyConfiguration, "petstore_auth"?:OAuth2Configuration, }
/**
* Creates the authentication methods from a swagger description.
*
*/
export function configureAuthMethods(conf: AuthMethodsConfiguration | undefined): AuthMethods {
let authMethods: AuthMethods = {
}
if (!conf) {
return authMethods;
}
if (conf["api_key"]) {
authMethods["api_key"] = new APIKeyAuthentication("api_key", "api_key", "header", <string> conf["api_key"]);
}
if (conf["petstore_auth"]) {
authMethods["petstore_auth"] = new OAuth2Authentication("petstore_auth");
}
return authMethods;
}

View File

@ -0,0 +1,60 @@
import {HttpLibrary} from './http/http';
import {Middleware, PromiseMiddleware, PromiseMiddlewareWrapper} from './middleware';
import {IsomorphicFetchHttpLibrary} from "./http/isomorphic-fetch";
import {ServerConfiguration, server1} from './servers';
import {configureAuthMethods, AuthMethods, AuthMethodsConfiguration} from './auth/auth';
/**
* Inetrface with which a configuration object can be configured.
*
*/
export interface ConfigurationParameters {
/**
* Default server to use
*/
baseServer?: ServerConfiguration<any>;
/**
* HTTP library to use e.g. IsomorphicFetch
*/
httpApi?: HttpLibrary;
/**
* The middlewares which will be applied to requests and responses
*/
middleware?: Middleware[]; // middleware to apply before/after fetch requests
/**
* configures all middlewares using the promise api instead of observables (which Middleware uses)
*/
promiseMiddleware?: PromiseMiddleware[];
/**
* Configuration for the available authentication methods
*/
authMethods?: AuthMethodsConfiguration
}
export class Configuration {
baseServer: ServerConfiguration<any>;
httpApi: HttpLibrary;
middleware: Middleware[];
authMethods: AuthMethods;
/**
* Creates a new configuration object based on the given configuration.
* If a property is not included in conf, a default is used:
* - baseServer: server1
* - httpApi: IsomorphicFetchHttpLibrary
* - middleware: []
* - promiseMiddleware: []
* - authMethods: {}
* @param conf particial configuration
*/
constructor(conf: ConfigurationParameters = {}) {
this.baseServer = conf.baseServer !== undefined ? conf.baseServer : server1;
this.httpApi = conf.httpApi || new IsomorphicFetchHttpLibrary(); // TODO: replace with window.fetch if available?
this.middleware = conf.middleware || [];
this.authMethods = configureAuthMethods(conf.authMethods);
if (conf.promiseMiddleware) {
conf.promiseMiddleware.forEach(m => this.middleware.push(new PromiseMiddlewareWrapper(m)));
}
}
}

View File

@ -0,0 +1,52 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update"
git_user_id=$1
git_repo_id=$2
release_note=$3
if [ "$git_user_id" = "" ]; then
git_user_id="GIT_USER_ID"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="GIT_REPO_ID"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="Minor update"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -0,0 +1,140 @@
// TODO: evaluate if we can easily get rid of this library
import * as FormData from "form-data";
// typings of url-parse are incorrect...
// @ts-ignore
import * as URLParse from "url-parse";
import { Observable } from '../rxjsStub';
export * from './isomorphic-fetch';
/**
* Represents a HTTP Method.
*/
export enum HttpMethod {
GET = "GET",
HEAD = "HEAD",
POST = "POST",
PUT = "PUT",
DELETE = "DELETE",
CONNECT = "CONNECT",
OPTIONS = "OPTIONS",
TRACE = "TRACE",
PATCH = "PATCH"
}
/**
* Represents a http file which will be uploaded to a server.
*/
export interface HttpFile {
data: Buffer;
name: string;
}
export class HttpException extends Error {
public constructor(msg: string) {
super(msg);
}
}
/**
* Represents a HTTP request context
*
*/
export class RequestContext {
private headers: { [key: string]: string } = {};
private body: string | FormData = "";
private url: URLParse;
/**
* Creates the request context using a http method and request resource url
*
* @param url url of the requested resource
* @param httpMethod http method
*/
public constructor(url: string, private httpMethod: HttpMethod) {
this.url = URLParse(url, true);
}
/*
* Returns the url set in the constructor including the query string
*
*/
public getUrl(): string {
return this.url.toString();
}
/**
* Replaces the url set in the constructor with this url.
*
*/
public setUrl(url: string) {
this.url = URLParse(url, true);
}
/**
* Sets the body of the http request either as a string or FormData
* Setting a body on a HTTP GET request is disallowed under HTTP-Spec 1.1. Section
* 4.3 and this method throws an HttpException accordingly.
*
* @param body the body of the request
*/
public setBody(body: string | FormData) {
// HTTP-Spec 1.1 Section 4.3
if (this.httpMethod === HttpMethod.GET) {
throw new HttpException("Body should not be included in GET-Requests!");
}
// TODO: other http methods
// post is fine either formData or string
this.body = body;
}
public getHttpMethod(): HttpMethod {
return this.httpMethod;
}
public getHeaders(): { [key: string]: string } {
return this.headers;
}
public getBody(): string | FormData {
return this.body;
}
public setQueryParam(name: string, value: string) {
let queryObj = this.url.query;
queryObj[name] = value;
this.url.set("query", queryObj);
}
/**
* Sets a cookie with the name and value. NO check for duplicate cookies is performed
*
*/
public addCookie(name: string, value: string): void {
if (!this.headers["Cookie"]) {
this.headers["Cookie"] = "";
}
this.headers["Cookie"] += name + "=" + value + "; ";
}
public setHeaderParam(key: string, value: string): void {
this.headers[key] = value;
}
}
export class ResponseContext {
public constructor(public httpStatusCode: number,
public headers: { [key: string]: string }, public body: string) {
}
}
export interface HttpLibrary {
send(request: RequestContext): Observable<ResponseContext>;
}

View File

@ -0,0 +1,35 @@
declare var fetch: any;
import {HttpLibrary, RequestContext, ResponseContext} from './http';
import * as e6p from 'es6-promise'
import { from, Observable } from '../rxjsStub';
e6p.polyfill();
import 'isomorphic-fetch';
export class IsomorphicFetchHttpLibrary implements HttpLibrary {
public send(request: RequestContext): Observable<ResponseContext> {
let method = request.getHttpMethod().toString();
let body = request.getBody();
const resultPromise = fetch(request.getUrl(), {
method: method,
body: body as any,
headers: request.getHeaders(),
credentials: "same-origin"
}).then((resp: any) => {
// hack
let headers = (resp.headers as any)._headers;
for (let key in headers) {
headers[key] = (headers[key] as Array<string>).join("; ");
}
return resp.text().then((body: string) => {
return new ResponseContext(resp.status, headers, body)
});
});
return from<Promise<ResponseContext>>(resultPromise);
}
}

View File

@ -0,0 +1,7 @@
export * from './http/http';
export * from './auth/auth';
export {Middleware, PromiseMiddleware} from './middleware';
export * from './models/all';
export { Configuration} from './configuration'
export * from './types/PromiseAPI';
export * from './apis/exception';

View File

@ -0,0 +1,66 @@
import {RequestContext, ResponseContext} from './http/http';
import { Observable, from } from './rxjsStub';
/**
* Defines the contract for a middleware intercepting requests before
* they are sent (but after the RequestContext was created)
* and before the ResponseContext is unwrapped.
*
*/
export interface Middleware {
/**
* Modifies the request before the request is sent.
*
* @param context RequestContext of a request which is about to be sent to the server
* @returns an observable of the updated request context
*
*/
pre(context: RequestContext): Observable<RequestContext>;
/**
* Modifies the returned response before it is deserialized.
*
* @param context ResponseContext of a sent request
* @returns an observable of the modified response context
*/
post(context: ResponseContext): Observable<ResponseContext>;
}
export class PromiseMiddlewareWrapper implements Middleware {
public constructor(private middleware: PromiseMiddleware) {
}
pre(context: RequestContext): Observable<RequestContext> {
return from(this.middleware.pre(context));
}
post(context: ResponseContext): Observable<ResponseContext> {
return from(this.middleware.post(context));
}
}
/**
* Defines the contract for a middleware intercepting requests before
* they are sent (but after the RequestContext was created)
* and before the ResponseContext is unwrapped.
*
*/
export interface PromiseMiddleware {
/**
* Modifies the request before the request is sent.
*
* @param context RequestContext of a request which is about to be sent to the server
* @returns an observable of the updated request context
*
*/
pre(context: RequestContext): Promise<RequestContext>;
/**
* Modifies the returned response before it is deserialized.
*
* @param context ResponseContext of a sent request
* @returns an observable of the modified response context
*/
post(context: ResponseContext): Promise<ResponseContext>;
}

View File

@ -0,0 +1,51 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* Describes the result of uploading an image resource
*/
export class ApiResponse {
'code'?: number;
'type'?: string;
'message'?: string;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{
"name": "code",
"baseName": "code",
"type": "number",
"format": "int32"
},
{
"name": "type",
"baseName": "type",
"type": "string",
"format": ""
},
{
"name": "message",
"baseName": "message",
"type": "string",
"format": ""
} ];
static getAttributeTypeMap() {
return ApiResponse.attributeTypeMap;
}
public constructor() {
}
}

View File

@ -0,0 +1,44 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A category for a pet
*/
export class Category {
'id'?: number;
'name'?: string;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{
"name": "id",
"baseName": "id",
"type": "number",
"format": "int64"
},
{
"name": "name",
"baseName": "name",
"type": "string",
"format": ""
} ];
static getAttributeTypeMap() {
return Category.attributeTypeMap;
}
public constructor() {
}
}

View File

@ -0,0 +1,159 @@
export * from './ApiResponse';
export * from './Category';
export * from './Order';
export * from './Pet';
export * from './Tag';
export * from './User';
import { ApiResponse } from './ApiResponse';
import { Category } from './Category';
import { Order , OrderStatusEnum } from './Order';
import { Pet , PetStatusEnum } from './Pet';
import { Tag } from './Tag';
import { User } from './User';
/* tslint:disable:no-unused-variable */
let primitives = [
"string",
"boolean",
"double",
"integer",
"long",
"float",
"number",
"any"
];
let enumsMap: Set<string> = new Set<string>([
"OrderStatusEnum",
"PetStatusEnum",
]);
let typeMap: {[index: string]: any} = {
"ApiResponse": ApiResponse,
"Category": Category,
"Order": Order,
"Pet": Pet,
"Tag": Tag,
"User": User,
}
export class ObjectSerializer {
public static findCorrectType(data: any, expectedType: string) {
if (data == undefined) {
return expectedType;
} else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) {
return expectedType;
} else if (expectedType === "Date") {
return expectedType;
} else {
if (enumsMap.has(expectedType)) {
return expectedType;
}
if (!typeMap[expectedType]) {
return expectedType; // w/e we don't know the type
}
// Check the discriminator
let discriminatorProperty = typeMap[expectedType].discriminator;
if (discriminatorProperty == null) {
return expectedType; // the type does not have a discriminator. use it.
} else {
if (data[discriminatorProperty]) {
var discriminatorType = data[discriminatorProperty];
if(typeMap[discriminatorType]){
return discriminatorType; // use the type given in the discriminator
} else {
return expectedType; // discriminator did not map to a type
}
} else {
return expectedType; // discriminator was not present (or an empty string)
}
}
}
}
public static serialize(data: any, type: string, format: string) {
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index in data) {
let date = data[index];
transformedData.push(ObjectSerializer.serialize(date, subType, format));
}
return transformedData;
} else if (type === "Date") {
if (format == "date") {
let month = data.getMonth()+1
month = month < 10 ? "0" + month.toString() : month.toString()
let day = data.getDate();
day = day < 10 ? "0" + day.toString() : day.toString();
return data.getFullYear() + "-" + month + "-" + day;
} else {
return data.toISOString();
}
} else {
if (enumsMap.has(type)) {
return data;
}
if (!typeMap[type]) { // in case we dont know the type
return data;
}
// Get the actual type of this object
type = this.findCorrectType(data, type);
// get the map for the correct type.
let attributeTypes = typeMap[type].getAttributeTypeMap();
let instance: {[index: string]: any} = {};
for (let index in attributeTypes) {
let attributeType = attributeTypes[index];
instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type, attributeType.format);
}
return instance;
}
}
public static deserialize(data: any, type: string, format: string) {
// polymorphism may change the actual type.
type = ObjectSerializer.findCorrectType(data, type);
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index in data) {
let date = data[index];
transformedData.push(ObjectSerializer.deserialize(date, subType, format));
}
return transformedData;
} else if (type === "Date") {
return new Date(data);
} else {
if (enumsMap.has(type)) {// is Enum
return data;
}
if (!typeMap[type]) { // dont know the type
return data;
}
let instance = new typeMap[type]();
let attributeTypes = typeMap[type].getAttributeTypeMap();
for (let index in attributeTypes) {
let attributeType = attributeTypes[index];
instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type, attributeType.format);
}
return instance;
}
}
}

View File

@ -0,0 +1,78 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* An order for a pets from the pet store
*/
export class Order {
'id'?: number;
'petId'?: number;
'quantity'?: number;
'shipDate'?: Date;
/**
* Order Status
*/
'status'?: OrderStatusEnum;
'complete'?: boolean;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{
"name": "id",
"baseName": "id",
"type": "number",
"format": "int64"
},
{
"name": "petId",
"baseName": "petId",
"type": "number",
"format": "int64"
},
{
"name": "quantity",
"baseName": "quantity",
"type": "number",
"format": "int32"
},
{
"name": "shipDate",
"baseName": "shipDate",
"type": "Date",
"format": "date-time"
},
{
"name": "status",
"baseName": "status",
"type": "OrderStatusEnum",
"format": ""
},
{
"name": "complete",
"baseName": "complete",
"type": "boolean",
"format": ""
} ];
static getAttributeTypeMap() {
return Order.attributeTypeMap;
}
public constructor() {
}
}
export type OrderStatusEnum = "placed" | "approved" | "delivered" ;

View File

@ -0,0 +1,80 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Category } from './Category';
import { Tag } from './Tag';
/**
* A pet for sale in the pet store
*/
export class Pet {
'id'?: number;
'category'?: Category;
'name': string;
'photoUrls': Array<string>;
'tags'?: Array<Tag>;
/**
* pet status in the store
*/
'status'?: PetStatusEnum;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{
"name": "id",
"baseName": "id",
"type": "number",
"format": "int64"
},
{
"name": "category",
"baseName": "category",
"type": "Category",
"format": ""
},
{
"name": "name",
"baseName": "name",
"type": "string",
"format": ""
},
{
"name": "photoUrls",
"baseName": "photoUrls",
"type": "Array<string>",
"format": ""
},
{
"name": "tags",
"baseName": "tags",
"type": "Array<Tag>",
"format": ""
},
{
"name": "status",
"baseName": "status",
"type": "PetStatusEnum",
"format": ""
} ];
static getAttributeTypeMap() {
return Pet.attributeTypeMap;
}
public constructor() {
}
}
export type PetStatusEnum = "available" | "pending" | "sold" ;

View File

@ -0,0 +1,44 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A tag for a pet
*/
export class Tag {
'id'?: number;
'name'?: string;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{
"name": "id",
"baseName": "id",
"type": "number",
"format": "int64"
},
{
"name": "name",
"baseName": "name",
"type": "string",
"format": ""
} ];
static getAttributeTypeMap() {
return Tag.attributeTypeMap;
}
public constructor() {
}
}

View File

@ -0,0 +1,89 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A User who is purchasing from the pet store
*/
export class User {
'id'?: number;
'username'?: string;
'firstName'?: string;
'lastName'?: string;
'email'?: string;
'password'?: string;
'phone'?: string;
/**
* User Status
*/
'userStatus'?: number;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{
"name": "id",
"baseName": "id",
"type": "number",
"format": "int64"
},
{
"name": "username",
"baseName": "username",
"type": "string",
"format": ""
},
{
"name": "firstName",
"baseName": "firstName",
"type": "string",
"format": ""
},
{
"name": "lastName",
"baseName": "lastName",
"type": "string",
"format": ""
},
{
"name": "email",
"baseName": "email",
"type": "string",
"format": ""
},
{
"name": "password",
"baseName": "password",
"type": "string",
"format": ""
},
{
"name": "phone",
"baseName": "phone",
"type": "string",
"format": ""
},
{
"name": "userStatus",
"baseName": "userStatus",
"type": "number",
"format": "int32"
} ];
static getAttributeTypeMap() {
return User.attributeTypeMap;
}
public constructor() {
}
}

View File

@ -0,0 +1,6 @@
export * from './ApiResponse'
export * from './Category'
export * from './Order'
export * from './Pet'
export * from './Tag'
export * from './User'

View File

@ -0,0 +1,143 @@
{
"name": "ts-petstore-client",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@types/isomorphic-fetch": {
"version": "0.0.34",
"resolved": "https://registry.npmjs.org/@types/isomorphic-fetch/-/isomorphic-fetch-0.0.34.tgz",
"integrity": "sha1-PDSD5gbAQTeEOOlRRk8A5OYHBtY="
},
"@types/node": {
"version": "12.12.7",
"resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.7.tgz",
"integrity": "sha512-E6Zn0rffhgd130zbCbAr/JdXfXkoOUFAKNs/rF8qnafSJ8KYaA/j3oz7dcwal+lYjLA7xvdd5J4wdYpCTlP8+w=="
},
"asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k="
},
"btoa": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/btoa/-/btoa-1.2.1.tgz",
"integrity": "sha512-SB4/MIGlsiVkMcHmT+pSmIPoNDoHg+7cMzmt3Uxt628MTz2487DKSqK/fuhFBrkuqrYv5UCEnACpF4dTFNKc/g=="
},
"combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"requires": {
"delayed-stream": "~1.0.0"
}
},
"delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk="
},
"encoding": {
"version": "0.1.12",
"resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.12.tgz",
"integrity": "sha1-U4tm8+5izRq1HsMjgp0flIDHS+s=",
"requires": {
"iconv-lite": "~0.4.13"
}
},
"es6-promise": {
"version": "4.2.5",
"resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.5.tgz",
"integrity": "sha512-n6wvpdE43VFtJq+lUDYDBFUwV8TZbuGXLV4D6wKafg13ldznKsyEvatubnmUe31zcvelSzOHF+XbaT+Bl9ObDg=="
},
"form-data": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-2.5.1.tgz",
"integrity": "sha512-m21N3WOmEEURgk6B9GLOE4RuWOFf28Lhh9qGYeNlGq4VDXUlJy2th2slBNU8Gp8EzloYZOibZJ7t5ecIrFSjVA==",
"requires": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.6",
"mime-types": "^2.1.12"
}
},
"iconv-lite": {
"version": "0.4.24",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
"requires": {
"safer-buffer": ">= 2.1.2 < 3"
}
},
"is-stream": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz",
"integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ="
},
"isomorphic-fetch": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/isomorphic-fetch/-/isomorphic-fetch-2.2.1.tgz",
"integrity": "sha1-YRrhrPFPXoH3KVB0coGf6XM1WKk=",
"requires": {
"node-fetch": "^1.0.1",
"whatwg-fetch": ">=0.10.0"
}
},
"mime-db": {
"version": "1.40.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.40.0.tgz",
"integrity": "sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA=="
},
"mime-types": {
"version": "2.1.24",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.24.tgz",
"integrity": "sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ==",
"requires": {
"mime-db": "1.40.0"
}
},
"node-fetch": {
"version": "1.7.3",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-1.7.3.tgz",
"integrity": "sha512-NhZ4CsKx7cYm2vSrBAr2PvFOe6sWDf0UYLRqA6svUYg7+/TSfVAu49jYC4BvQ4Sms9SZgdqGBgroqfDhJdTyKQ==",
"requires": {
"encoding": "^0.1.11",
"is-stream": "^1.0.1"
}
},
"querystringify": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.1.0.tgz",
"integrity": "sha512-sluvZZ1YiTLD5jsqZcDmFyV2EwToyXZBfpoVOmktMmW+VEnhgakFHnasVph65fOjGPTWN0Nw3+XQaSeMayr0kg=="
},
"requires-port": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
"integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8="
},
"safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
},
"typescript": {
"version": "2.9.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-2.9.2.tgz",
"integrity": "sha512-Gr4p6nFNaoufRIY4NMdpQRNmgxVIGMs4Fcu/ujdYk3nAZqk7supzBE9idmvfZIlH/Cuj//dvi+019qEue9lV0w==",
"dev": true
},
"url-parse": {
"version": "1.4.3",
"resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.4.3.tgz",
"integrity": "sha512-rh+KuAW36YKo0vClhQzLLveoj8FwPJNu65xLb7Mrt+eZht0IPT0IXgSv8gcMegZ6NvjJUALf6Mf25POlMwD1Fw==",
"requires": {
"querystringify": "^2.0.0",
"requires-port": "^1.0.0"
}
},
"whatwg-fetch": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-3.0.0.tgz",
"integrity": "sha512-9GSJUgz1D4MfyKU7KRqwOjXCXTqWdFNvEr7eUBYchQiVc744mqK/MzXPNR2WsPkmkOa4ywfg8C2n8h+13Bey1Q=="
}
}
}

View File

@ -0,0 +1,31 @@
{
"name": "ts-petstore-client",
"version": "1.0.0",
"description": "OpenAPI client for ts-petstore-client",
"author": "OpenAPI-Generator Contributors",
"keywords": [
"fetch",
"typescript",
"openapi-client",
"openapi-generator"
],
"license": "Unlicense",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"scripts": {
"build": "tsc",
"prepublishOnly": "npm run build"
},
"dependencies": {
"isomorphic-fetch": "^2.2.1",
"@types/isomorphic-fetch": "0.0.34",
"@types/node": "*",
"form-data": "^2.5.0",
"btoa": "^1.2.1",
"es6-promise": "^4.2.4",
"url-parse": "^1.4.3"
},
"devDependencies": {
"typescript": "^2.9.2"
}
}

View File

@ -0,0 +1,60 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>TypeScriptBuildPetstoreClientSample</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>TS Default Petstore Client</name>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>npm-install</id>
<phase>pre-integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>npm-build</id>
<phase>pre-integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>run</argument>
<argument>build</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,27 @@
export class Observable<T> {
constructor(private promise: Promise<T>) {}
toPromise() {
return this.promise;
}
pipe<S>(callback: (value: T) => S | Promise<S>): Observable<S> {
return new Observable(this.promise.then(callback));
}
}
export function from<T>(promise: Promise<any>) {
return new Observable(promise);
}
export function of<T>(value: T) {
return new Observable<T>(Promise.resolve(value));
}
export function mergeMap<T, S>(callback: (value: T) => Observable<S>) {
return (value: T) => callback(value).toPromise();
}
export function map(callback: any) {
return callback;
}

View File

@ -0,0 +1,55 @@
import {RequestContext, HttpMethod} from './http/http';
/**
*
* Represents the configuration of a server including its
* url template and variable configuration based on the url.
*
*/
export class ServerConfiguration<T> {
public constructor(private url: string, private variableConfiguration: T) {
}
/**
* Sets the value of the variables of this server.
*
* @param variableConfiguration a partial variable configuration for the variables contained in the url
*/
public setVariables(variableConfiguration: Partial<T>) {
for (const key in variableConfiguration) {
const val = variableConfiguration[key]
// We know that val isn't undefined here - hopefully
if (val !== undefined) {
this.variableConfiguration[key] = val as T[Extract<keyof T, string>];
}
}
}
public getConfiguration(): T {
return this.variableConfiguration
}
private getUrl() {
let replacedUrl = this.url;
for (const key in this.variableConfiguration) {
var re = new RegExp("{" + key + "}","g");
replacedUrl = replacedUrl.replace(re, this.variableConfiguration[key].toString());
}
return replacedUrl
}
/**
* Creates a new request context for this server using the url with variables
* replaced with their respective values and the endpoint of the request appended.
*
* @param endpoint the endpoint to be queried on the server
* @param httpMethod httpMethod to be used
*
*/
public makeRequestContext(endpoint: string, httpMethod: HttpMethod): RequestContext {
return new RequestContext(this.getUrl() + endpoint, httpMethod);
}
}
export const server1 = new ServerConfiguration<{ }>("http://petstore.swagger.io/v2", { })

View File

@ -0,0 +1,29 @@
{
"compilerOptions": {
"strict": true,
/* Basic Options */
"target": "es5",
"module": "commonjs",
"declaration": true,
/* Additional Checks */
"noUnusedLocals": false, /* Report errors on unused locals. */ // TODO: reenable (unused imports!)
"noUnusedParameters": false, /* Report errors on unused parameters. */ // TODO: set to true again
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
"noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
"removeComments": true,
"sourceMap": true,
"outDir": "./dist",
"noLib": false,
"lib": [ "es6", "dom" ]
},
"exclude": [
"dist",
"node_modules"
],
"filesGlob": [
"./**/*.ts",
]
}

View File

@ -0,0 +1,540 @@
import { ResponseContext, RequestContext, HttpFile } from '../http/http';
import * as models from '../models/all';
import { Configuration} from '../configuration'
import { Observable, of } from '../rxjsStub';
import {mergeMap, map} from '../rxjsStub';
import { ApiResponse } from '../models/ApiResponse';
import { Category } from '../models/Category';
import { Order } from '../models/Order';
import { Pet } from '../models/Pet';
import { Tag } from '../models/Tag';
import { User } from '../models/User';
import { PetApiRequestFactory, PetApiResponseProcessor} from "../apis/PetApi";
export class ObservablePetApi {
private requestFactory: PetApiRequestFactory;
private responseProcessor: PetApiResponseProcessor;
private configuration: Configuration;
public constructor(configuration: Configuration, requestFactory?: PetApiRequestFactory, responseProcessor?: PetApiResponseProcessor) {
this.configuration = configuration;
this.requestFactory = requestFactory || new PetApiRequestFactory(configuration);
this.responseProcessor = responseProcessor || new PetApiResponseProcessor();
}
/**
* Add a new pet to the store
* @param body Pet object that needs to be added to the store
*/
public addPet(body: Pet, options?: Configuration): Observable<void> {
const requestContext = this.requestFactory.addPet(body, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.addPet(rsp)));
}));
}
/**
* Deletes a pet
* @param petId Pet id to delete
* @param apiKey
*/
public deletePet(petId: number, apiKey?: string, options?: Configuration): Observable<void> {
const requestContext = this.requestFactory.deletePet(petId, apiKey, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deletePet(rsp)));
}));
}
/**
* Multiple status values can be provided with comma separated strings
* Finds Pets by status
* @param status Status values that need to be considered for filter
*/
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Observable<Array<Pet>> {
const requestContext = this.requestFactory.findPetsByStatus(status, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.findPetsByStatus(rsp)));
}));
}
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* Finds Pets by tags
* @param tags Tags to filter by
*/
public findPetsByTags(tags: Array<string>, options?: Configuration): Observable<Array<Pet>> {
const requestContext = this.requestFactory.findPetsByTags(tags, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.findPetsByTags(rsp)));
}));
}
/**
* Returns a single pet
* Find pet by ID
* @param petId ID of pet to return
*/
public getPetById(petId: number, options?: Configuration): Observable<Pet> {
const requestContext = this.requestFactory.getPetById(petId, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getPetById(rsp)));
}));
}
/**
* Update an existing pet
* @param body Pet object that needs to be added to the store
*/
public updatePet(body: Pet, options?: Configuration): Observable<void> {
const requestContext = this.requestFactory.updatePet(body, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updatePet(rsp)));
}));
}
/**
* Updates a pet in the store with form data
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
*/
public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Observable<void> {
const requestContext = this.requestFactory.updatePetWithForm(petId, name, status, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updatePetWithForm(rsp)));
}));
}
/**
* uploads an image
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Observable<ApiResponse> {
const requestContext = this.requestFactory.uploadFile(petId, additionalMetadata, file, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.uploadFile(rsp)));
}));
}
}
import { StoreApiRequestFactory, StoreApiResponseProcessor} from "../apis/StoreApi";
export class ObservableStoreApi {
private requestFactory: StoreApiRequestFactory;
private responseProcessor: StoreApiResponseProcessor;
private configuration: Configuration;
public constructor(configuration: Configuration, requestFactory?: StoreApiRequestFactory, responseProcessor?: StoreApiResponseProcessor) {
this.configuration = configuration;
this.requestFactory = requestFactory || new StoreApiRequestFactory(configuration);
this.responseProcessor = responseProcessor || new StoreApiResponseProcessor();
}
/**
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* Delete purchase order by ID
* @param orderId ID of the order that needs to be deleted
*/
public deleteOrder(orderId: string, options?: Configuration): Observable<void> {
const requestContext = this.requestFactory.deleteOrder(orderId, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteOrder(rsp)));
}));
}
/**
* Returns a map of status codes to quantities
* Returns pet inventories by status
*/
public getInventory(options?: Configuration): Observable<{ [key: string]: number; }> {
const requestContext = this.requestFactory.getInventory(options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getInventory(rsp)));
}));
}
/**
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* Find purchase order by ID
* @param orderId ID of pet that needs to be fetched
*/
public getOrderById(orderId: number, options?: Configuration): Observable<Order> {
const requestContext = this.requestFactory.getOrderById(orderId, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getOrderById(rsp)));
}));
}
/**
* Place an order for a pet
* @param body order placed for purchasing the pet
*/
public placeOrder(body: Order, options?: Configuration): Observable<Order> {
const requestContext = this.requestFactory.placeOrder(body, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.placeOrder(rsp)));
}));
}
}
import { UserApiRequestFactory, UserApiResponseProcessor} from "../apis/UserApi";
export class ObservableUserApi {
private requestFactory: UserApiRequestFactory;
private responseProcessor: UserApiResponseProcessor;
private configuration: Configuration;
public constructor(configuration: Configuration, requestFactory?: UserApiRequestFactory, responseProcessor?: UserApiResponseProcessor) {
this.configuration = configuration;
this.requestFactory = requestFactory || new UserApiRequestFactory(configuration);
this.responseProcessor = responseProcessor || new UserApiResponseProcessor();
}
/**
* This can only be done by the logged in user.
* Create user
* @param body Created user object
*/
public createUser(body: User, options?: Configuration): Observable<void> {
const requestContext = this.requestFactory.createUser(body, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.createUser(rsp)));
}));
}
/**
* Creates list of users with given input array
* @param body List of user object
*/
public createUsersWithArrayInput(body: Array<User>, options?: Configuration): Observable<void> {
const requestContext = this.requestFactory.createUsersWithArrayInput(body, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.createUsersWithArrayInput(rsp)));
}));
}
/**
* Creates list of users with given input array
* @param body List of user object
*/
public createUsersWithListInput(body: Array<User>, options?: Configuration): Observable<void> {
const requestContext = this.requestFactory.createUsersWithListInput(body, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.createUsersWithListInput(rsp)));
}));
}
/**
* This can only be done by the logged in user.
* Delete user
* @param username The name that needs to be deleted
*/
public deleteUser(username: string, options?: Configuration): Observable<void> {
const requestContext = this.requestFactory.deleteUser(username, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.deleteUser(rsp)));
}));
}
/**
* Get user by user name
* @param username The name that needs to be fetched. Use user1 for testing.
*/
public getUserByName(username: string, options?: Configuration): Observable<User> {
const requestContext = this.requestFactory.getUserByName(username, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.getUserByName(rsp)));
}));
}
/**
* Logs user into the system
* @param username The user name for login
* @param password The password for login in clear text
*/
public loginUser(username: string, password: string, options?: Configuration): Observable<string> {
const requestContext = this.requestFactory.loginUser(username, password, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.loginUser(rsp)));
}));
}
/**
* Logs out current logged in user session
*/
public logoutUser(options?: Configuration): Observable<void> {
const requestContext = this.requestFactory.logoutUser(options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.logoutUser(rsp)));
}));
}
/**
* This can only be done by the logged in user.
* Updated user
* @param username name that need to be deleted
* @param body Updated user object
*/
public updateUser(username: string, body: User, options?: Configuration): Observable<void> {
const requestContext = this.requestFactory.updateUser(username, body, options);
// build promise chain
let middlewarePreObservable = of(requestContext);
for (let middleware of this.configuration.middleware) {
middlewarePreObservable = middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => middleware.pre(ctx)));
}
return middlewarePreObservable.pipe(mergeMap((ctx: RequestContext) => this.configuration.httpApi.send(ctx))).
pipe(mergeMap((response: ResponseContext) => {
let middlewarePostObservable = of(response);
for (let middleware of this.configuration.middleware) {
middlewarePostObservable = middlewarePostObservable.pipe(mergeMap((rsp: ResponseContext) => middleware.post(rsp)));
}
return middlewarePostObservable.pipe(map((rsp: ResponseContext) => this.responseProcessor.updateUser(rsp)));
}));
}
}

View File

@ -0,0 +1,252 @@
import { ResponseContext, RequestContext, HttpFile } from '../http/http';
import * as models from '../models/all';
import { Configuration} from '../configuration'
import { ApiResponse } from '../models/ApiResponse';
import { Category } from '../models/Category';
import { Order } from '../models/Order';
import { Pet } from '../models/Pet';
import { Tag } from '../models/Tag';
import { User } from '../models/User';
import { ObservablePetApi } from './ObservableAPI';
import { PetApiRequestFactory, PetApiResponseProcessor} from "../apis/PetApi";
export class PromisePetApi {
private api: ObservablePetApi
public constructor(configuration: Configuration, requestFactory?: PetApiRequestFactory, responseProcessor?: PetApiResponseProcessor) {
this.api = new ObservablePetApi(configuration, requestFactory, responseProcessor);
}
/**
* Add a new pet to the store
* @param body Pet object that needs to be added to the store
*/
public addPet(body: Pet, options?: Configuration): Promise<void> {
const result = this.api.addPet(body, options);
return result.toPromise();
}
/**
* Deletes a pet
* @param petId Pet id to delete
* @param apiKey
*/
public deletePet(petId: number, apiKey?: string, options?: Configuration): Promise<void> {
const result = this.api.deletePet(petId, apiKey, options);
return result.toPromise();
}
/**
* Multiple status values can be provided with comma separated strings
* Finds Pets by status
* @param status Status values that need to be considered for filter
*/
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): Promise<Array<Pet>> {
const result = this.api.findPetsByStatus(status, options);
return result.toPromise();
}
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* Finds Pets by tags
* @param tags Tags to filter by
*/
public findPetsByTags(tags: Array<string>, options?: Configuration): Promise<Array<Pet>> {
const result = this.api.findPetsByTags(tags, options);
return result.toPromise();
}
/**
* Returns a single pet
* Find pet by ID
* @param petId ID of pet to return
*/
public getPetById(petId: number, options?: Configuration): Promise<Pet> {
const result = this.api.getPetById(petId, options);
return result.toPromise();
}
/**
* Update an existing pet
* @param body Pet object that needs to be added to the store
*/
public updatePet(body: Pet, options?: Configuration): Promise<void> {
const result = this.api.updatePet(body, options);
return result.toPromise();
}
/**
* Updates a pet in the store with form data
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
*/
public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): Promise<void> {
const result = this.api.updatePetWithForm(petId, name, status, options);
return result.toPromise();
}
/**
* uploads an image
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): Promise<ApiResponse> {
const result = this.api.uploadFile(petId, additionalMetadata, file, options);
return result.toPromise();
}
}
import { ObservableStoreApi } from './ObservableAPI';
import { StoreApiRequestFactory, StoreApiResponseProcessor} from "../apis/StoreApi";
export class PromiseStoreApi {
private api: ObservableStoreApi
public constructor(configuration: Configuration, requestFactory?: StoreApiRequestFactory, responseProcessor?: StoreApiResponseProcessor) {
this.api = new ObservableStoreApi(configuration, requestFactory, responseProcessor);
}
/**
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* Delete purchase order by ID
* @param orderId ID of the order that needs to be deleted
*/
public deleteOrder(orderId: string, options?: Configuration): Promise<void> {
const result = this.api.deleteOrder(orderId, options);
return result.toPromise();
}
/**
* Returns a map of status codes to quantities
* Returns pet inventories by status
*/
public getInventory(options?: Configuration): Promise<{ [key: string]: number; }> {
const result = this.api.getInventory(options);
return result.toPromise();
}
/**
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* Find purchase order by ID
* @param orderId ID of pet that needs to be fetched
*/
public getOrderById(orderId: number, options?: Configuration): Promise<Order> {
const result = this.api.getOrderById(orderId, options);
return result.toPromise();
}
/**
* Place an order for a pet
* @param body order placed for purchasing the pet
*/
public placeOrder(body: Order, options?: Configuration): Promise<Order> {
const result = this.api.placeOrder(body, options);
return result.toPromise();
}
}
import { ObservableUserApi } from './ObservableAPI';
import { UserApiRequestFactory, UserApiResponseProcessor} from "../apis/UserApi";
export class PromiseUserApi {
private api: ObservableUserApi
public constructor(configuration: Configuration, requestFactory?: UserApiRequestFactory, responseProcessor?: UserApiResponseProcessor) {
this.api = new ObservableUserApi(configuration, requestFactory, responseProcessor);
}
/**
* This can only be done by the logged in user.
* Create user
* @param body Created user object
*/
public createUser(body: User, options?: Configuration): Promise<void> {
const result = this.api.createUser(body, options);
return result.toPromise();
}
/**
* Creates list of users with given input array
* @param body List of user object
*/
public createUsersWithArrayInput(body: Array<User>, options?: Configuration): Promise<void> {
const result = this.api.createUsersWithArrayInput(body, options);
return result.toPromise();
}
/**
* Creates list of users with given input array
* @param body List of user object
*/
public createUsersWithListInput(body: Array<User>, options?: Configuration): Promise<void> {
const result = this.api.createUsersWithListInput(body, options);
return result.toPromise();
}
/**
* This can only be done by the logged in user.
* Delete user
* @param username The name that needs to be deleted
*/
public deleteUser(username: string, options?: Configuration): Promise<void> {
const result = this.api.deleteUser(username, options);
return result.toPromise();
}
/**
* Get user by user name
* @param username The name that needs to be fetched. Use user1 for testing.
*/
public getUserByName(username: string, options?: Configuration): Promise<User> {
const result = this.api.getUserByName(username, options);
return result.toPromise();
}
/**
* Logs user into the system
* @param username The user name for login
* @param password The password for login in clear text
*/
public loginUser(username: string, password: string, options?: Configuration): Promise<string> {
const result = this.api.loginUser(username, password, options);
return result.toPromise();
}
/**
* Logs out current logged in user session
*/
public logoutUser(options?: Configuration): Promise<void> {
const result = this.api.logoutUser(options);
return result.toPromise();
}
/**
* This can only be done by the logged in user.
* Updated user
* @param username name that need to be deleted
* @param body Updated user object
*/
public updateUser(username: string, body: User, options?: Configuration): Promise<void> {
const result = this.api.updateUser(username, body, options);
return result.toPromise();
}
}

View File

@ -0,0 +1,28 @@
/**
* Returns if a specific http code is in a given code range
* where the code range is defined as a combination of digits
* and "X" (the letter X) with a length of 3
*
* @param codeRange string with length 3 consisting of digits and "X" (the letter X)
* @param code the http status code to be checked against the code range
*/
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;
}
}

View File

@ -0,0 +1 @@
dist

View File

@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -0,0 +1 @@
4.3.1-SNAPSHOT

View File

@ -0,0 +1,30 @@
## ts-petstore-client@1.0.0
This generator creates TypeScript/JavaScript client that utilizes jquery.
### Building
To build and compile the typescript sources to javascript use:
```
npm install
npm run build
```
### Publishing
First build the package then run ```npm publish```
### Consuming
navigate to the folder of your consuming project and run one of the following commands.
_published:_
```
npm install ts-petstore-client@1.0.0 --save
```
_unPublished (not recommended):_
```
npm install PATH_TO_GENERATED_PACKAGE --save

View File

@ -0,0 +1,5 @@
Use qunit + https://github.com/ameshkov/node-qunit-puppeteer
to run the tests locally using a headless chromium!
ADD https://github.com/chenglou/require-polyfill to make require work

View File

@ -0,0 +1,583 @@
// TODO: better import syntax?
import { BaseAPIRequestFactory, RequiredError } from './baseapi';
import {Configuration} from '../configuration';
import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http';
import {ObjectSerializer} from '../models/ObjectSerializer';
import {ApiException} from './exception';
import {isCodeInRange} from '../util';
import { ApiResponse } from '../models/ApiResponse';
import { Pet } from '../models/Pet';
/**
* no description
*/
export class PetApiRequestFactory extends BaseAPIRequestFactory {
/**
* Add a new pet to the store
* @param body Pet object that needs to be added to the store
*/
public addPet(body: Pet, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('Required parameter body was null or undefined when calling addPet.');
}
// Path Params
const localVarPath = '/pet';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
requestContext.setHeaderParam("Content-Type", "application/json");
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"Pet" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify(body || {}) : (body.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["petstore_auth"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* Deletes a pet
* @param petId Pet id to delete
* @param apiKey
*/
public deletePet(petId: number, apiKey?: string, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new RequiredError('Required parameter petId was null or undefined when calling deletePet.');
}
// Path Params
const localVarPath = '/pet/{petId}'
.replace('{' + 'petId' + '}', encodeURIComponent(String(petId)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
requestContext.setHeaderParam("api_key", ObjectSerializer.serialize(apiKey, "string", ""));
// Form Params
// Body Params
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["petstore_auth"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* Multiple status values can be provided with comma separated strings
* Finds Pets by status
* @param status Status values that need to be considered for filter
*/
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'status' is not null or undefined
if (status === null || status === undefined) {
throw new RequiredError('Required parameter status was null or undefined when calling findPetsByStatus.');
}
// Path Params
const localVarPath = '/pet/findByStatus';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
if (status !== undefined) {
requestContext.setQueryParam("status", ObjectSerializer.serialize(status, "Array<'available' | 'pending' | 'sold'>", ""));
}
// Header Params
// Form Params
// Body Params
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["petstore_auth"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* Finds Pets by tags
* @param tags Tags to filter by
*/
public findPetsByTags(tags: Array<string>, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'tags' is not null or undefined
if (tags === null || tags === undefined) {
throw new RequiredError('Required parameter tags was null or undefined when calling findPetsByTags.');
}
// Path Params
const localVarPath = '/pet/findByTags';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
if (tags !== undefined) {
requestContext.setQueryParam("tags", ObjectSerializer.serialize(tags, "Array<string>", ""));
}
// Header Params
// Form Params
// Body Params
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["petstore_auth"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* Returns a single pet
* Find pet by ID
* @param petId ID of pet to return
*/
public getPetById(petId: number, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new RequiredError('Required parameter petId was null or undefined when calling getPetById.');
}
// Path Params
const localVarPath = '/pet/{petId}'
.replace('{' + 'petId' + '}', encodeURIComponent(String(petId)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["api_key"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* Update an existing pet
* @param body Pet object that needs to be added to the store
*/
public updatePet(body: Pet, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('Required parameter body was null or undefined when calling updatePet.');
}
// Path Params
const localVarPath = '/pet';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
requestContext.setHeaderParam("Content-Type", "application/json");
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"Pet" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify(body || {}) : (body.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["petstore_auth"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* Updates a pet in the store with form data
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
*/
public updatePetWithForm(petId: number, name?: string, status?: string, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new RequiredError('Required parameter petId was null or undefined when calling updatePetWithForm.');
}
// Path Params
const localVarPath = '/pet/{petId}'
.replace('{' + 'petId' + '}', encodeURIComponent(String(petId)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
let localVarFormParams = new FormData();
if (name !== undefined) {
// TODO: replace .append with .set
localVarFormParams.append('name', name as any);
}
if (status !== undefined) {
// TODO: replace .append with .set
localVarFormParams.append('status', status as any);
}
requestContext.setBody(localVarFormParams);
// Body Params
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["petstore_auth"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* uploads an image
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
public uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'petId' is not null or undefined
if (petId === null || petId === undefined) {
throw new RequiredError('Required parameter petId was null or undefined when calling uploadFile.');
}
// Path Params
const localVarPath = '/pet/{petId}/uploadImage'
.replace('{' + 'petId' + '}', encodeURIComponent(String(petId)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
let localVarFormParams = new FormData();
if (additionalMetadata !== undefined) {
// TODO: replace .append with .set
localVarFormParams.append('additionalMetadata', additionalMetadata as any);
}
if (file !== undefined) {
// TODO: replace .append with .set
localVarFormParams.append('file', file.data, file.name);
}
requestContext.setBody(localVarFormParams);
// Body Params
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["petstore_auth"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
}
export class PetApiResponseProcessor {
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public addPet(response: ResponseContext): void {
if (isCodeInRange("405", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Invalid input");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public deletePet(response: ResponseContext): void {
if (isCodeInRange("400", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Invalid pet value");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public findPetsByStatus(response: ResponseContext): Array<Pet> {
if (isCodeInRange("200", response.httpStatusCode)) {
const jsonBody = JSON.parse(response.body);
const body: Array<Pet> = ObjectSerializer.deserialize(jsonBody, "Array<Pet>", "") as Array<Pet>;
return body;
}
if (isCodeInRange("400", response.httpStatusCode)) {
throw new ApiException<string>(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<Pet> = ObjectSerializer.deserialize(jsonBody, "Array<Pet>", "") as Array<Pet>;
return body;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public findPetsByTags(response: ResponseContext): Array<Pet> {
if (isCodeInRange("200", response.httpStatusCode)) {
const jsonBody = JSON.parse(response.body);
const body: Array<Pet> = ObjectSerializer.deserialize(jsonBody, "Array<Pet>", "") as Array<Pet>;
return body;
}
if (isCodeInRange("400", response.httpStatusCode)) {
throw new ApiException<string>(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<Pet> = ObjectSerializer.deserialize(jsonBody, "Array<Pet>", "") as Array<Pet>;
return body;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
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<string>(response.httpStatusCode, "Invalid ID supplied");
}
if (isCodeInRange("404", response.httpStatusCode)) {
throw new ApiException<string>(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;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public updatePet(response: ResponseContext): void {
if (isCodeInRange("400", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Invalid ID supplied");
}
if (isCodeInRange("404", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Pet not found");
}
if (isCodeInRange("405", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Validation exception");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public updatePetWithForm(response: ResponseContext): void {
if (isCodeInRange("405", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Invalid input");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
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;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
}

View File

@ -0,0 +1,270 @@
// TODO: better import syntax?
import { BaseAPIRequestFactory, RequiredError } from './baseapi';
import {Configuration} from '../configuration';
import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http';
import {ObjectSerializer} from '../models/ObjectSerializer';
import {ApiException} from './exception';
import {isCodeInRange} from '../util';
import { Order } from '../models/Order';
/**
* no description
*/
export class StoreApiRequestFactory extends BaseAPIRequestFactory {
/**
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* Delete purchase order by ID
* @param orderId ID of the order that needs to be deleted
*/
public deleteOrder(orderId: string, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'orderId' is not null or undefined
if (orderId === null || orderId === undefined) {
throw new RequiredError('Required parameter orderId was null or undefined when calling deleteOrder.');
}
// Path Params
const localVarPath = '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
// Apply auth methods
return requestContext;
}
/**
* Returns a map of status codes to quantities
* Returns pet inventories by status
*/
public getInventory(options?: Configuration): RequestContext {
let config = options || this.configuration;
// Path Params
const localVarPath = '/store/inventory';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
let authMethod = null;
// Apply auth methods
authMethod = config.authMethods["api_key"]
if (authMethod) {
authMethod.applySecurityAuthentication(requestContext);
}
return requestContext;
}
/**
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* Find purchase order by ID
* @param orderId ID of pet that needs to be fetched
*/
public getOrderById(orderId: number, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'orderId' is not null or undefined
if (orderId === null || orderId === undefined) {
throw new RequiredError('Required parameter orderId was null or undefined when calling getOrderById.');
}
// Path Params
const localVarPath = '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', encodeURIComponent(String(orderId)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
// Apply auth methods
return requestContext;
}
/**
* Place an order for a pet
* @param body order placed for purchasing the pet
*/
public placeOrder(body: Order, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('Required parameter body was null or undefined when calling placeOrder.');
}
// Path Params
const localVarPath = '/store/order';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
requestContext.setHeaderParam("Content-Type", "application/json");
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"Order" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify(body || {}) : (body.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
// Apply auth methods
return requestContext;
}
}
export class StoreApiResponseProcessor {
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public deleteOrder(response: ResponseContext): void {
if (isCodeInRange("400", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Invalid ID supplied");
}
if (isCodeInRange("404", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Order not found");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
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; }", "int32") 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; }", "int32") as { [key: string]: number; };
return body;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
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<string>(response.httpStatusCode, "Invalid ID supplied");
}
if (isCodeInRange("404", response.httpStatusCode)) {
throw new ApiException<string>(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;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
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<string>(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;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
}

View File

@ -0,0 +1,516 @@
// TODO: better import syntax?
import { BaseAPIRequestFactory, RequiredError } from './baseapi';
import {Configuration} from '../configuration';
import { RequestContext, HttpMethod, ResponseContext, HttpFile} from '../http/http';
import {ObjectSerializer} from '../models/ObjectSerializer';
import {ApiException} from './exception';
import {isCodeInRange} from '../util';
import { User } from '../models/User';
/**
* no description
*/
export class UserApiRequestFactory extends BaseAPIRequestFactory {
/**
* This can only be done by the logged in user.
* Create user
* @param body Created user object
*/
public createUser(body: User, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('Required parameter body was null or undefined when calling createUser.');
}
// Path Params
const localVarPath = '/user';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
requestContext.setHeaderParam("Content-Type", "application/json");
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"User" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify(body || {}) : (body.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
// Apply auth methods
return requestContext;
}
/**
* Creates list of users with given input array
* @param body List of user object
*/
public createUsersWithArrayInput(body: Array<User>, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('Required parameter body was null or undefined when calling createUsersWithArrayInput.');
}
// Path Params
const localVarPath = '/user/createWithArray';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
requestContext.setHeaderParam("Content-Type", "application/json");
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"Array&lt;User&gt;" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify(body || {}) : (body.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
// Apply auth methods
return requestContext;
}
/**
* Creates list of users with given input array
* @param body List of user object
*/
public createUsersWithListInput(body: Array<User>, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('Required parameter body was null or undefined when calling createUsersWithListInput.');
}
// Path Params
const localVarPath = '/user/createWithList';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
requestContext.setHeaderParam("Content-Type", "application/json");
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"Array&lt;User&gt;" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify(body || {}) : (body.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
// Apply auth methods
return requestContext;
}
/**
* This can only be done by the logged in user.
* Delete user
* @param username The name that needs to be deleted
*/
public deleteUser(username: string, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new RequiredError('Required parameter username was null or undefined when calling deleteUser.');
}
// Path Params
const localVarPath = '/user/{username}'
.replace('{' + 'username' + '}', encodeURIComponent(String(username)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.DELETE);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
// Apply auth methods
return requestContext;
}
/**
* Get user by user name
* @param username The name that needs to be fetched. Use user1 for testing.
*/
public getUserByName(username: string, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new RequiredError('Required parameter username was null or undefined when calling getUserByName.');
}
// Path Params
const localVarPath = '/user/{username}'
.replace('{' + 'username' + '}', encodeURIComponent(String(username)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
// Apply auth methods
return requestContext;
}
/**
* Logs user into the system
* @param username The user name for login
* @param password The password for login in clear text
*/
public loginUser(username: string, password: string, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new RequiredError('Required parameter username was null or undefined when calling loginUser.');
}
// verify required parameter 'password' is not null or undefined
if (password === null || password === undefined) {
throw new RequiredError('Required parameter password was null or undefined when calling loginUser.');
}
// Path Params
const localVarPath = '/user/login';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
if (username !== undefined) {
requestContext.setQueryParam("username", ObjectSerializer.serialize(username, "string", ""));
}
if (password !== undefined) {
requestContext.setQueryParam("password", ObjectSerializer.serialize(password, "string", ""));
}
// Header Params
// Form Params
// Body Params
// Apply auth methods
return requestContext;
}
/**
* Logs out current logged in user session
*/
public logoutUser(options?: Configuration): RequestContext {
let config = options || this.configuration;
// Path Params
const localVarPath = '/user/logout';
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
// Apply auth methods
return requestContext;
}
/**
* This can only be done by the logged in user.
* Updated user
* @param username name that need to be deleted
* @param body Updated user object
*/
public updateUser(username: string, body: User, options?: Configuration): RequestContext {
let config = options || this.configuration;
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new RequiredError('Required parameter username was null or undefined when calling updateUser.');
}
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new RequiredError('Required parameter body was null or undefined when calling updateUser.');
}
// Path Params
const localVarPath = '/user/{username}'
.replace('{' + 'username' + '}', encodeURIComponent(String(username)));
// Make Request Context
const requestContext = config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT);
requestContext.setHeaderParam("Accept", "application/json")
// Query Params
// Header Params
// Form Params
// Body Params
requestContext.setHeaderParam("Content-Type", "application/json");
// TODO: Should this be handled by ObjectSerializer? imo yes => confidential information included in local object should not be sent
const needsSerialization = (<any>"User" !== "string") || requestContext.getHeaders()['Content-Type'] === 'application/json';
const serializedBody = needsSerialization ? JSON.stringify(body || {}) : (body.toString() || ""); // TODO: `toString` call is unnecessary
requestContext.setBody(serializedBody);
// Apply auth methods
return requestContext;
}
}
export class UserApiResponseProcessor {
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public createUser(response: ResponseContext): void {
if (isCodeInRange("0", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "successful operation");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public createUsersWithArrayInput(response: ResponseContext): void {
if (isCodeInRange("0", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "successful operation");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public createUsersWithListInput(response: ResponseContext): void {
if (isCodeInRange("0", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "successful operation");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public deleteUser(response: ResponseContext): void {
if (isCodeInRange("400", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Invalid username supplied");
}
if (isCodeInRange("404", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "User not found");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
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<string>(response.httpStatusCode, "Invalid username supplied");
}
if (isCodeInRange("404", response.httpStatusCode)) {
throw new ApiException<string>(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;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
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<string>(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;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public logoutUser(response: ResponseContext): void {
if (isCodeInRange("0", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "successful operation");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
/**
* Unwraps the actual response sent by the server from the response context and deserializes the response content
* to the expected objects
*
* @params response Response returned by the server for a request to
* @throws ApiException if the response code was not in [200, 299]
*/
public updateUser(response: ResponseContext): void {
if (isCodeInRange("400", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "Invalid user supplied");
}
if (isCodeInRange("404", response.httpStatusCode)) {
throw new ApiException<string>(response.httpStatusCode, "User not found");
}
// Work around for incorrect api specification in petstore.yaml
if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) {
return;
}
let body = response.body || "";
throw new ApiException<string>(response.httpStatusCode, "Unknown API Status Code!\nBody: \"" + body + "\"");
}
}

View File

@ -0,0 +1,37 @@
import { Configuration } from '../configuration'
/**
*
* @export
*/
export const COLLECTION_FORMATS = {
csv: ",",
ssv: " ",
tsv: "\t",
pipes: "|",
};
/**
*
* @export
* @class BaseAPI
*/
export class BaseAPIRequestFactory {
constructor(protected configuration: Configuration) {
}
};
/**
*
* @export
* @class RequiredError
* @extends {Error}
*/
export class RequiredError extends Error {
name: "RequiredError" = "RequiredError";
constructor(public field: string, msg?: string) {
super(msg);
}
}

View File

@ -0,0 +1,14 @@
/**
* Represents an error caused by an api call i.e. it has attributes for a HTTP status code
* and the returned body object.
*
* Example
* API returns a ErrorMessageObject whenever HTTP status code is not in [200, 299]
* => ApiException(404, someErrorMessageObject)
*
*/
export class ApiException<T> extends Error {
public constructor(public code: number, public body: T) {
super("HTTP-Code: " + code + "\nMessage: " + JSON.stringify(body))
}
}

View File

@ -0,0 +1,145 @@
import {RequestContext} from '../http/http';
// typings for btoa are incorrect
//@ts-ignore
import * as btoa from "btoa";
/**
* Base class for all authentication schemes.
*
*/
export abstract class SecurityAuthentication {
public constructor(private name: string) {
}
/*
*
* @return returns the name of the security authentication as specified in OAI
*/
public getName(): string {
return this.name;
}
/**
* Applies the authentication scheme to the request context
*
* @params context the request context which should use this authentication scheme
*/
public abstract applySecurityAuthentication(context: RequestContext): void;
}
/**
* Applies no authentication.
*
*/
export class NoAuthentication extends SecurityAuthentication {
public constructor() {
super("_no_auth");
}
public applySecurityAuthentication(_context: RequestContext) {
}
}
/**
* Applies an api key to the request context.
*
*/
export class APIKeyAuthentication extends SecurityAuthentication {
/**
* Configures this api key authentication with the necessary properties
*
* @param authName: name of this authentication scheme as specified in the swagger.json
* @param paramName: Parameter name used for the api key
* @param keyLocation: Parameter location, either query, header or cookie.
* @param apiKey: The api key to be used for every request
*/
public constructor(authName: string, private paramName: string, private keyLocation: "query" | "header" | "cookie", private apiKey: string) {
super(authName);
}
public applySecurityAuthentication(context: RequestContext) {
if (this.keyLocation === "header") {
context.setHeaderParam(this.paramName, this.apiKey);
} else if (this.keyLocation === "cookie") {
context.addCookie(this.paramName, this.apiKey);
} else if (this.keyLocation === "query") {
context.setQueryParam(this.paramName, this.apiKey);
}
}
}
/**
* Applies basic http authentication to a request.
*
*/
export class HttpBasicAuthentication extends SecurityAuthentication {
/**
* Configures the http authentication with the required details.
*
*
* @param authName name of the authentication scheme as defined in swagger json
* @param username username for http basic authentication
* @param password password for http basic authentication
*/
public constructor(authName: string, private username: string, private password: string) {
super(authName);
}
public applySecurityAuthentication(context: RequestContext) {
let comb = this.username + ":" + this.password;
context.setHeaderParam("Authentication", "Basic " + btoa(comb));
}
}
// TODO: How to handle oauth2 authentication!
export class OAuth2Authentication extends SecurityAuthentication {
public constructor(authName: string) {
super(authName);
}
public applySecurityAuthentication(context: RequestContext) {
// TODO
}
}
export type AuthMethods = {
"api_key"?: APIKeyAuthentication,
"petstore_auth"?: OAuth2Authentication,
}
export type ApiKeyConfiguration = string;
export type HttpBasicConfiguration = { "username": string, "password": string };
export type OAuth2Configuration = string;
export type AuthMethodsConfiguration = { "api_key"?:ApiKeyConfiguration, "petstore_auth"?:OAuth2Configuration, }
/**
* Creates the authentication methods from a swagger description.
*
*/
export function configureAuthMethods(conf: AuthMethodsConfiguration | undefined): AuthMethods {
let authMethods: AuthMethods = {
}
if (!conf) {
return authMethods;
}
if (conf["api_key"]) {
authMethods["api_key"] = new APIKeyAuthentication("api_key", "api_key", "header", <string> conf["api_key"]);
}
if (conf["petstore_auth"]) {
authMethods["petstore_auth"] = new OAuth2Authentication("petstore_auth");
}
return authMethods;
}

View File

@ -0,0 +1,60 @@
import {HttpLibrary} from './http/http';
import {Middleware, PromiseMiddleware, PromiseMiddlewareWrapper} from './middleware';
import {JQueryHttpLibrary} from "./http/jquery";
import {ServerConfiguration, server1} from './servers';
import {configureAuthMethods, AuthMethods, AuthMethodsConfiguration} from './auth/auth';
/**
* Inetrface with which a configuration object can be configured.
*
*/
export interface ConfigurationParameters {
/**
* Default server to use
*/
baseServer?: ServerConfiguration<any>;
/**
* HTTP library to use e.g. IsomorphicFetch
*/
httpApi?: HttpLibrary;
/**
* The middlewares which will be applied to requests and responses
*/
middleware?: Middleware[]; // middleware to apply before/after fetch requests
/**
* configures all middlewares using the promise api instead of observables (which Middleware uses)
*/
promiseMiddleware?: PromiseMiddleware[];
/**
* Configuration for the available authentication methods
*/
authMethods?: AuthMethodsConfiguration
}
export class Configuration {
baseServer: ServerConfiguration<any>;
httpApi: HttpLibrary;
middleware: Middleware[];
authMethods: AuthMethods;
/**
* Creates a new configuration object based on the given configuration.
* If a property is not included in conf, a default is used:
* - baseServer: server1
* - httpApi: IsomorphicFetchHttpLibrary
* - middleware: []
* - promiseMiddleware: []
* - authMethods: {}
* @param conf particial configuration
*/
constructor(conf: ConfigurationParameters = {}) {
this.baseServer = conf.baseServer !== undefined ? conf.baseServer : server1;
this.httpApi = conf.httpApi || new JQueryHttpLibrary; // TODO: replace with window.fetch if available?
this.middleware = conf.middleware || [];
this.authMethods = configureAuthMethods(conf.authMethods);
if (conf.promiseMiddleware) {
conf.promiseMiddleware.forEach(m => this.middleware.push(new PromiseMiddlewareWrapper(m)));
}
}
}

View File

@ -0,0 +1,52 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update"
git_user_id=$1
git_repo_id=$2
release_note=$3
if [ "$git_user_id" = "" ]; then
git_user_id="GIT_USER_ID"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="GIT_REPO_ID"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="Minor update"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -0,0 +1,138 @@
// typings of url-parse are incorrect...
// @ts-ignore
import * as URLParse from "url-parse";
import { Observable } from '../rxjsStub';
export * from './jquery';
/**
* Represents a HTTP Method.
*/
export enum HttpMethod {
GET = "GET",
HEAD = "HEAD",
POST = "POST",
PUT = "PUT",
DELETE = "DELETE",
CONNECT = "CONNECT",
OPTIONS = "OPTIONS",
TRACE = "TRACE",
PATCH = "PATCH"
}
/**
* Represents a http file which will be uploaded to a server.
*/
export interface HttpFile {
data: Blob;
name: string;
}
export class HttpException extends Error {
public constructor(msg: string) {
super(msg);
}
}
/**
* Represents a HTTP request context
*
*/
export class RequestContext {
private headers: { [key: string]: string } = {};
private body: string | FormData = "";
private url: URLParse;
/**
* Creates the request context using a http method and request resource url
*
* @param url url of the requested resource
* @param httpMethod http method
*/
public constructor(url: string, private httpMethod: HttpMethod) {
this.url = URLParse(url, true);
}
/*
* Returns the url set in the constructor including the query string
*
*/
public getUrl(): string {
return this.url.toString();
}
/**
* Replaces the url set in the constructor with this url.
*
*/
public setUrl(url: string) {
this.url = URLParse(url, true);
}
/**
* Sets the body of the http request either as a string or FormData
* Setting a body on a HTTP GET request is disallowed under HTTP-Spec 1.1. Section
* 4.3 and this method throws an HttpException accordingly.
*
* @param body the body of the request
*/
public setBody(body: string | FormData) {
// HTTP-Spec 1.1 Section 4.3
if (this.httpMethod === HttpMethod.GET) {
throw new HttpException("Body should not be included in GET-Requests!");
}
// TODO: other http methods
// post is fine either formData or string
this.body = body;
}
public getHttpMethod(): HttpMethod {
return this.httpMethod;
}
public getHeaders(): { [key: string]: string } {
return this.headers;
}
public getBody(): string | FormData {
return this.body;
}
public setQueryParam(name: string, value: string) {
let queryObj = this.url.query;
queryObj[name] = value;
this.url.set("query", queryObj);
}
/**
* Sets a cookie with the name and value. NO check for duplicate cookies is performed
*
*/
public addCookie(name: string, value: string): void {
if (!this.headers["Cookie"]) {
this.headers["Cookie"] = "";
}
this.headers["Cookie"] += name + "=" + value + "; ";
}
public setHeaderParam(key: string, value: string): void {
this.headers[key] = value;
}
}
export class ResponseContext {
public constructor(public httpStatusCode: number,
public headers: { [key: string]: string }, public body: string) {
}
}
export interface HttpLibrary {
send(request: RequestContext): Observable<ResponseContext>;
}

View File

@ -0,0 +1,74 @@
import {HttpLibrary, RequestContext, ResponseContext, HttpException} from './http';
import * as e6p from 'es6-promise'
import { from, Observable } from '../rxjsStub';
e6p.polyfill();
import * as $ from 'jquery';
export class JQueryHttpLibrary implements HttpLibrary {
public send(request: RequestContext): Observable<ResponseContext> {
let method = request.getHttpMethod().toString();
let body = request.getBody();
let headerParams = request.getHeaders()
let requestOptions: any = {
url: request.getUrl(),
type: method,
headers: request.getHeaders(),
processData: false,
xhrFields: { withCredentials: true },
data: body
};
if (request.getHeaders()['Content-Type']) {
requestOptions.contentType = headerParams['Content-Type'];
}
requestOptions.dataFilter = ((headerParams: { [key:string]: string}) => {
return (data: string, type: string) => {
if (headerParams["Accept"] == "application/json" && data == "") {
return "{}"
} else {
return data
}
}
})(headerParams);
if (request.getHeaders()["Cookie"]) {
throw new HttpException("Setting the \"Cookie\"-Header field is blocked by every major browser when using jquery.ajax requests. Please switch to another library like fetch to enable this option");
}
if (body.constructor.name == "FormData") {
requestOptions.contentType = false;
}
const sentRequest = $.ajax(requestOptions);
const resultPromise = new Promise<ResponseContext>((resolve, reject) => {
sentRequest.done((resp, _, jqXHR) => {
const headers = this.getResponseHeaders(jqXHR)
const result = new ResponseContext(jqXHR.status, headers, JSON.stringify(resp));
resolve(result);
})
sentRequest.fail((jqXHR: any) => {
const headers = this.getResponseHeaders(jqXHR)
const result = new ResponseContext(jqXHR.status, headers, jqXHR.responseText);
resolve(result);
})
})
return from(resultPromise);
}
private getResponseHeaders(jqXHR: any): { [key: string]: string } {
const responseHeaders: { [key: string]: string } = {};
var headers = jqXHR.getAllResponseHeaders();
headers = headers.split("\n");
headers.forEach(function (header: any) {
header = header.split(": ");
var key = header.shift();
if (key.length == 0) return
// chrome60+ force lowercase, other browsers can be different
key = key.toLowerCase();
responseHeaders[key] = header.join(": ");
});
return responseHeaders
}
}

View File

@ -0,0 +1,7 @@
export * from './http/http';
export * from './auth/auth';
export {Middleware, PromiseMiddleware} from './middleware';
export * from './models/all';
export { Configuration} from './configuration'
export * from './types/PromiseAPI';
export * from './apis/exception';

View File

@ -0,0 +1,66 @@
import {RequestContext, ResponseContext} from './http/http';
import { Observable, from } from './rxjsStub';
/**
* Defines the contract for a middleware intercepting requests before
* they are sent (but after the RequestContext was created)
* and before the ResponseContext is unwrapped.
*
*/
export interface Middleware {
/**
* Modifies the request before the request is sent.
*
* @param context RequestContext of a request which is about to be sent to the server
* @returns an observable of the updated request context
*
*/
pre(context: RequestContext): Observable<RequestContext>;
/**
* Modifies the returned response before it is deserialized.
*
* @param context ResponseContext of a sent request
* @returns an observable of the modified response context
*/
post(context: ResponseContext): Observable<ResponseContext>;
}
export class PromiseMiddlewareWrapper implements Middleware {
public constructor(private middleware: PromiseMiddleware) {
}
pre(context: RequestContext): Observable<RequestContext> {
return from(this.middleware.pre(context));
}
post(context: ResponseContext): Observable<ResponseContext> {
return from(this.middleware.post(context));
}
}
/**
* Defines the contract for a middleware intercepting requests before
* they are sent (but after the RequestContext was created)
* and before the ResponseContext is unwrapped.
*
*/
export interface PromiseMiddleware {
/**
* Modifies the request before the request is sent.
*
* @param context RequestContext of a request which is about to be sent to the server
* @returns an observable of the updated request context
*
*/
pre(context: RequestContext): Promise<RequestContext>;
/**
* Modifies the returned response before it is deserialized.
*
* @param context ResponseContext of a sent request
* @returns an observable of the modified response context
*/
post(context: ResponseContext): Promise<ResponseContext>;
}

View File

@ -0,0 +1,51 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* Describes the result of uploading an image resource
*/
export class ApiResponse {
'code'?: number;
'type'?: string;
'message'?: string;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{
"name": "code",
"baseName": "code",
"type": "number",
"format": "int32"
},
{
"name": "type",
"baseName": "type",
"type": "string",
"format": ""
},
{
"name": "message",
"baseName": "message",
"type": "string",
"format": ""
} ];
static getAttributeTypeMap() {
return ApiResponse.attributeTypeMap;
}
public constructor() {
}
}

View File

@ -0,0 +1,44 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A category for a pet
*/
export class Category {
'id'?: number;
'name'?: string;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{
"name": "id",
"baseName": "id",
"type": "number",
"format": "int64"
},
{
"name": "name",
"baseName": "name",
"type": "string",
"format": ""
} ];
static getAttributeTypeMap() {
return Category.attributeTypeMap;
}
public constructor() {
}
}

View File

@ -0,0 +1,159 @@
export * from './ApiResponse';
export * from './Category';
export * from './Order';
export * from './Pet';
export * from './Tag';
export * from './User';
import { ApiResponse } from './ApiResponse';
import { Category } from './Category';
import { Order , OrderStatusEnum } from './Order';
import { Pet , PetStatusEnum } from './Pet';
import { Tag } from './Tag';
import { User } from './User';
/* tslint:disable:no-unused-variable */
let primitives = [
"string",
"boolean",
"double",
"integer",
"long",
"float",
"number",
"any"
];
let enumsMap: Set<string> = new Set<string>([
"OrderStatusEnum",
"PetStatusEnum",
]);
let typeMap: {[index: string]: any} = {
"ApiResponse": ApiResponse,
"Category": Category,
"Order": Order,
"Pet": Pet,
"Tag": Tag,
"User": User,
}
export class ObjectSerializer {
public static findCorrectType(data: any, expectedType: string) {
if (data == undefined) {
return expectedType;
} else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) {
return expectedType;
} else if (expectedType === "Date") {
return expectedType;
} else {
if (enumsMap.has(expectedType)) {
return expectedType;
}
if (!typeMap[expectedType]) {
return expectedType; // w/e we don't know the type
}
// Check the discriminator
let discriminatorProperty = typeMap[expectedType].discriminator;
if (discriminatorProperty == null) {
return expectedType; // the type does not have a discriminator. use it.
} else {
if (data[discriminatorProperty]) {
var discriminatorType = data[discriminatorProperty];
if(typeMap[discriminatorType]){
return discriminatorType; // use the type given in the discriminator
} else {
return expectedType; // discriminator did not map to a type
}
} else {
return expectedType; // discriminator was not present (or an empty string)
}
}
}
}
public static serialize(data: any, type: string, format: string) {
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index in data) {
let date = data[index];
transformedData.push(ObjectSerializer.serialize(date, subType, format));
}
return transformedData;
} else if (type === "Date") {
if (format == "date") {
let month = data.getMonth()+1
month = month < 10 ? "0" + month.toString() : month.toString()
let day = data.getDate();
day = day < 10 ? "0" + day.toString() : day.toString();
return data.getFullYear() + "-" + month + "-" + day;
} else {
return data.toISOString();
}
} else {
if (enumsMap.has(type)) {
return data;
}
if (!typeMap[type]) { // in case we dont know the type
return data;
}
// Get the actual type of this object
type = this.findCorrectType(data, type);
// get the map for the correct type.
let attributeTypes = typeMap[type].getAttributeTypeMap();
let instance: {[index: string]: any} = {};
for (let index in attributeTypes) {
let attributeType = attributeTypes[index];
instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type, attributeType.format);
}
return instance;
}
}
public static deserialize(data: any, type: string, format: string) {
// polymorphism may change the actual type.
type = ObjectSerializer.findCorrectType(data, type);
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index in data) {
let date = data[index];
transformedData.push(ObjectSerializer.deserialize(date, subType, format));
}
return transformedData;
} else if (type === "Date") {
return new Date(data);
} else {
if (enumsMap.has(type)) {// is Enum
return data;
}
if (!typeMap[type]) { // dont know the type
return data;
}
let instance = new typeMap[type]();
let attributeTypes = typeMap[type].getAttributeTypeMap();
for (let index in attributeTypes) {
let attributeType = attributeTypes[index];
instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type, attributeType.format);
}
return instance;
}
}
}

View File

@ -0,0 +1,78 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* An order for a pets from the pet store
*/
export class Order {
'id'?: number;
'petId'?: number;
'quantity'?: number;
'shipDate'?: Date;
/**
* Order Status
*/
'status'?: OrderStatusEnum;
'complete'?: boolean;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{
"name": "id",
"baseName": "id",
"type": "number",
"format": "int64"
},
{
"name": "petId",
"baseName": "petId",
"type": "number",
"format": "int64"
},
{
"name": "quantity",
"baseName": "quantity",
"type": "number",
"format": "int32"
},
{
"name": "shipDate",
"baseName": "shipDate",
"type": "Date",
"format": "date-time"
},
{
"name": "status",
"baseName": "status",
"type": "OrderStatusEnum",
"format": ""
},
{
"name": "complete",
"baseName": "complete",
"type": "boolean",
"format": ""
} ];
static getAttributeTypeMap() {
return Order.attributeTypeMap;
}
public constructor() {
}
}
export type OrderStatusEnum = "placed" | "approved" | "delivered" ;

View File

@ -0,0 +1,80 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Category } from './Category';
import { Tag } from './Tag';
/**
* A pet for sale in the pet store
*/
export class Pet {
'id'?: number;
'category'?: Category;
'name': string;
'photoUrls': Array<string>;
'tags'?: Array<Tag>;
/**
* pet status in the store
*/
'status'?: PetStatusEnum;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{
"name": "id",
"baseName": "id",
"type": "number",
"format": "int64"
},
{
"name": "category",
"baseName": "category",
"type": "Category",
"format": ""
},
{
"name": "name",
"baseName": "name",
"type": "string",
"format": ""
},
{
"name": "photoUrls",
"baseName": "photoUrls",
"type": "Array<string>",
"format": ""
},
{
"name": "tags",
"baseName": "tags",
"type": "Array<Tag>",
"format": ""
},
{
"name": "status",
"baseName": "status",
"type": "PetStatusEnum",
"format": ""
} ];
static getAttributeTypeMap() {
return Pet.attributeTypeMap;
}
public constructor() {
}
}
export type PetStatusEnum = "available" | "pending" | "sold" ;

View File

@ -0,0 +1,44 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A tag for a pet
*/
export class Tag {
'id'?: number;
'name'?: string;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{
"name": "id",
"baseName": "id",
"type": "number",
"format": "int64"
},
{
"name": "name",
"baseName": "name",
"type": "string",
"format": ""
} ];
static getAttributeTypeMap() {
return Tag.attributeTypeMap;
}
public constructor() {
}
}

View File

@ -0,0 +1,89 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A User who is purchasing from the pet store
*/
export class User {
'id'?: number;
'username'?: string;
'firstName'?: string;
'lastName'?: string;
'email'?: string;
'password'?: string;
'phone'?: string;
/**
* User Status
*/
'userStatus'?: number;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [
{
"name": "id",
"baseName": "id",
"type": "number",
"format": "int64"
},
{
"name": "username",
"baseName": "username",
"type": "string",
"format": ""
},
{
"name": "firstName",
"baseName": "firstName",
"type": "string",
"format": ""
},
{
"name": "lastName",
"baseName": "lastName",
"type": "string",
"format": ""
},
{
"name": "email",
"baseName": "email",
"type": "string",
"format": ""
},
{
"name": "password",
"baseName": "password",
"type": "string",
"format": ""
},
{
"name": "phone",
"baseName": "phone",
"type": "string",
"format": ""
},
{
"name": "userStatus",
"baseName": "userStatus",
"type": "number",
"format": "int32"
} ];
static getAttributeTypeMap() {
return User.attributeTypeMap;
}
public constructor() {
}
}

View File

@ -0,0 +1,6 @@
export * from './ApiResponse'
export * from './Category'
export * from './Order'
export * from './Pet'
export * from './Tag'
export * from './User'

View File

@ -0,0 +1,61 @@
{
"name": "ts-petstore-client",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@types/jquery": {
"version": "3.3.29",
"resolved": "https://registry.npmjs.org/@types/jquery/-/jquery-3.3.29.tgz",
"integrity": "sha512-FhJvBninYD36v3k6c+bVk1DSZwh7B5Dpb/Pyk3HKVsiohn0nhbefZZ+3JXbWQhFyt0MxSl2jRDdGQPHeOHFXrQ==",
"requires": {
"@types/sizzle": "*"
}
},
"@types/sizzle": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/@types/sizzle/-/sizzle-2.3.2.tgz",
"integrity": "sha512-7EJYyKTL7tFR8+gDbB6Wwz/arpGa0Mywk1TJbNzKzHtzbwVmY4HR9WqS5VV7dsBUKQmPNr192jHr/VpBluj/hg=="
},
"btoa": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/btoa/-/btoa-1.2.1.tgz",
"integrity": "sha512-SB4/MIGlsiVkMcHmT+pSmIPoNDoHg+7cMzmt3Uxt628MTz2487DKSqK/fuhFBrkuqrYv5UCEnACpF4dTFNKc/g=="
},
"es6-promise": {
"version": "4.2.6",
"resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.6.tgz",
"integrity": "sha512-aRVgGdnmW2OiySVPUC9e6m+plolMAJKjZnQlCwNSuK5yQ0JN61DZSO1X1Ufd1foqWRAlig0rhduTCHe7sVtK5Q=="
},
"jquery": {
"version": "3.4.1",
"resolved": "https://registry.npmjs.org/jquery/-/jquery-3.4.1.tgz",
"integrity": "sha512-36+AdBzCL+y6qjw5Tx7HgzeGCzC81MDDgaUP8ld2zhx58HdqXGoBd+tHdrBMiyjGQs0Hxs/MLZTu/eHNJJuWPw=="
},
"querystringify": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.1.1.tgz",
"integrity": "sha512-w7fLxIRCRT7U8Qu53jQnJyPkYZIaR4n5151KMfcJlO/A9397Wxb1amJvROTK6TOnp7PfoAmg/qXiNHI+08jRfA=="
},
"requires-port": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
"integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8="
},
"typescript": {
"version": "2.9.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-2.9.2.tgz",
"integrity": "sha512-Gr4p6nFNaoufRIY4NMdpQRNmgxVIGMs4Fcu/ujdYk3nAZqk7supzBE9idmvfZIlH/Cuj//dvi+019qEue9lV0w==",
"dev": true
},
"url-parse": {
"version": "1.4.7",
"resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.4.7.tgz",
"integrity": "sha512-d3uaVyzDB9tQoSXFvuSUNFibTd9zxd2bkVrDRvF5TmvWWQwqE4lgYJ5m+x1DbecWkw+LK4RNl2CU1hHuOKPVlg==",
"requires": {
"querystringify": "^2.1.1",
"requires-port": "^1.0.0"
}
}
}
}

View File

@ -0,0 +1,29 @@
{
"name": "ts-petstore-client",
"version": "1.0.0",
"description": "OpenAPI client for ts-petstore-client",
"author": "OpenAPI-Generator Contributors",
"keywords": [
"fetch",
"typescript",
"openapi-client",
"openapi-generator"
],
"license": "Unlicense",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"scripts": {
"build": "tsc",
"prepublishOnly": "npm run build"
},
"dependencies": {
"@types/jquery": "^3.3.29",
"jquery": "^3.4.1",
"btoa": "^1.2.1",
"es6-promise": "^4.2.4",
"url-parse": "^1.4.3"
},
"devDependencies": {
"typescript": "^2.9.2"
}
}

View File

@ -0,0 +1,60 @@
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools</groupId>
<artifactId>TypeScriptBuildPetstoreClientSample</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>TS Default Petstore Client</name>
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>npm-install</id>
<phase>pre-integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>install</argument>
</arguments>
</configuration>
</execution>
<execution>
<id>npm-build</id>
<phase>pre-integration-test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>npm</executable>
<arguments>
<argument>run</argument>
<argument>build</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,27 @@
export class Observable<T> {
constructor(private promise: Promise<T>) {}
toPromise() {
return this.promise;
}
pipe<S>(callback: (value: T) => S | Promise<S>): Observable<S> {
return new Observable(this.promise.then(callback));
}
}
export function from<T>(promise: Promise<any>) {
return new Observable(promise);
}
export function of<T>(value: T) {
return new Observable<T>(Promise.resolve(value));
}
export function mergeMap<T, S>(callback: (value: T) => Observable<S>) {
return (value: T) => callback(value).toPromise();
}
export function map(callback: any) {
return callback;
}

View File

@ -0,0 +1,55 @@
import {RequestContext, HttpMethod} from './http/http';
/**
*
* Represents the configuration of a server including its
* url template and variable configuration based on the url.
*
*/
export class ServerConfiguration<T> {
public constructor(private url: string, private variableConfiguration: T) {
}
/**
* Sets the value of the variables of this server.
*
* @param variableConfiguration a partial variable configuration for the variables contained in the url
*/
public setVariables(variableConfiguration: Partial<T>) {
for (const key in variableConfiguration) {
const val = variableConfiguration[key]
// We know that val isn't undefined here - hopefully
if (val !== undefined) {
this.variableConfiguration[key] = val as T[Extract<keyof T, string>];
}
}
}
public getConfiguration(): T {
return this.variableConfiguration
}
private getUrl() {
let replacedUrl = this.url;
for (const key in this.variableConfiguration) {
var re = new RegExp("{" + key + "}","g");
replacedUrl = replacedUrl.replace(re, this.variableConfiguration[key].toString());
}
return replacedUrl
}
/**
* Creates a new request context for this server using the url with variables
* replaced with their respective values and the endpoint of the request appended.
*
* @param endpoint the endpoint to be queried on the server
* @param httpMethod httpMethod to be used
*
*/
public makeRequestContext(endpoint: string, httpMethod: HttpMethod): RequestContext {
return new RequestContext(this.getUrl() + endpoint, httpMethod);
}
}
export const server1 = new ServerConfiguration<{ }>("http://petstore.swagger.io/v2", { })

View File

@ -0,0 +1,29 @@
{
"compilerOptions": {
"strict": true,
/* Basic Options */
"target": "es5",
"module": "commonjs",
"declaration": true,
/* Additional Checks */
"noUnusedLocals": false, /* Report errors on unused locals. */ // TODO: reenable (unused imports!)
"noUnusedParameters": false, /* Report errors on unused parameters. */ // TODO: set to true again
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
"noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
"removeComments": true,
"sourceMap": true,
"outDir": "./dist",
"noLib": false,
"lib": [ "es6", "dom" ]
},
"exclude": [
"dist",
"node_modules"
],
"filesGlob": [
"./**/*.ts",
]
}

Some files were not shown because too many files have changed in this diff Show More