From 7c52708d1438d9c4c0b4b6864c6d0f3c1cb349cb Mon Sep 17 00:00:00 2001 From: David Gamero Date: Tue, 25 Jan 2022 13:20:11 -0500 Subject: [PATCH 1/8] add custom agent support --- .../src/main/resources/typescript/http/http.mustache | 11 +++++++++++ .../typescript/http/isomorphic-fetch.mustache | 1 + 2 files changed, 12 insertions(+) diff --git a/modules/openapi-generator/src/main/resources/typescript/http/http.mustache b/modules/openapi-generator/src/main/resources/typescript/http/http.mustache index 2f71d86109f2..2b051b7c118d 100644 --- a/modules/openapi-generator/src/main/resources/typescript/http/http.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/http/http.mustache @@ -13,6 +13,8 @@ import * as URLParse from "url-parse"; {{/deno}} {{/platforms}} import { Observable, from } from {{#useRxJS}}'rxjs'{{/useRxJS}}{{^useRxJS}}'../rxjsStub{{extensionForDeno}}'{{/useRxJS}}; +import * as http from 'http'; +import * as https from 'https'; {{#platforms}} {{^deno}} @@ -113,6 +115,7 @@ export class RequestContext { private headers: { [key: string]: string } = {}; private body: RequestBody = undefined; private url: URLParse; + private agent: http.Agent | https.Agent | undefined = undefined; /** * Creates the request context using a http method and request resource url @@ -185,6 +188,14 @@ export class RequestContext { public setHeaderParam(key: string, value: string): void { this.headers[key] = value; } + + public setAgent(agent: http.Agent | https.Agent) { + this.agent = agent; + } + + public getAgent(): http.Agent | https.Agent | undefined { + return this.agent; + } } export interface ResponseBody { diff --git a/modules/openapi-generator/src/main/resources/typescript/http/isomorphic-fetch.mustache b/modules/openapi-generator/src/main/resources/typescript/http/isomorphic-fetch.mustache index 7646836694b3..59c5805a42b4 100644 --- a/modules/openapi-generator/src/main/resources/typescript/http/isomorphic-fetch.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/http/isomorphic-fetch.mustache @@ -19,6 +19,7 @@ export class IsomorphicFetchHttpLibrary implements HttpLibrary { method: method, body: body as any, headers: request.getHeaders(), + agent: request.getAgent(), {{#platforms}} {{#browser}} credentials: "same-origin" From 105461b14c36ac5887d28806548cec092d9e1731 Mon Sep 17 00:00:00 2001 From: David Gamero Date: Tue, 25 Jan 2022 13:26:35 -0500 Subject: [PATCH 2/8] samples --- .../perl/lib/WWW/OpenAPIClient/Object/Foo.pm | 183 ------ .../php-dt/src/App/DTO/Collection25.php | 16 - .../lib/Model/AdditionalPropertiesClass.php | 350 ------------ .../python/dynamic_servers/api/usage_api.py | 316 ----------- .../schema/petstore/mysql/mysql_schema.sql | 534 ------------------ .../src/App/DTO/Collection3.php | 14 - .../src/openapi_server/models/tag.py | 26 - 7 files changed, 1439 deletions(-) diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Foo.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Foo.pm index e400a15003bd..e69de29bb2d1 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Foo.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Foo.pm @@ -1,183 +0,0 @@ -=begin comment - -OpenAPI Petstore - -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - -The version of the OpenAPI document: 1.0.0 - -Generated by: https://openapi-generator.tech - -=end comment - -=cut - -# -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# Do not edit the class manually. -# Ref: https://openapi-generator.tech -# -package WWW::OpenAPIClient::Object::Foo; - -require 5.6.0; -use strict; -use warnings; -use utf8; -use JSON qw(decode_json); -use Data::Dumper; -use Module::Runtime qw(use_module); -use Log::Any qw($log); -use Date::Parse; -use DateTime; - - -use base ("Class::Accessor", "Class::Data::Inheritable"); - -# -# -# -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. -# REF: https://openapi-generator.tech -# - -=begin comment - -OpenAPI Petstore - -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - -The version of the OpenAPI document: 1.0.0 - -Generated by: https://openapi-generator.tech - -=end comment - -=cut - -# -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -# Do not edit the class manually. -# Ref: https://openapi-generator.tech -# -__PACKAGE__->mk_classdata('attribute_map' => {}); -__PACKAGE__->mk_classdata('openapi_types' => {}); -__PACKAGE__->mk_classdata('method_documentation' => {}); -__PACKAGE__->mk_classdata('class_documentation' => {}); - -# new plain object -sub new { - my ($class, %args) = @_; - - my $self = bless {}, $class; - - $self->init(%args); - - return $self; -} - -# initialize the object -sub init -{ - my ($self, %args) = @_; - - foreach my $attribute (keys %{$self->attribute_map}) { - my $args_key = $self->attribute_map->{$attribute}; - $self->$attribute( $args{ $args_key } ); - } -} - -# return perl hash -sub to_hash { - my $self = shift; - my $_hash = decode_json(JSON->new->convert_blessed->encode($self)); - - return $_hash; -} - -# used by JSON for serialization -sub TO_JSON { - my $self = shift; - my $_data = {}; - foreach my $_key (keys %{$self->attribute_map}) { - if (defined $self->{$_key}) { - $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; - } - } - - return $_data; -} - -# from Perl hashref -sub from_hash { - my ($self, $hash) = @_; - - # loop through attributes and use openapi_types to deserialize the data - while ( my ($_key, $_type) = each %{$self->openapi_types} ) { - my $_json_attribute = $self->attribute_map->{$_key}; - if ($_type =~ /^array\[(.+)\]$/i) { # array - my $_subclass = $1; - my @_array = (); - foreach my $_element (@{$hash->{$_json_attribute}}) { - push @_array, $self->_deserialize($_subclass, $_element); - } - $self->{$_key} = \@_array; - } elsif ($_type =~ /^hash\[string,(.+)\]$/i) { # hash - my $_subclass = $1; - my %_hash = (); - while (my($_key, $_element) = each %{$hash->{$_json_attribute}}) { - $_hash{$_key} = $self->_deserialize($_subclass, $_element); - } - $self->{$_key} = \%_hash; - } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime - $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); - } else { - $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); - } - } - - return $self; -} - -# deserialize non-array data -sub _deserialize { - my ($self, $type, $data) = @_; - $log->debugf("deserializing %s with %s",Dumper($data), $type); - - if ($type eq 'DateTime') { - return DateTime->from_epoch(epoch => str2time($data)); - } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { - return $data; - } else { # hash(model) - my $_instance = eval "WWW::OpenAPIClient::Object::$type->new()"; - return $_instance->from_hash($data); - } -} - - -__PACKAGE__->class_documentation({description => '', - class => 'Foo', - required => [], # TODO -} ); - -__PACKAGE__->method_documentation({ - 'bar' => { - datatype => 'string', - base_name => 'bar', - description => '', - format => '', - read_only => '', - }, -}); - -__PACKAGE__->openapi_types( { - 'bar' => 'string' -} ); - -__PACKAGE__->attribute_map( { - 'bar' => 'bar' -} ); - -__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); - - -1; diff --git a/samples/client/petstore/php-dt/src/App/DTO/Collection25.php b/samples/client/petstore/php-dt/src/App/DTO/Collection25.php index 8cc9f56843a8..e69de29bb2d1 100644 --- a/samples/client/petstore/php-dt/src/App/DTO/Collection25.php +++ b/samples/client/petstore/php-dt/src/App/DTO/Collection25.php @@ -1,16 +0,0 @@ - - * @template TKey int|null - * @template TValue mixed|null - */ -class AdditionalPropertiesClass implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'AdditionalPropertiesClass'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'map_property' => 'array', - 'map_of_map_property' => 'array>' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'map_property' => null, - 'map_of_map_property' => null - ]; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @return array - */ - public static function openAPITypes() - { - return self::$openAPITypes; - } - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @return array - */ - public static function openAPIFormats() - { - return self::$openAPIFormats; - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'map_property' => 'map_property', - 'map_of_map_property' => 'map_of_map_property' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'map_property' => 'setMapProperty', - 'map_of_map_property' => 'setMapOfMapProperty' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'map_property' => 'getMapProperty', - 'map_of_map_property' => 'getMapOfMapProperty' - ]; - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @return array - */ - public static function attributeMap() - { - return self::$attributeMap; - } - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @return array - */ - public static function setters() - { - return self::$setters; - } - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @return array - */ - public static function getters() - { - return self::$getters; - } - - /** - * The original name of the model. - * - * @return string - */ - public function getModelName() - { - return self::$openAPIModelName; - } - - - /** - * Associative array for storing property values - * - * @var mixed[] - */ - protected $container = []; - - /** - * Constructor - * - * @param mixed[] $data Associated array of property values - * initializing the model - */ - public function __construct(array $data = null) - { - $this->container['map_property'] = $data['map_property'] ?? null; - $this->container['map_of_map_property'] = $data['map_of_map_property'] ?? null; - } - - /** - * Show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalidProperties = []; - - return $invalidProperties; - } - - /** - * Validate all the properties in the model - * return true if all passed - * - * @return bool True if all properties are valid - */ - public function valid() - { - return count($this->listInvalidProperties()) === 0; - } - - - /** - * Gets map_property - * - * @return array|null - */ - public function getMapProperty() - { - return $this->container['map_property']; - } - - /** - * Sets map_property - * - * @param array|null $map_property map_property - * - * @return self - */ - public function setMapProperty($map_property) - { - $this->container['map_property'] = $map_property; - - return $this; - } - - /** - * Gets map_of_map_property - * - * @return array>|null - */ - public function getMapOfMapProperty() - { - return $this->container['map_of_map_property']; - } - - /** - * Sets map_of_map_property - * - * @param array>|null $map_of_map_property map_of_map_property - * - * @return self - */ - public function setMapOfMapProperty($map_of_map_property) - { - $this->container['map_of_map_property'] = $map_of_map_property; - - return $this; - } - /** - * Returns true if offset exists. False otherwise. - * - * @param integer $offset Offset - * - * @return boolean - */ - public function offsetExists($offset) - { - return isset($this->container[$offset]); - } - - /** - * Gets offset. - * - * @param integer $offset Offset - * - * @return mixed|null - */ - public function offsetGet($offset) - { - return $this->container[$offset] ?? null; - } - - /** - * Sets value based on offset. - * - * @param int|null $offset Offset - * @param mixed $value Value to be set - * - * @return void - */ - public function offsetSet($offset, $value) - { - if (is_null($offset)) { - $this->container[] = $value; - } else { - $this->container[$offset] = $value; - } - } - - /** - * Unsets offset. - * - * @param integer $offset Offset - * - * @return void - */ - public function offsetUnset($offset) - { - unset($this->container[$offset]); - } - - /** - * Serializes the object to a value that can be serialized natively by json_encode(). - * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php - * - * @return mixed Returns data which can be serialized by json_encode(), which is a value - * of any type other than a resource. - */ - public function jsonSerialize() - { - return ObjectSerializer::sanitizeForSerialization($this); - } - - /** - * Gets the string presentation of the object - * - * @return string - */ - public function __toString() - { - return json_encode( - ObjectSerializer::sanitizeForSerialization($this), - JSON_PRETTY_PRINT - ); - } - - /** - * Gets a header-safe presentation of the object - * - * @return string - */ - public function toHeaderValue() - { - return json_encode(ObjectSerializer::sanitizeForSerialization($this)); - } -} - - diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api/usage_api.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api/usage_api.py index f71f533ceeca..e69de29bb2d1 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api/usage_api.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api/usage_api.py @@ -1,316 +0,0 @@ -""" - OpenAPI Extension with dynamic servers - - This specification shows how to use dynamic servers. # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from dynamic_servers.api_client import ApiClient, Endpoint as _Endpoint -from dynamic_servers.model_utils import ( # noqa: F401 - check_allowed_values, - check_validations, - date, - datetime, - file_type, - none_type, - validate_and_convert_types -) - - -class UsageApi(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient() - self.api_client = api_client - self.custom_server_endpoint = _Endpoint( - settings={ - 'response_type': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), - 'auth': [], - 'endpoint_path': '/custom', - 'operation_id': 'custom_server', - 'http_method': 'GET', - 'servers': [ - { - 'url': "https://{server}.swagger.io:{port}/v2", - 'description': "No description provided", - 'variables': { - 'server': { - 'description': "No description provided", - 'default_value': "custom-petstore", - 'enum_values': [ - "custom-petstore", - "custom-qa-petstore", - "custom-dev-petstore" - ] - }, - 'port': { - 'description': "No description provided", - 'default_value': "8080", - 'enum_values': [ - "80", - "8080" - ] - } - } - }, - { - 'url': "https://localhost:8081/{version}", - 'description': "The local custom server", - 'variables': { - 'version': { - 'description': "No description provided", - 'default_value': "v2", - 'enum_values': [ - "v1", - "v2", - "v3" - ] - } - } - }, - { - 'url': "https://third.example.com/{prefix}", - 'description': "The local custom server", - 'variables': { - 'prefix': { - 'description': "No description provided", - 'default_value': "custom", - } - } - }, - ] - }, - params_map={ - 'all': [ - ], - 'required': [], - 'nullable': [ - ], - 'enum': [ - ], - 'validation': [ - ] - }, - root_map={ - 'validations': { - }, - 'allowed_values': { - }, - 'openapi_types': { - }, - 'attribute_map': { - }, - 'location_map': { - }, - 'collection_format_map': { - } - }, - headers_map={ - 'accept': [ - 'application/json' - ], - 'content_type': [], - }, - api_client=api_client - ) - self.default_server_endpoint = _Endpoint( - settings={ - 'response_type': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), - 'auth': [], - 'endpoint_path': '/default', - 'operation_id': 'default_server', - 'http_method': 'GET', - 'servers': None, - }, - params_map={ - 'all': [ - ], - 'required': [], - 'nullable': [ - ], - 'enum': [ - ], - 'validation': [ - ] - }, - root_map={ - 'validations': { - }, - 'allowed_values': { - }, - 'openapi_types': { - }, - 'attribute_map': { - }, - 'location_map': { - }, - 'collection_format_map': { - } - }, - headers_map={ - 'accept': [ - 'application/json' - ], - 'content_type': [], - }, - api_client=api_client - ) - - def custom_server( - self, - **kwargs - ): - """Use custom server # noqa: E501 - - Use custom server # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.custom_server(async_req=True) - >>> result = thread.get() - - - Keyword Args: - _return_http_data_only (bool): response data without head status - code and headers. Default is True. - _preload_content (bool): if False, the urllib3.HTTPResponse object - will be returned without reading/decoding response data. - Default is True. - _request_timeout (int/float/tuple): timeout setting for this request. If - one number provided, it will be total request timeout. It can also - be a pair (tuple) of (connection, read) timeouts. - Default is None. - _check_input_type (bool): specifies if type checking - should be done one the data sent to the server. - Default is True. - _check_return_type (bool): specifies if type checking - should be done one the data received from the server. - Default is True. - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _content_type (str/None): force body content-type. - Default is None and content-type will be predicted by allowed - content-types and body. - _host_index (int/None): specifies the index of the server - that we want to use. - Default is read from the configuration. - async_req (bool): execute request asynchronously - - Returns: - {str: (bool, date, datetime, dict, float, int, list, str, none_type)} - If the method is called asynchronously, returns the request - thread. - """ - kwargs['async_req'] = kwargs.get( - 'async_req', False - ) - kwargs['_return_http_data_only'] = kwargs.get( - '_return_http_data_only', True - ) - kwargs['_preload_content'] = kwargs.get( - '_preload_content', True - ) - kwargs['_request_timeout'] = kwargs.get( - '_request_timeout', None - ) - kwargs['_check_input_type'] = kwargs.get( - '_check_input_type', True - ) - kwargs['_check_return_type'] = kwargs.get( - '_check_return_type', True - ) - kwargs['_spec_property_naming'] = kwargs.get( - '_spec_property_naming', False - ) - kwargs['_content_type'] = kwargs.get( - '_content_type') - kwargs['_host_index'] = kwargs.get('_host_index') - return self.custom_server_endpoint.call_with_http_info(**kwargs) - - def default_server( - self, - **kwargs - ): - """Use default server # noqa: E501 - - Use default server # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.default_server(async_req=True) - >>> result = thread.get() - - - Keyword Args: - _return_http_data_only (bool): response data without head status - code and headers. Default is True. - _preload_content (bool): if False, the urllib3.HTTPResponse object - will be returned without reading/decoding response data. - Default is True. - _request_timeout (int/float/tuple): timeout setting for this request. If - one number provided, it will be total request timeout. It can also - be a pair (tuple) of (connection, read) timeouts. - Default is None. - _check_input_type (bool): specifies if type checking - should be done one the data sent to the server. - Default is True. - _check_return_type (bool): specifies if type checking - should be done one the data received from the server. - Default is True. - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _content_type (str/None): force body content-type. - Default is None and content-type will be predicted by allowed - content-types and body. - _host_index (int/None): specifies the index of the server - that we want to use. - Default is read from the configuration. - async_req (bool): execute request asynchronously - - Returns: - {str: (bool, date, datetime, dict, float, int, list, str, none_type)} - If the method is called asynchronously, returns the request - thread. - """ - kwargs['async_req'] = kwargs.get( - 'async_req', False - ) - kwargs['_return_http_data_only'] = kwargs.get( - '_return_http_data_only', True - ) - kwargs['_preload_content'] = kwargs.get( - '_preload_content', True - ) - kwargs['_request_timeout'] = kwargs.get( - '_request_timeout', None - ) - kwargs['_check_input_type'] = kwargs.get( - '_check_input_type', True - ) - kwargs['_check_return_type'] = kwargs.get( - '_check_return_type', True - ) - kwargs['_spec_property_naming'] = kwargs.get( - '_spec_property_naming', False - ) - kwargs['_content_type'] = kwargs.get( - '_content_type') - kwargs['_host_index'] = kwargs.get('_host_index') - return self.default_server_endpoint.call_with_http_info(**kwargs) - diff --git a/samples/schema/petstore/mysql/mysql_schema.sql b/samples/schema/petstore/mysql/mysql_schema.sql index a189b16c3ab5..e69de29bb2d1 100644 --- a/samples/schema/petstore/mysql/mysql_schema.sql +++ b/samples/schema/petstore/mysql/mysql_schema.sql @@ -1,534 +0,0 @@ -/* SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; */ -/* SET AUTOCOMMIT = 0; */ -/* START TRANSACTION; */ -/* SET time_zone = "+00:00"; */ - --- -------------------------------------------------------- - --- --- Table structure for table `200_response` generated from model '200Underscoreresponse' --- Model for testing model name starting with number --- - -CREATE TABLE IF NOT EXISTS `200_response` ( - `name` INT DEFAULT NULL, - `class` TEXT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Model for testing model name starting with number'; - --- --- Table structure for table `AdditionalPropertiesClass` generated from model 'AdditionalPropertiesClass' --- - -CREATE TABLE IF NOT EXISTS `AdditionalPropertiesClass` ( - `map_property` JSON DEFAULT NULL, - `map_of_map_property` JSON DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `Animal` generated from model 'Animal' --- - -CREATE TABLE IF NOT EXISTS `Animal` ( - `className` TEXT NOT NULL, - `color` TEXT -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `ApiResponse` generated from model 'ApiResponse' --- - -CREATE TABLE IF NOT EXISTS `ApiResponse` ( - `code` INT DEFAULT NULL, - `type` TEXT DEFAULT NULL, - `message` TEXT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `ArrayOfArrayOfNumberOnly` generated from model 'ArrayOfArrayOfNumberOnly' --- - -CREATE TABLE IF NOT EXISTS `ArrayOfArrayOfNumberOnly` ( - `ArrayArrayNumber` JSON DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `ArrayOfNumberOnly` generated from model 'ArrayOfNumberOnly' --- - -CREATE TABLE IF NOT EXISTS `ArrayOfNumberOnly` ( - `ArrayNumber` JSON DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `ArrayTest` generated from model 'ArrayTest' --- - -CREATE TABLE IF NOT EXISTS `ArrayTest` ( - `array_of_string` JSON DEFAULT NULL, - `array_array_of_integer` JSON DEFAULT NULL, - `array_array_of_model` JSON DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `Capitalization` generated from model 'Capitalization' --- - -CREATE TABLE IF NOT EXISTS `Capitalization` ( - `smallCamel` TEXT DEFAULT NULL, - `CapitalCamel` TEXT DEFAULT NULL, - `small_Snake` TEXT DEFAULT NULL, - `Capital_Snake` TEXT DEFAULT NULL, - `SCA_ETH_Flow_Points` TEXT DEFAULT NULL, - `ATT_NAME` TEXT DEFAULT NULL COMMENT 'Name of the pet ' -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `Cat` generated from model 'Cat' --- - -CREATE TABLE IF NOT EXISTS `Cat` ( - `className` TEXT NOT NULL, - `color` TEXT, - `declawed` TINYINT(1) DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `Cat_allOf` generated from model 'CatUnderscoreallOf' --- - -CREATE TABLE IF NOT EXISTS `Cat_allOf` ( - `declawed` TINYINT(1) DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `Category` generated from model 'Category' --- - -CREATE TABLE IF NOT EXISTS `Category` ( - `id` BIGINT DEFAULT NULL, - `name` TEXT NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `ClassModel` generated from model 'ClassModel' --- Model for testing model with \"_class\" property --- - -CREATE TABLE IF NOT EXISTS `ClassModel` ( - `_class` TEXT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Model for testing model with \"_class\" property'; - --- --- Table structure for table `Client` generated from model 'Client' --- - -CREATE TABLE IF NOT EXISTS `Client` ( - `client` TEXT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `DeprecatedObject` generated from model 'DeprecatedObject' --- - -CREATE TABLE IF NOT EXISTS `DeprecatedObject` ( - `name` TEXT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `Dog` generated from model 'Dog' --- - -CREATE TABLE IF NOT EXISTS `Dog` ( - `className` TEXT NOT NULL, - `color` TEXT, - `breed` TEXT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `Dog_allOf` generated from model 'DogUnderscoreallOf' --- - -CREATE TABLE IF NOT EXISTS `Dog_allOf` ( - `breed` TEXT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `EnumArrays` generated from model 'EnumArrays' --- - -CREATE TABLE IF NOT EXISTS `EnumArrays` ( - `just_symbol` ENUM('>=', '$') DEFAULT NULL, - `array_enum` JSON DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `Enum_Test` generated from model 'EnumUnderscoreTest' --- - -CREATE TABLE IF NOT EXISTS `Enum_Test` ( - `enum_string` ENUM('UPPER', 'lower', '') DEFAULT NULL, - `enum_string_required` ENUM('UPPER', 'lower', '') NOT NULL, - `enum_integer` ENUM('1', '-1') DEFAULT NULL, - `enum_number` ENUM('1.1', '-1.2') DEFAULT NULL, - `outerEnum` TEXT DEFAULT NULL, - `outerEnumInteger` TEXT DEFAULT NULL, - `outerEnumDefaultValue` TEXT DEFAULT NULL, - `outerEnumIntegerDefaultValue` TEXT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `File` generated from model 'File' --- Must be named `File` for test. --- - -CREATE TABLE IF NOT EXISTS `File` ( - `sourceURI` TEXT DEFAULT NULL COMMENT 'Test capitalization' -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Must be named `File` for test.'; - --- --- Table structure for table `FileSchemaTestClass` generated from model 'FileSchemaTestClass' --- - -CREATE TABLE IF NOT EXISTS `FileSchemaTestClass` ( - `file` TEXT DEFAULT NULL, - `files` JSON DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `Foo` generated from model 'Foo' --- - -CREATE TABLE IF NOT EXISTS `Foo` ( - `bar` TEXT -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `format_test` generated from model 'formatUnderscoretest' --- - -CREATE TABLE IF NOT EXISTS `format_test` ( - `integer` TINYINT UNSIGNED DEFAULT NULL, - `int32` TINYINT UNSIGNED DEFAULT NULL, - `int64` BIGINT DEFAULT NULL, - `number` DECIMAL(20, 9) UNSIGNED NOT NULL, - `float` DECIMAL(20, 9) UNSIGNED DEFAULT NULL, - `double` DECIMAL(20, 9) UNSIGNED DEFAULT NULL, - `decimal` TEXT DEFAULT NULL, - `string` TEXT DEFAULT NULL, - `byte` MEDIUMBLOB NOT NULL, - `binary` MEDIUMBLOB DEFAULT NULL, - `date` DATE NOT NULL, - `dateTime` DATETIME DEFAULT NULL, - `uuid` TEXT DEFAULT NULL, - `password` VARCHAR(64) NOT NULL, - `pattern_with_digits` TEXT DEFAULT NULL COMMENT 'A string that is a 10 digit number. Can have leading zeros.', - `pattern_with_digits_and_delimiter` TEXT DEFAULT NULL COMMENT 'A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.' -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `hasOnlyReadOnly` generated from model 'hasOnlyReadOnly' --- - -CREATE TABLE IF NOT EXISTS `hasOnlyReadOnly` ( - `bar` TEXT DEFAULT NULL, - `foo` TEXT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `HealthCheckResult` generated from model 'HealthCheckResult' --- Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. --- - -CREATE TABLE IF NOT EXISTS `HealthCheckResult` ( - `NullableMessage` TEXT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model.'; - --- --- Table structure for table `inline_response_default` generated from model 'inlineUnderscoreresponseUnderscoredefault' --- - -CREATE TABLE IF NOT EXISTS `inline_response_default` ( - `string` TEXT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `List` generated from model 'List' --- - -CREATE TABLE IF NOT EXISTS `List` ( - `123-list` TEXT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `MapTest` generated from model 'MapTest' --- - -CREATE TABLE IF NOT EXISTS `MapTest` ( - `map_map_of_string` JSON DEFAULT NULL, - `map_of_enum_string` JSON DEFAULT NULL, - `direct_map` JSON DEFAULT NULL, - `indirect_map` JSON DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `MixedPropertiesAndAdditionalPropertiesClass` generated from model 'MixedPropertiesAndAdditionalPropertiesClass' --- - -CREATE TABLE IF NOT EXISTS `MixedPropertiesAndAdditionalPropertiesClass` ( - `uuid` TEXT DEFAULT NULL, - `dateTime` DATETIME DEFAULT NULL, - `map` JSON DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `Name` generated from model 'Name' --- Model for testing model name same as property name --- - -CREATE TABLE IF NOT EXISTS `Name` ( - `name` INT NOT NULL, - `snake_case` INT DEFAULT NULL, - `property` TEXT DEFAULT NULL, - `123Number` INT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Model for testing model name same as property name'; - --- --- Table structure for table `NullableClass` generated from model 'NullableClass' --- - -CREATE TABLE IF NOT EXISTS `NullableClass` ( - `integer_prop` INT DEFAULT NULL, - `number_prop` DECIMAL(20, 9) DEFAULT NULL, - `boolean_prop` TINYINT(1) DEFAULT NULL, - `string_prop` TEXT DEFAULT NULL, - `date_prop` DATE DEFAULT NULL, - `datetime_prop` DATETIME DEFAULT NULL, - `array_nullable_prop` JSON DEFAULT NULL, - `array_and_items_nullable_prop` JSON DEFAULT NULL, - `array_items_nullable` JSON DEFAULT NULL, - `object_nullable_prop` JSON DEFAULT NULL, - `object_and_items_nullable_prop` JSON DEFAULT NULL, - `object_items_nullable` JSON DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `NumberOnly` generated from model 'NumberOnly' --- - -CREATE TABLE IF NOT EXISTS `NumberOnly` ( - `JustNumber` DECIMAL(20, 9) DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `ObjectWithDeprecatedFields` generated from model 'ObjectWithDeprecatedFields' --- - -CREATE TABLE IF NOT EXISTS `ObjectWithDeprecatedFields` ( - `uuid` TEXT DEFAULT NULL, - `id` DECIMAL(20, 9) DEFAULT NULL, - `deprecatedRef` TEXT DEFAULT NULL, - `bars` JSON DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `Order` generated from model 'Order' --- - -CREATE TABLE IF NOT EXISTS `Order` ( - `id` BIGINT DEFAULT NULL, - `petId` BIGINT DEFAULT NULL, - `quantity` INT DEFAULT NULL, - `shipDate` DATETIME DEFAULT NULL, - `status` ENUM('placed', 'approved', 'delivered') DEFAULT NULL COMMENT 'Order Status', - `complete` TINYINT(1) DEFAULT false -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `OuterComposite` generated from model 'OuterComposite' --- - -CREATE TABLE IF NOT EXISTS `OuterComposite` ( - `my_number` DECIMAL(20, 9) DEFAULT NULL, - `my_string` TEXT DEFAULT NULL, - `my_boolean` TINYINT(1) DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `OuterObjectWithEnumProperty` generated from model 'OuterObjectWithEnumProperty' --- - -CREATE TABLE IF NOT EXISTS `OuterObjectWithEnumProperty` ( - `value` TEXT NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `Pet` generated from model 'Pet' --- - -CREATE TABLE IF NOT EXISTS `Pet` ( - `id` BIGINT DEFAULT NULL, - `category` TEXT DEFAULT NULL, - `name` TEXT NOT NULL, - `photoUrls` JSON NOT NULL, - `tags` JSON DEFAULT NULL, - `status` ENUM('available', 'pending', 'sold') DEFAULT NULL COMMENT 'pet status in the store' -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `ReadOnlyFirst` generated from model 'ReadOnlyFirst' --- - -CREATE TABLE IF NOT EXISTS `ReadOnlyFirst` ( - `bar` TEXT DEFAULT NULL, - `baz` TEXT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `Return` generated from model 'Return' --- Model for testing reserved words --- - -CREATE TABLE IF NOT EXISTS `Return` ( - `return` INT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Model for testing reserved words'; - --- --- Table structure for table `_special_model.name_` generated from model 'UnderscorespecialUnderscoremodelPeriodnameUnderscore' --- - -CREATE TABLE IF NOT EXISTS `_special_model.name_` ( - `$special[property.name]` BIGINT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `Tag` generated from model 'Tag' --- - -CREATE TABLE IF NOT EXISTS `Tag` ( - `id` BIGINT DEFAULT NULL, - `name` TEXT DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `User` generated from model 'User' --- - -CREATE TABLE IF NOT EXISTS `User` ( - `id` BIGINT DEFAULT NULL, - `username` TEXT DEFAULT NULL, - `firstName` TEXT DEFAULT NULL, - `lastName` TEXT DEFAULT NULL, - `email` TEXT DEFAULT NULL, - `password` TEXT DEFAULT NULL, - `phone` TEXT DEFAULT NULL, - `userStatus` INT DEFAULT NULL COMMENT 'User Status' -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - - --- --- OAuth2 framework tables --- Thanks to https://github.com/dsquier/oauth2-server-php-mysql repo --- - --- --- Table structure for table `oauth_clients` --- -CREATE TABLE IF NOT EXISTS `oauth_clients` ( - `client_id` VARCHAR(80) NOT NULL, - `client_secret` VARCHAR(80) DEFAULT NULL, - `redirect_uri` VARCHAR(2000) DEFAULT NULL, - `grant_types` VARCHAR(80) DEFAULT NULL, - `scope` VARCHAR(4000) DEFAULT NULL, - `user_id` VARCHAR(80) DEFAULT NULL, - PRIMARY KEY (`client_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `oauth_access_tokens` --- -CREATE TABLE IF NOT EXISTS `oauth_access_tokens` ( - `access_token` VARCHAR(40) NOT NULL, - `client_id` VARCHAR(80) DEFAULT NULL, - `user_id` VARCHAR(80) DEFAULT NULL, - `expires` TIMESTAMP NOT NULL, - `scope` VARCHAR(4000) DEFAULT NULL, - PRIMARY KEY (`access_token`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `oauth_authorization_codes` --- -CREATE TABLE IF NOT EXISTS `oauth_authorization_codes` ( - `authorization_code` VARCHAR(40) NOT NULL, - `client_id` VARCHAR(80) DEFAULT NULL, - `user_id` VARCHAR(80) DEFAULT NULL, - `redirect_uri` VARCHAR(2000) NOT NULL, - `expires` TIMESTAMP NOT NULL, - `scope` VARCHAR(4000) DEFAULT NULL, - `id_token` VARCHAR(1000) DEFAULT NULL, - PRIMARY KEY (`authorization_code`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `oauth_refresh_tokens` --- -CREATE TABLE IF NOT EXISTS `oauth_refresh_tokens` ( - `refresh_token` VARCHAR(40) NOT NULL, - `client_id` VARCHAR(80) DEFAULT NULL, - `user_id` VARCHAR(80) DEFAULT NULL, - `expires` TIMESTAMP on update CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - `scope` VARCHAR(4000) DEFAULT NULL, - PRIMARY KEY (`refresh_token`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `oauth_users` --- -CREATE TABLE IF NOT EXISTS `oauth_users` ( - `username` VARCHAR(80) DEFAULT NULL, - `password` VARCHAR(255) DEFAULT NULL, - `first_name` VARCHAR(80) DEFAULT NULL, - `last_name` VARCHAR(80) DEFAULT NULL, - `email` VARCHAR(2000) DEFAULT NULL, - `email_verified` TINYINT(1) DEFAULT NULL, - `scope` VARCHAR(4000) DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `oauth_scopes` --- -CREATE TABLE IF NOT EXISTS `oauth_scopes` ( - `scope` VARCHAR(80) NOT NULL, - `is_default` TINYINT(1) DEFAULT NULL, - PRIMARY KEY (`scope`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `oauth_jwt` --- -CREATE TABLE IF NOT EXISTS `oauth_jwt` ( - `client_id` VARCHAR(80) NOT NULL, - `subject` VARCHAR(80) DEFAULT NULL, - `public_key` VARCHAR(2000) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `oauth_jti` --- -CREATE TABLE IF NOT EXISTS `oauth_jti` ( - `issuer` VARCHAR(80) NOT NULL, - `subject` VARCHAR(80) DEFAULT NULL, - `audience` VARCHAR(80) DEFAULT NULL, - `expires` TIMESTAMP NOT NULL, - `jti` VARCHAR(2000) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - --- --- Table structure for table `oauth_public_keys` --- -CREATE TABLE IF NOT EXISTS `oauth_public_keys` ( - `client_id` VARCHAR(80) DEFAULT NULL, - `public_key` VARCHAR(2000) DEFAULT NULL, - `private_key` VARCHAR(2000) DEFAULT NULL, - `encryption_algorithm` VARCHAR(100) DEFAULT 'RS256' -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection3.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection3.php index 1833307cd7e6..e69de29bb2d1 100644 --- a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection3.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection3.php @@ -1,14 +0,0 @@ - \App\DTO\Tag::class])] -#[DTA\Validator("Collection", ["validators" => [ - ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] -]])] -class Collection3 extends \ArrayObject -{ -} diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py index 3e0b45cd787b..e69de29bb2d1 100644 --- a/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py @@ -1,26 +0,0 @@ -# coding: utf-8 - -from __future__ import annotations -from datetime import date, datetime # noqa: F401 - -import re # noqa: F401 -from typing import Any, Dict, List, Optional # noqa: F401 - -from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401 - - -class Tag(BaseModel): - """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - - Do not edit the class manually. - - Tag - a model defined in OpenAPI - - id: The id of this Tag [Optional]. - name: The name of this Tag [Optional]. - """ - - id: Optional[int] = None - name: Optional[str] = None - -Tag.update_forward_refs() From 60e458377850d21861d48951cce48f558267f88d Mon Sep 17 00:00:00 2001 From: David Gamero Date: Tue, 25 Jan 2022 13:34:18 -0500 Subject: [PATCH 3/8] more samples --- .../typescript/builds/composed-schemas/http/http.ts | 11 +++++++++++ .../builds/composed-schemas/http/isomorphic-fetch.ts | 1 + .../petstore/typescript/builds/default/http/http.ts | 11 +++++++++++ .../builds/default/http/isomorphic-fetch.ts | 1 + .../petstore/typescript/builds/deno/http/http.ts | 11 +++++++++++ .../typescript/builds/deno/http/isomorphic-fetch.ts | 1 + .../petstore/typescript/builds/inversify/http/http.ts | 11 +++++++++++ .../builds/inversify/http/isomorphic-fetch.ts | 1 + .../petstore/typescript/builds/jquery/http/http.ts | 11 +++++++++++ .../typescript/builds/object_params/http/http.ts | 11 +++++++++++ .../builds/object_params/http/isomorphic-fetch.ts | 1 + 11 files changed, 71 insertions(+) diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/http.ts index f19e206b19ff..473c679e5697 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/http.ts @@ -2,6 +2,8 @@ // @ts-ignore import * as URLParse from "url-parse"; import { Observable, from } from '../rxjsStub'; +import * as http from 'http'; +import * as https from 'https'; export * from './isomorphic-fetch'; @@ -44,6 +46,7 @@ export class RequestContext { private headers: { [key: string]: string } = {}; private body: RequestBody = undefined; private url: URLParse; + private agent: http.Agent | https.Agent | undefined = undefined; /** * Creates the request context using a http method and request resource url @@ -116,6 +119,14 @@ export class RequestContext { public setHeaderParam(key: string, value: string): void { this.headers[key] = value; } + + public setAgent(agent: http.Agent | https.Agent) { + this.agent = agent; + } + + public getAgent(): http.Agent | https.Agent | undefined { + return this.agent; + } } export interface ResponseBody { diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/isomorphic-fetch.ts b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/isomorphic-fetch.ts index 3af85f3d902c..80c114d36daf 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/isomorphic-fetch.ts +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/isomorphic-fetch.ts @@ -12,6 +12,7 @@ export class IsomorphicFetchHttpLibrary implements HttpLibrary { method: method, body: body as any, headers: request.getHeaders(), + agent: request.getAgent(), credentials: "same-origin" }).then((resp: any) => { const headers: { [name: string]: string } = {}; diff --git a/samples/openapi3/client/petstore/typescript/builds/default/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/default/http/http.ts index a623aef12789..d4e5df9191dc 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/http/http.ts @@ -5,6 +5,8 @@ import { URLSearchParams } from 'url'; // @ts-ignore import * as URLParse from "url-parse"; import { Observable, from } from '../rxjsStub'; +import * as http from 'http'; +import * as https from 'https'; export * from './isomorphic-fetch'; @@ -50,6 +52,7 @@ export class RequestContext { private headers: { [key: string]: string } = {}; private body: RequestBody = undefined; private url: URLParse; + private agent: http.Agent | https.Agent | undefined = undefined; /** * Creates the request context using a http method and request resource url @@ -122,6 +125,14 @@ export class RequestContext { public setHeaderParam(key: string, value: string): void { this.headers[key] = value; } + + public setAgent(agent: http.Agent | https.Agent) { + this.agent = agent; + } + + public getAgent(): http.Agent | https.Agent | undefined { + return this.agent; + } } export interface ResponseBody { diff --git a/samples/openapi3/client/petstore/typescript/builds/default/http/isomorphic-fetch.ts b/samples/openapi3/client/petstore/typescript/builds/default/http/isomorphic-fetch.ts index ed390df7ce10..26d267cfc063 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/http/isomorphic-fetch.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/http/isomorphic-fetch.ts @@ -12,6 +12,7 @@ export class IsomorphicFetchHttpLibrary implements HttpLibrary { method: method, body: body as any, headers: request.getHeaders(), + agent: request.getAgent(), }).then((resp: any) => { const headers: { [name: string]: string } = {}; resp.headers.forEach((value: string, name: string) => { diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/deno/http/http.ts index 139149cec973..46539f64ef44 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/http/http.ts @@ -1,4 +1,6 @@ import { Observable, from } from '../rxjsStub.ts'; +import * as http from 'http'; +import * as https from 'https'; /** @@ -73,6 +75,7 @@ export class RequestContext { private headers: { [key: string]: string } = {}; private body: RequestBody = undefined; private url: URLParse; + private agent: http.Agent | https.Agent | undefined = undefined; /** * Creates the request context using a http method and request resource url @@ -145,6 +148,14 @@ export class RequestContext { public setHeaderParam(key: string, value: string): void { this.headers[key] = value; } + + public setAgent(agent: http.Agent | https.Agent) { + this.agent = agent; + } + + public getAgent(): http.Agent | https.Agent | undefined { + return this.agent; + } } export interface ResponseBody { diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/http/isomorphic-fetch.ts b/samples/openapi3/client/petstore/typescript/builds/deno/http/isomorphic-fetch.ts index a7521351e065..450533765e60 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/http/isomorphic-fetch.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/http/isomorphic-fetch.ts @@ -11,6 +11,7 @@ export class IsomorphicFetchHttpLibrary implements HttpLibrary { method: method, body: body as any, headers: request.getHeaders(), + agent: request.getAgent(), }).then((resp: any) => { const headers: { [name: string]: string } = {}; resp.headers.forEach((value: string, name: string) => { diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/http/http.ts index a623aef12789..d4e5df9191dc 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/http/http.ts @@ -5,6 +5,8 @@ import { URLSearchParams } from 'url'; // @ts-ignore import * as URLParse from "url-parse"; import { Observable, from } from '../rxjsStub'; +import * as http from 'http'; +import * as https from 'https'; export * from './isomorphic-fetch'; @@ -50,6 +52,7 @@ export class RequestContext { private headers: { [key: string]: string } = {}; private body: RequestBody = undefined; private url: URLParse; + private agent: http.Agent | https.Agent | undefined = undefined; /** * Creates the request context using a http method and request resource url @@ -122,6 +125,14 @@ export class RequestContext { public setHeaderParam(key: string, value: string): void { this.headers[key] = value; } + + public setAgent(agent: http.Agent | https.Agent) { + this.agent = agent; + } + + public getAgent(): http.Agent | https.Agent | undefined { + return this.agent; + } } export interface ResponseBody { diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/http/isomorphic-fetch.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/http/isomorphic-fetch.ts index ed390df7ce10..26d267cfc063 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/http/isomorphic-fetch.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/http/isomorphic-fetch.ts @@ -12,6 +12,7 @@ export class IsomorphicFetchHttpLibrary implements HttpLibrary { method: method, body: body as any, headers: request.getHeaders(), + agent: request.getAgent(), }).then((resp: any) => { const headers: { [name: string]: string } = {}; resp.headers.forEach((value: string, name: string) => { diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/http/http.ts index 4b9ef54beeb5..cc443163f0e1 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/http/http.ts @@ -2,6 +2,8 @@ // @ts-ignore import * as URLParse from "url-parse"; import { Observable, from } from '../rxjsStub'; +import * as http from 'http'; +import * as https from 'https'; export * from './jquery'; @@ -44,6 +46,7 @@ export class RequestContext { private headers: { [key: string]: string } = {}; private body: RequestBody = undefined; private url: URLParse; + private agent: http.Agent | https.Agent | undefined = undefined; /** * Creates the request context using a http method and request resource url @@ -116,6 +119,14 @@ export class RequestContext { public setHeaderParam(key: string, value: string): void { this.headers[key] = value; } + + public setAgent(agent: http.Agent | https.Agent) { + this.agent = agent; + } + + public getAgent(): http.Agent | https.Agent | undefined { + return this.agent; + } } export interface ResponseBody { diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/http/http.ts index a623aef12789..d4e5df9191dc 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/http/http.ts @@ -5,6 +5,8 @@ import { URLSearchParams } from 'url'; // @ts-ignore import * as URLParse from "url-parse"; import { Observable, from } from '../rxjsStub'; +import * as http from 'http'; +import * as https from 'https'; export * from './isomorphic-fetch'; @@ -50,6 +52,7 @@ export class RequestContext { private headers: { [key: string]: string } = {}; private body: RequestBody = undefined; private url: URLParse; + private agent: http.Agent | https.Agent | undefined = undefined; /** * Creates the request context using a http method and request resource url @@ -122,6 +125,14 @@ export class RequestContext { public setHeaderParam(key: string, value: string): void { this.headers[key] = value; } + + public setAgent(agent: http.Agent | https.Agent) { + this.agent = agent; + } + + public getAgent(): http.Agent | https.Agent | undefined { + return this.agent; + } } export interface ResponseBody { diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/http/isomorphic-fetch.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/http/isomorphic-fetch.ts index ed390df7ce10..26d267cfc063 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/http/isomorphic-fetch.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/http/isomorphic-fetch.ts @@ -12,6 +12,7 @@ export class IsomorphicFetchHttpLibrary implements HttpLibrary { method: method, body: body as any, headers: request.getHeaders(), + agent: request.getAgent(), }).then((resp: any) => { const headers: { [name: string]: string } = {}; resp.headers.forEach((value: string, name: string) => { From 94eb15efdcc4e94612967d4d131f3c748daded74 Mon Sep 17 00:00:00 2001 From: David Gamero Date: Tue, 25 Jan 2022 13:44:38 -0500 Subject: [PATCH 4/8] merge master files --- .../perl/lib/WWW/OpenAPIClient/Object/Foo.pm | 183 ++++++ .../php-dt/src/App/DTO/Collection25.php | 16 + .../lib/Model/AdditionalPropertiesClass.php | 350 ++++++++++++ .../python/dynamic_servers/api/usage_api.py | 316 +++++++++++ .../schema/petstore/mysql/mysql_schema.sql | 534 ++++++++++++++++++ .../src/App/DTO/Collection3.php | 14 + .../src/openapi_server/models/tag.py | 26 + 7 files changed, 1439 insertions(+) diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Foo.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Foo.pm index e69de29bb2d1..e400a15003bd 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Foo.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/Object/Foo.pm @@ -0,0 +1,183 @@ +=begin comment + +OpenAPI Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech + +=end comment + +=cut + +# +# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +# Do not edit the class manually. +# Ref: https://openapi-generator.tech +# +package WWW::OpenAPIClient::Object::Foo; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + + +use base ("Class::Accessor", "Class::Data::Inheritable"); + +# +# +# +# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. +# REF: https://openapi-generator.tech +# + +=begin comment + +OpenAPI Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech + +=end comment + +=cut + +# +# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +# Do not edit the class manually. +# Ref: https://openapi-generator.tech +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('openapi_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new plain object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + $self->init(%args); + + return $self; +} + +# initialize the object +sub init +{ + my ($self, %args) = @_; + + foreach my $attribute (keys %{$self->attribute_map}) { + my $args_key = $self->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } +} + +# return perl hash +sub to_hash { + my $self = shift; + my $_hash = decode_json(JSON->new->convert_blessed->encode($self)); + + return $_hash; +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use openapi_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->openapi_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[(.+)\]$/i) { # array + my $_subclass = $1; + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif ($_type =~ /^hash\[string,(.+)\]$/i) { # hash + my $_subclass = $1; + my %_hash = (); + while (my($_key, $_element) = each %{$hash->{$_json_attribute}}) { + $_hash{$_key} = $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \%_hash; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::OpenAPIClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + +__PACKAGE__->class_documentation({description => '', + class => 'Foo', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'bar' => { + datatype => 'string', + base_name => 'bar', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->openapi_types( { + 'bar' => 'string' +} ); + +__PACKAGE__->attribute_map( { + 'bar' => 'bar' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/php-dt/src/App/DTO/Collection25.php b/samples/client/petstore/php-dt/src/App/DTO/Collection25.php index e69de29bb2d1..8cc9f56843a8 100644 --- a/samples/client/petstore/php-dt/src/App/DTO/Collection25.php +++ b/samples/client/petstore/php-dt/src/App/DTO/Collection25.php @@ -0,0 +1,16 @@ + + * @template TKey int|null + * @template TValue mixed|null + */ +class AdditionalPropertiesClass implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'AdditionalPropertiesClass'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'map_property' => 'array', + 'map_of_map_property' => 'array>' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'map_property' => null, + 'map_of_map_property' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'map_property' => 'map_property', + 'map_of_map_property' => 'map_of_map_property' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'map_property' => 'setMapProperty', + 'map_of_map_property' => 'setMapOfMapProperty' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'map_property' => 'getMapProperty', + 'map_of_map_property' => 'getMapOfMapProperty' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['map_property'] = $data['map_property'] ?? null; + $this->container['map_of_map_property'] = $data['map_of_map_property'] ?? null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets map_property + * + * @return array|null + */ + public function getMapProperty() + { + return $this->container['map_property']; + } + + /** + * Sets map_property + * + * @param array|null $map_property map_property + * + * @return self + */ + public function setMapProperty($map_property) + { + $this->container['map_property'] = $map_property; + + return $this; + } + + /** + * Gets map_of_map_property + * + * @return array>|null + */ + public function getMapOfMapProperty() + { + return $this->container['map_of_map_property']; + } + + /** + * Sets map_of_map_property + * + * @param array>|null $map_of_map_property map_of_map_property + * + * @return self + */ + public function setMapOfMapProperty($map_of_map_property) + { + $this->container['map_of_map_property'] = $map_of_map_property; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed|null + */ + public function offsetGet($offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api/usage_api.py b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api/usage_api.py index e69de29bb2d1..f71f533ceeca 100644 --- a/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api/usage_api.py +++ b/samples/openapi3/client/features/dynamic-servers/python/dynamic_servers/api/usage_api.py @@ -0,0 +1,316 @@ +""" + OpenAPI Extension with dynamic servers + + This specification shows how to use dynamic servers. # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +import re # noqa: F401 +import sys # noqa: F401 + +from dynamic_servers.api_client import ApiClient, Endpoint as _Endpoint +from dynamic_servers.model_utils import ( # noqa: F401 + check_allowed_values, + check_validations, + date, + datetime, + file_type, + none_type, + validate_and_convert_types +) + + +class UsageApi(object): + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None): + if api_client is None: + api_client = ApiClient() + self.api_client = api_client + self.custom_server_endpoint = _Endpoint( + settings={ + 'response_type': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), + 'auth': [], + 'endpoint_path': '/custom', + 'operation_id': 'custom_server', + 'http_method': 'GET', + 'servers': [ + { + 'url': "https://{server}.swagger.io:{port}/v2", + 'description': "No description provided", + 'variables': { + 'server': { + 'description': "No description provided", + 'default_value': "custom-petstore", + 'enum_values': [ + "custom-petstore", + "custom-qa-petstore", + "custom-dev-petstore" + ] + }, + 'port': { + 'description': "No description provided", + 'default_value': "8080", + 'enum_values': [ + "80", + "8080" + ] + } + } + }, + { + 'url': "https://localhost:8081/{version}", + 'description': "The local custom server", + 'variables': { + 'version': { + 'description': "No description provided", + 'default_value': "v2", + 'enum_values': [ + "v1", + "v2", + "v3" + ] + } + } + }, + { + 'url': "https://third.example.com/{prefix}", + 'description': "The local custom server", + 'variables': { + 'prefix': { + 'description': "No description provided", + 'default_value': "custom", + } + } + }, + ] + }, + params_map={ + 'all': [ + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + }, + 'attribute_map': { + }, + 'location_map': { + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client + ) + self.default_server_endpoint = _Endpoint( + settings={ + 'response_type': ({str: (bool, date, datetime, dict, float, int, list, str, none_type)},), + 'auth': [], + 'endpoint_path': '/default', + 'operation_id': 'default_server', + 'http_method': 'GET', + 'servers': None, + }, + params_map={ + 'all': [ + ], + 'required': [], + 'nullable': [ + ], + 'enum': [ + ], + 'validation': [ + ] + }, + root_map={ + 'validations': { + }, + 'allowed_values': { + }, + 'openapi_types': { + }, + 'attribute_map': { + }, + 'location_map': { + }, + 'collection_format_map': { + } + }, + headers_map={ + 'accept': [ + 'application/json' + ], + 'content_type': [], + }, + api_client=api_client + ) + + def custom_server( + self, + **kwargs + ): + """Use custom server # noqa: E501 + + Use custom server # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.custom_server(async_req=True) + >>> result = thread.get() + + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _content_type (str/None): force body content-type. + Default is None and content-type will be predicted by allowed + content-types and body. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + {str: (bool, date, datetime, dict, float, int, list, str, none_type)} + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_spec_property_naming'] = kwargs.get( + '_spec_property_naming', False + ) + kwargs['_content_type'] = kwargs.get( + '_content_type') + kwargs['_host_index'] = kwargs.get('_host_index') + return self.custom_server_endpoint.call_with_http_info(**kwargs) + + def default_server( + self, + **kwargs + ): + """Use default server # noqa: E501 + + Use default server # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.default_server(async_req=True) + >>> result = thread.get() + + + Keyword Args: + _return_http_data_only (bool): response data without head status + code and headers. Default is True. + _preload_content (bool): if False, the urllib3.HTTPResponse object + will be returned without reading/decoding response data. + Default is True. + _request_timeout (int/float/tuple): timeout setting for this request. If + one number provided, it will be total request timeout. It can also + be a pair (tuple) of (connection, read) timeouts. + Default is None. + _check_input_type (bool): specifies if type checking + should be done one the data sent to the server. + Default is True. + _check_return_type (bool): specifies if type checking + should be done one the data received from the server. + Default is True. + _spec_property_naming (bool): True if the variable names in the input data + are serialized names, as specified in the OpenAPI document. + False if the variable names in the input data + are pythonic names, e.g. snake case (default) + _content_type (str/None): force body content-type. + Default is None and content-type will be predicted by allowed + content-types and body. + _host_index (int/None): specifies the index of the server + that we want to use. + Default is read from the configuration. + async_req (bool): execute request asynchronously + + Returns: + {str: (bool, date, datetime, dict, float, int, list, str, none_type)} + If the method is called asynchronously, returns the request + thread. + """ + kwargs['async_req'] = kwargs.get( + 'async_req', False + ) + kwargs['_return_http_data_only'] = kwargs.get( + '_return_http_data_only', True + ) + kwargs['_preload_content'] = kwargs.get( + '_preload_content', True + ) + kwargs['_request_timeout'] = kwargs.get( + '_request_timeout', None + ) + kwargs['_check_input_type'] = kwargs.get( + '_check_input_type', True + ) + kwargs['_check_return_type'] = kwargs.get( + '_check_return_type', True + ) + kwargs['_spec_property_naming'] = kwargs.get( + '_spec_property_naming', False + ) + kwargs['_content_type'] = kwargs.get( + '_content_type') + kwargs['_host_index'] = kwargs.get('_host_index') + return self.default_server_endpoint.call_with_http_info(**kwargs) + diff --git a/samples/schema/petstore/mysql/mysql_schema.sql b/samples/schema/petstore/mysql/mysql_schema.sql index e69de29bb2d1..a189b16c3ab5 100644 --- a/samples/schema/petstore/mysql/mysql_schema.sql +++ b/samples/schema/petstore/mysql/mysql_schema.sql @@ -0,0 +1,534 @@ +/* SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; */ +/* SET AUTOCOMMIT = 0; */ +/* START TRANSACTION; */ +/* SET time_zone = "+00:00"; */ + +-- -------------------------------------------------------- + +-- +-- Table structure for table `200_response` generated from model '200Underscoreresponse' +-- Model for testing model name starting with number +-- + +CREATE TABLE IF NOT EXISTS `200_response` ( + `name` INT DEFAULT NULL, + `class` TEXT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Model for testing model name starting with number'; + +-- +-- Table structure for table `AdditionalPropertiesClass` generated from model 'AdditionalPropertiesClass' +-- + +CREATE TABLE IF NOT EXISTS `AdditionalPropertiesClass` ( + `map_property` JSON DEFAULT NULL, + `map_of_map_property` JSON DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `Animal` generated from model 'Animal' +-- + +CREATE TABLE IF NOT EXISTS `Animal` ( + `className` TEXT NOT NULL, + `color` TEXT +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `ApiResponse` generated from model 'ApiResponse' +-- + +CREATE TABLE IF NOT EXISTS `ApiResponse` ( + `code` INT DEFAULT NULL, + `type` TEXT DEFAULT NULL, + `message` TEXT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `ArrayOfArrayOfNumberOnly` generated from model 'ArrayOfArrayOfNumberOnly' +-- + +CREATE TABLE IF NOT EXISTS `ArrayOfArrayOfNumberOnly` ( + `ArrayArrayNumber` JSON DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `ArrayOfNumberOnly` generated from model 'ArrayOfNumberOnly' +-- + +CREATE TABLE IF NOT EXISTS `ArrayOfNumberOnly` ( + `ArrayNumber` JSON DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `ArrayTest` generated from model 'ArrayTest' +-- + +CREATE TABLE IF NOT EXISTS `ArrayTest` ( + `array_of_string` JSON DEFAULT NULL, + `array_array_of_integer` JSON DEFAULT NULL, + `array_array_of_model` JSON DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `Capitalization` generated from model 'Capitalization' +-- + +CREATE TABLE IF NOT EXISTS `Capitalization` ( + `smallCamel` TEXT DEFAULT NULL, + `CapitalCamel` TEXT DEFAULT NULL, + `small_Snake` TEXT DEFAULT NULL, + `Capital_Snake` TEXT DEFAULT NULL, + `SCA_ETH_Flow_Points` TEXT DEFAULT NULL, + `ATT_NAME` TEXT DEFAULT NULL COMMENT 'Name of the pet ' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `Cat` generated from model 'Cat' +-- + +CREATE TABLE IF NOT EXISTS `Cat` ( + `className` TEXT NOT NULL, + `color` TEXT, + `declawed` TINYINT(1) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `Cat_allOf` generated from model 'CatUnderscoreallOf' +-- + +CREATE TABLE IF NOT EXISTS `Cat_allOf` ( + `declawed` TINYINT(1) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `Category` generated from model 'Category' +-- + +CREATE TABLE IF NOT EXISTS `Category` ( + `id` BIGINT DEFAULT NULL, + `name` TEXT NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `ClassModel` generated from model 'ClassModel' +-- Model for testing model with \"_class\" property +-- + +CREATE TABLE IF NOT EXISTS `ClassModel` ( + `_class` TEXT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Model for testing model with \"_class\" property'; + +-- +-- Table structure for table `Client` generated from model 'Client' +-- + +CREATE TABLE IF NOT EXISTS `Client` ( + `client` TEXT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `DeprecatedObject` generated from model 'DeprecatedObject' +-- + +CREATE TABLE IF NOT EXISTS `DeprecatedObject` ( + `name` TEXT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `Dog` generated from model 'Dog' +-- + +CREATE TABLE IF NOT EXISTS `Dog` ( + `className` TEXT NOT NULL, + `color` TEXT, + `breed` TEXT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `Dog_allOf` generated from model 'DogUnderscoreallOf' +-- + +CREATE TABLE IF NOT EXISTS `Dog_allOf` ( + `breed` TEXT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `EnumArrays` generated from model 'EnumArrays' +-- + +CREATE TABLE IF NOT EXISTS `EnumArrays` ( + `just_symbol` ENUM('>=', '$') DEFAULT NULL, + `array_enum` JSON DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `Enum_Test` generated from model 'EnumUnderscoreTest' +-- + +CREATE TABLE IF NOT EXISTS `Enum_Test` ( + `enum_string` ENUM('UPPER', 'lower', '') DEFAULT NULL, + `enum_string_required` ENUM('UPPER', 'lower', '') NOT NULL, + `enum_integer` ENUM('1', '-1') DEFAULT NULL, + `enum_number` ENUM('1.1', '-1.2') DEFAULT NULL, + `outerEnum` TEXT DEFAULT NULL, + `outerEnumInteger` TEXT DEFAULT NULL, + `outerEnumDefaultValue` TEXT DEFAULT NULL, + `outerEnumIntegerDefaultValue` TEXT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `File` generated from model 'File' +-- Must be named `File` for test. +-- + +CREATE TABLE IF NOT EXISTS `File` ( + `sourceURI` TEXT DEFAULT NULL COMMENT 'Test capitalization' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Must be named `File` for test.'; + +-- +-- Table structure for table `FileSchemaTestClass` generated from model 'FileSchemaTestClass' +-- + +CREATE TABLE IF NOT EXISTS `FileSchemaTestClass` ( + `file` TEXT DEFAULT NULL, + `files` JSON DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `Foo` generated from model 'Foo' +-- + +CREATE TABLE IF NOT EXISTS `Foo` ( + `bar` TEXT +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `format_test` generated from model 'formatUnderscoretest' +-- + +CREATE TABLE IF NOT EXISTS `format_test` ( + `integer` TINYINT UNSIGNED DEFAULT NULL, + `int32` TINYINT UNSIGNED DEFAULT NULL, + `int64` BIGINT DEFAULT NULL, + `number` DECIMAL(20, 9) UNSIGNED NOT NULL, + `float` DECIMAL(20, 9) UNSIGNED DEFAULT NULL, + `double` DECIMAL(20, 9) UNSIGNED DEFAULT NULL, + `decimal` TEXT DEFAULT NULL, + `string` TEXT DEFAULT NULL, + `byte` MEDIUMBLOB NOT NULL, + `binary` MEDIUMBLOB DEFAULT NULL, + `date` DATE NOT NULL, + `dateTime` DATETIME DEFAULT NULL, + `uuid` TEXT DEFAULT NULL, + `password` VARCHAR(64) NOT NULL, + `pattern_with_digits` TEXT DEFAULT NULL COMMENT 'A string that is a 10 digit number. Can have leading zeros.', + `pattern_with_digits_and_delimiter` TEXT DEFAULT NULL COMMENT 'A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `hasOnlyReadOnly` generated from model 'hasOnlyReadOnly' +-- + +CREATE TABLE IF NOT EXISTS `hasOnlyReadOnly` ( + `bar` TEXT DEFAULT NULL, + `foo` TEXT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `HealthCheckResult` generated from model 'HealthCheckResult' +-- Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. +-- + +CREATE TABLE IF NOT EXISTS `HealthCheckResult` ( + `NullableMessage` TEXT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model.'; + +-- +-- Table structure for table `inline_response_default` generated from model 'inlineUnderscoreresponseUnderscoredefault' +-- + +CREATE TABLE IF NOT EXISTS `inline_response_default` ( + `string` TEXT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `List` generated from model 'List' +-- + +CREATE TABLE IF NOT EXISTS `List` ( + `123-list` TEXT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `MapTest` generated from model 'MapTest' +-- + +CREATE TABLE IF NOT EXISTS `MapTest` ( + `map_map_of_string` JSON DEFAULT NULL, + `map_of_enum_string` JSON DEFAULT NULL, + `direct_map` JSON DEFAULT NULL, + `indirect_map` JSON DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `MixedPropertiesAndAdditionalPropertiesClass` generated from model 'MixedPropertiesAndAdditionalPropertiesClass' +-- + +CREATE TABLE IF NOT EXISTS `MixedPropertiesAndAdditionalPropertiesClass` ( + `uuid` TEXT DEFAULT NULL, + `dateTime` DATETIME DEFAULT NULL, + `map` JSON DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `Name` generated from model 'Name' +-- Model for testing model name same as property name +-- + +CREATE TABLE IF NOT EXISTS `Name` ( + `name` INT NOT NULL, + `snake_case` INT DEFAULT NULL, + `property` TEXT DEFAULT NULL, + `123Number` INT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Model for testing model name same as property name'; + +-- +-- Table structure for table `NullableClass` generated from model 'NullableClass' +-- + +CREATE TABLE IF NOT EXISTS `NullableClass` ( + `integer_prop` INT DEFAULT NULL, + `number_prop` DECIMAL(20, 9) DEFAULT NULL, + `boolean_prop` TINYINT(1) DEFAULT NULL, + `string_prop` TEXT DEFAULT NULL, + `date_prop` DATE DEFAULT NULL, + `datetime_prop` DATETIME DEFAULT NULL, + `array_nullable_prop` JSON DEFAULT NULL, + `array_and_items_nullable_prop` JSON DEFAULT NULL, + `array_items_nullable` JSON DEFAULT NULL, + `object_nullable_prop` JSON DEFAULT NULL, + `object_and_items_nullable_prop` JSON DEFAULT NULL, + `object_items_nullable` JSON DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `NumberOnly` generated from model 'NumberOnly' +-- + +CREATE TABLE IF NOT EXISTS `NumberOnly` ( + `JustNumber` DECIMAL(20, 9) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `ObjectWithDeprecatedFields` generated from model 'ObjectWithDeprecatedFields' +-- + +CREATE TABLE IF NOT EXISTS `ObjectWithDeprecatedFields` ( + `uuid` TEXT DEFAULT NULL, + `id` DECIMAL(20, 9) DEFAULT NULL, + `deprecatedRef` TEXT DEFAULT NULL, + `bars` JSON DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `Order` generated from model 'Order' +-- + +CREATE TABLE IF NOT EXISTS `Order` ( + `id` BIGINT DEFAULT NULL, + `petId` BIGINT DEFAULT NULL, + `quantity` INT DEFAULT NULL, + `shipDate` DATETIME DEFAULT NULL, + `status` ENUM('placed', 'approved', 'delivered') DEFAULT NULL COMMENT 'Order Status', + `complete` TINYINT(1) DEFAULT false +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `OuterComposite` generated from model 'OuterComposite' +-- + +CREATE TABLE IF NOT EXISTS `OuterComposite` ( + `my_number` DECIMAL(20, 9) DEFAULT NULL, + `my_string` TEXT DEFAULT NULL, + `my_boolean` TINYINT(1) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `OuterObjectWithEnumProperty` generated from model 'OuterObjectWithEnumProperty' +-- + +CREATE TABLE IF NOT EXISTS `OuterObjectWithEnumProperty` ( + `value` TEXT NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `Pet` generated from model 'Pet' +-- + +CREATE TABLE IF NOT EXISTS `Pet` ( + `id` BIGINT DEFAULT NULL, + `category` TEXT DEFAULT NULL, + `name` TEXT NOT NULL, + `photoUrls` JSON NOT NULL, + `tags` JSON DEFAULT NULL, + `status` ENUM('available', 'pending', 'sold') DEFAULT NULL COMMENT 'pet status in the store' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `ReadOnlyFirst` generated from model 'ReadOnlyFirst' +-- + +CREATE TABLE IF NOT EXISTS `ReadOnlyFirst` ( + `bar` TEXT DEFAULT NULL, + `baz` TEXT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `Return` generated from model 'Return' +-- Model for testing reserved words +-- + +CREATE TABLE IF NOT EXISTS `Return` ( + `return` INT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Model for testing reserved words'; + +-- +-- Table structure for table `_special_model.name_` generated from model 'UnderscorespecialUnderscoremodelPeriodnameUnderscore' +-- + +CREATE TABLE IF NOT EXISTS `_special_model.name_` ( + `$special[property.name]` BIGINT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `Tag` generated from model 'Tag' +-- + +CREATE TABLE IF NOT EXISTS `Tag` ( + `id` BIGINT DEFAULT NULL, + `name` TEXT DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `User` generated from model 'User' +-- + +CREATE TABLE IF NOT EXISTS `User` ( + `id` BIGINT DEFAULT NULL, + `username` TEXT DEFAULT NULL, + `firstName` TEXT DEFAULT NULL, + `lastName` TEXT DEFAULT NULL, + `email` TEXT DEFAULT NULL, + `password` TEXT DEFAULT NULL, + `phone` TEXT DEFAULT NULL, + `userStatus` INT DEFAULT NULL COMMENT 'User Status' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + + +-- +-- OAuth2 framework tables +-- Thanks to https://github.com/dsquier/oauth2-server-php-mysql repo +-- + +-- +-- Table structure for table `oauth_clients` +-- +CREATE TABLE IF NOT EXISTS `oauth_clients` ( + `client_id` VARCHAR(80) NOT NULL, + `client_secret` VARCHAR(80) DEFAULT NULL, + `redirect_uri` VARCHAR(2000) DEFAULT NULL, + `grant_types` VARCHAR(80) DEFAULT NULL, + `scope` VARCHAR(4000) DEFAULT NULL, + `user_id` VARCHAR(80) DEFAULT NULL, + PRIMARY KEY (`client_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `oauth_access_tokens` +-- +CREATE TABLE IF NOT EXISTS `oauth_access_tokens` ( + `access_token` VARCHAR(40) NOT NULL, + `client_id` VARCHAR(80) DEFAULT NULL, + `user_id` VARCHAR(80) DEFAULT NULL, + `expires` TIMESTAMP NOT NULL, + `scope` VARCHAR(4000) DEFAULT NULL, + PRIMARY KEY (`access_token`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `oauth_authorization_codes` +-- +CREATE TABLE IF NOT EXISTS `oauth_authorization_codes` ( + `authorization_code` VARCHAR(40) NOT NULL, + `client_id` VARCHAR(80) DEFAULT NULL, + `user_id` VARCHAR(80) DEFAULT NULL, + `redirect_uri` VARCHAR(2000) NOT NULL, + `expires` TIMESTAMP NOT NULL, + `scope` VARCHAR(4000) DEFAULT NULL, + `id_token` VARCHAR(1000) DEFAULT NULL, + PRIMARY KEY (`authorization_code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `oauth_refresh_tokens` +-- +CREATE TABLE IF NOT EXISTS `oauth_refresh_tokens` ( + `refresh_token` VARCHAR(40) NOT NULL, + `client_id` VARCHAR(80) DEFAULT NULL, + `user_id` VARCHAR(80) DEFAULT NULL, + `expires` TIMESTAMP on update CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + `scope` VARCHAR(4000) DEFAULT NULL, + PRIMARY KEY (`refresh_token`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `oauth_users` +-- +CREATE TABLE IF NOT EXISTS `oauth_users` ( + `username` VARCHAR(80) DEFAULT NULL, + `password` VARCHAR(255) DEFAULT NULL, + `first_name` VARCHAR(80) DEFAULT NULL, + `last_name` VARCHAR(80) DEFAULT NULL, + `email` VARCHAR(2000) DEFAULT NULL, + `email_verified` TINYINT(1) DEFAULT NULL, + `scope` VARCHAR(4000) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `oauth_scopes` +-- +CREATE TABLE IF NOT EXISTS `oauth_scopes` ( + `scope` VARCHAR(80) NOT NULL, + `is_default` TINYINT(1) DEFAULT NULL, + PRIMARY KEY (`scope`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `oauth_jwt` +-- +CREATE TABLE IF NOT EXISTS `oauth_jwt` ( + `client_id` VARCHAR(80) NOT NULL, + `subject` VARCHAR(80) DEFAULT NULL, + `public_key` VARCHAR(2000) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `oauth_jti` +-- +CREATE TABLE IF NOT EXISTS `oauth_jti` ( + `issuer` VARCHAR(80) NOT NULL, + `subject` VARCHAR(80) DEFAULT NULL, + `audience` VARCHAR(80) DEFAULT NULL, + `expires` TIMESTAMP NOT NULL, + `jti` VARCHAR(2000) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- +-- Table structure for table `oauth_public_keys` +-- +CREATE TABLE IF NOT EXISTS `oauth_public_keys` ( + `client_id` VARCHAR(80) DEFAULT NULL, + `public_key` VARCHAR(2000) DEFAULT NULL, + `private_key` VARCHAR(2000) DEFAULT NULL, + `encryption_algorithm` VARCHAR(100) DEFAULT 'RS256' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection3.php b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection3.php index e69de29bb2d1..1833307cd7e6 100644 --- a/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection3.php +++ b/samples/server/petstore/php-mezzio-ph-modern/src/App/DTO/Collection3.php @@ -0,0 +1,14 @@ + \App\DTO\Tag::class])] +#[DTA\Validator("Collection", ["validators" => [ + ["name" => "TypeCompliant", "options" => ["type" => \App\DTO\Tag::class]] +]])] +class Collection3 extends \ArrayObject +{ +} diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py b/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py index e69de29bb2d1..3e0b45cd787b 100644 --- a/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py +++ b/samples/server/petstore/python-fastapi/src/openapi_server/models/tag.py @@ -0,0 +1,26 @@ +# coding: utf-8 + +from __future__ import annotations +from datetime import date, datetime # noqa: F401 + +import re # noqa: F401 +from typing import Any, Dict, List, Optional # noqa: F401 + +from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401 + + +class Tag(BaseModel): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + + Tag - a model defined in OpenAPI + + id: The id of this Tag [Optional]. + name: The name of this Tag [Optional]. + """ + + id: Optional[int] = None + name: Optional[str] = None + +Tag.update_forward_refs() From 172128ed5f9fc374a0b1b1b21ac06f9e62d0cceb Mon Sep 17 00:00:00 2001 From: David Gamero Date: Tue, 25 Jan 2022 14:27:40 -0500 Subject: [PATCH 5/8] only enable custom agent on nodejs not browser --- .../resources/typescript/http/http.mustache | 12 +- .../typescript/http/isomorphic-fetch.mustache | 4 +- .../git_push.sh | 57 -- .../with-single-request-parameters/.gitignore | 4 - .../builds/default/apis/PetApi.ts | 189 +---- .../builds/es6-target/src/apis/PetApi.ts | 189 +---- .../typescript/builds/default/apis/PetApi.ts | 67 +- .../typescript/builds/deno/apis/PetApi.ts | 452 +----------- .../builds/inversify/apis/PetApi.ts | 640 ----------------- .../typescript/builds/jquery/apis/PetApi.ts | 667 ------------------ .../builds/object_params/git_push.sh | 51 -- 11 files changed, 17 insertions(+), 2315 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/typescript/http/http.mustache b/modules/openapi-generator/src/main/resources/typescript/http/http.mustache index 2b051b7c118d..1731c1c23432 100644 --- a/modules/openapi-generator/src/main/resources/typescript/http/http.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/http/http.mustache @@ -3,6 +3,8 @@ // TODO: evaluate if we can easily get rid of this library import * as FormData from "form-data"; import { URLSearchParams } from 'url'; +import * as http from 'http'; +import * as https from 'https'; {{/node}} {{/platforms}} {{#platforms}} @@ -13,8 +15,6 @@ import * as URLParse from "url-parse"; {{/deno}} {{/platforms}} import { Observable, from } from {{#useRxJS}}'rxjs'{{/useRxJS}}{{^useRxJS}}'../rxjsStub{{extensionForDeno}}'{{/useRxJS}}; -import * as http from 'http'; -import * as https from 'https'; {{#platforms}} {{^deno}} @@ -115,7 +115,11 @@ export class RequestContext { private headers: { [key: string]: string } = {}; private body: RequestBody = undefined; private url: URLParse; + {{#platforms}} + {{#node}} private agent: http.Agent | https.Agent | undefined = undefined; + {{/node}} + {{/platforms}} /** * Creates the request context using a http method and request resource url @@ -189,6 +193,8 @@ export class RequestContext { this.headers[key] = value; } + {{#platforms}} + {{#node}} public setAgent(agent: http.Agent | https.Agent) { this.agent = agent; } @@ -196,6 +202,8 @@ export class RequestContext { public getAgent(): http.Agent | https.Agent | undefined { return this.agent; } + {{#node}} + {{#platforms}} } export interface ResponseBody { diff --git a/modules/openapi-generator/src/main/resources/typescript/http/isomorphic-fetch.mustache b/modules/openapi-generator/src/main/resources/typescript/http/isomorphic-fetch.mustache index 59c5805a42b4..57b1ae594f6f 100644 --- a/modules/openapi-generator/src/main/resources/typescript/http/isomorphic-fetch.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/http/isomorphic-fetch.mustache @@ -19,8 +19,10 @@ export class IsomorphicFetchHttpLibrary implements HttpLibrary { method: method, body: body as any, headers: request.getHeaders(), - agent: request.getAgent(), {{#platforms}} + {{#node}} + agent: request.getAgent(), + {{/node}} {{#browser}} credentials: "same-origin" {{/browser}} diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/git_push.sh b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/git_push.sh index f53a75d4fabe..e69de29bb2d1 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/git_push.sh +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/git_push.sh @@ -1,57 +0,0 @@ -#!/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-petstore-perl "minor update" "gitlab.com" - -git_user_id=$1 -git_repo_id=$2 -release_note=$3 -git_host=$4 - -if [ "$git_host" = "" ]; then - git_host="github.com" - echo "[INFO] No command line input provided. Set \$git_host to $git_host" -fi - -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://${git_host}/${git_user_id}/${git_repo_id}.git - else - git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${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://${git_host}/${git_user_id}/${git_repo_id}.git" -git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.gitignore b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.gitignore index 149b57654723..e69de29bb2d1 100644 --- a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.gitignore +++ b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.gitignore @@ -1,4 +0,0 @@ -wwwroot/*.js -node_modules -typings -dist diff --git a/samples/client/petstore/typescript-fetch/builds/default/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/default/apis/PetApi.ts index e4ddf7e853a0..232d4b3f1fa3 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/apis/PetApi.ts @@ -235,191 +235,4 @@ export class PetApi extends runtime.BaseAPI { const headerParameters: runtime.HTTPHeaders = {}; - if (this.configuration && this.configuration.apiKey) { - headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication - } - - const response = await this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), - method: 'GET', - headers: headerParameters, - query: queryParameters, - }, initOverrides); - - return new runtime.JSONApiResponse(response, (jsonValue) => PetFromJSON(jsonValue)); - } - - /** - * Returns a single pet - * Find pet by ID - */ - async getPetById(requestParameters: GetPetByIdRequest, initOverrides?: RequestInit): Promise { - const response = await this.getPetByIdRaw(requestParameters, initOverrides); - return await response.value(); - } - - /** - * Update an existing pet - */ - async updatePetRaw(requestParameters: UpdatePetRequest, initOverrides?: RequestInit): Promise> { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updatePet.'); - } - - const queryParameters: any = {}; - - const headerParameters: runtime.HTTPHeaders = {}; - - headerParameters['Content-Type'] = 'application/json'; - - if (this.configuration && this.configuration.accessToken) { - // oauth required - headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } - - const response = await this.request({ - path: `/pet`, - method: 'PUT', - headers: headerParameters, - query: queryParameters, - body: PetToJSON(requestParameters.body), - }, initOverrides); - - return new runtime.VoidApiResponse(response); - } - - /** - * Update an existing pet - */ - async updatePet(requestParameters: UpdatePetRequest, initOverrides?: RequestInit): Promise { - await this.updatePetRaw(requestParameters, initOverrides); - } - - /** - * Updates a pet in the store with form data - */ - async updatePetWithFormRaw(requestParameters: UpdatePetWithFormRequest, initOverrides?: RequestInit): Promise> { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling updatePetWithForm.'); - } - - const queryParameters: any = {}; - - const headerParameters: runtime.HTTPHeaders = {}; - - if (this.configuration && this.configuration.accessToken) { - // oauth required - headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } - - const consumes: runtime.Consume[] = [ - { contentType: 'application/x-www-form-urlencoded' }, - ]; - // @ts-ignore: canConsumeForm may be unused - const canConsumeForm = runtime.canConsumeForm(consumes); - - let formParams: { append(param: string, value: any): any }; - let useForm = false; - if (useForm) { - formParams = new FormData(); - } else { - formParams = new URLSearchParams(); - } - - if (requestParameters.name !== undefined) { - formParams.append('name', requestParameters.name as any); - } - - if (requestParameters.status !== undefined) { - formParams.append('status', requestParameters.status as any); - } - - const response = await this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), - method: 'POST', - headers: headerParameters, - query: queryParameters, - body: formParams, - }, initOverrides); - - return new runtime.VoidApiResponse(response); - } - - /** - * Updates a pet in the store with form data - */ - async updatePetWithForm(requestParameters: UpdatePetWithFormRequest, initOverrides?: RequestInit): Promise { - await this.updatePetWithFormRaw(requestParameters, initOverrides); - } - - /** - * uploads an image - */ - async uploadFileRaw(requestParameters: UploadFileRequest, initOverrides?: RequestInit): Promise> { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling uploadFile.'); - } - - const queryParameters: any = {}; - - const headerParameters: runtime.HTTPHeaders = {}; - - if (this.configuration && this.configuration.accessToken) { - // oauth required - headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } - - const consumes: runtime.Consume[] = [ - { contentType: 'multipart/form-data' }, - ]; - // @ts-ignore: canConsumeForm may be unused - const canConsumeForm = runtime.canConsumeForm(consumes); - - let formParams: { append(param: string, value: any): any }; - let useForm = false; - // use FormData to transmit files using content-type "multipart/form-data" - useForm = canConsumeForm; - if (useForm) { - formParams = new FormData(); - } else { - formParams = new URLSearchParams(); - } - - if (requestParameters.additionalMetadata !== undefined) { - formParams.append('additionalMetadata', requestParameters.additionalMetadata as any); - } - - if (requestParameters.file !== undefined) { - formParams.append('file', requestParameters.file as any); - } - - const response = await this.request({ - path: `/pet/{petId}/uploadImage`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), - method: 'POST', - headers: headerParameters, - query: queryParameters, - body: formParams, - }, initOverrides); - - return new runtime.JSONApiResponse(response, (jsonValue) => ModelApiResponseFromJSON(jsonValue)); - } - - /** - * uploads an image - */ - async uploadFile(requestParameters: UploadFileRequest, initOverrides?: RequestInit): Promise { - const response = await this.uploadFileRaw(requestParameters, initOverrides); - return await response.value(); - } - -} - -/** - * @export - * @enum {string} - */ -export enum FindPetsByStatusStatusEnum { - Available = 'available', - Pending = 'pending', - Sold = 'sold' -} + if (this.configuration && this.configuration.api \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/src/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/src/apis/PetApi.ts index e4ddf7e853a0..232d4b3f1fa3 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/src/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/src/apis/PetApi.ts @@ -235,191 +235,4 @@ export class PetApi extends runtime.BaseAPI { const headerParameters: runtime.HTTPHeaders = {}; - if (this.configuration && this.configuration.apiKey) { - headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication - } - - const response = await this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), - method: 'GET', - headers: headerParameters, - query: queryParameters, - }, initOverrides); - - return new runtime.JSONApiResponse(response, (jsonValue) => PetFromJSON(jsonValue)); - } - - /** - * Returns a single pet - * Find pet by ID - */ - async getPetById(requestParameters: GetPetByIdRequest, initOverrides?: RequestInit): Promise { - const response = await this.getPetByIdRaw(requestParameters, initOverrides); - return await response.value(); - } - - /** - * Update an existing pet - */ - async updatePetRaw(requestParameters: UpdatePetRequest, initOverrides?: RequestInit): Promise> { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updatePet.'); - } - - const queryParameters: any = {}; - - const headerParameters: runtime.HTTPHeaders = {}; - - headerParameters['Content-Type'] = 'application/json'; - - if (this.configuration && this.configuration.accessToken) { - // oauth required - headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } - - const response = await this.request({ - path: `/pet`, - method: 'PUT', - headers: headerParameters, - query: queryParameters, - body: PetToJSON(requestParameters.body), - }, initOverrides); - - return new runtime.VoidApiResponse(response); - } - - /** - * Update an existing pet - */ - async updatePet(requestParameters: UpdatePetRequest, initOverrides?: RequestInit): Promise { - await this.updatePetRaw(requestParameters, initOverrides); - } - - /** - * Updates a pet in the store with form data - */ - async updatePetWithFormRaw(requestParameters: UpdatePetWithFormRequest, initOverrides?: RequestInit): Promise> { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling updatePetWithForm.'); - } - - const queryParameters: any = {}; - - const headerParameters: runtime.HTTPHeaders = {}; - - if (this.configuration && this.configuration.accessToken) { - // oauth required - headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } - - const consumes: runtime.Consume[] = [ - { contentType: 'application/x-www-form-urlencoded' }, - ]; - // @ts-ignore: canConsumeForm may be unused - const canConsumeForm = runtime.canConsumeForm(consumes); - - let formParams: { append(param: string, value: any): any }; - let useForm = false; - if (useForm) { - formParams = new FormData(); - } else { - formParams = new URLSearchParams(); - } - - if (requestParameters.name !== undefined) { - formParams.append('name', requestParameters.name as any); - } - - if (requestParameters.status !== undefined) { - formParams.append('status', requestParameters.status as any); - } - - const response = await this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), - method: 'POST', - headers: headerParameters, - query: queryParameters, - body: formParams, - }, initOverrides); - - return new runtime.VoidApiResponse(response); - } - - /** - * Updates a pet in the store with form data - */ - async updatePetWithForm(requestParameters: UpdatePetWithFormRequest, initOverrides?: RequestInit): Promise { - await this.updatePetWithFormRaw(requestParameters, initOverrides); - } - - /** - * uploads an image - */ - async uploadFileRaw(requestParameters: UploadFileRequest, initOverrides?: RequestInit): Promise> { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling uploadFile.'); - } - - const queryParameters: any = {}; - - const headerParameters: runtime.HTTPHeaders = {}; - - if (this.configuration && this.configuration.accessToken) { - // oauth required - headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } - - const consumes: runtime.Consume[] = [ - { contentType: 'multipart/form-data' }, - ]; - // @ts-ignore: canConsumeForm may be unused - const canConsumeForm = runtime.canConsumeForm(consumes); - - let formParams: { append(param: string, value: any): any }; - let useForm = false; - // use FormData to transmit files using content-type "multipart/form-data" - useForm = canConsumeForm; - if (useForm) { - formParams = new FormData(); - } else { - formParams = new URLSearchParams(); - } - - if (requestParameters.additionalMetadata !== undefined) { - formParams.append('additionalMetadata', requestParameters.additionalMetadata as any); - } - - if (requestParameters.file !== undefined) { - formParams.append('file', requestParameters.file as any); - } - - const response = await this.request({ - path: `/pet/{petId}/uploadImage`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), - method: 'POST', - headers: headerParameters, - query: queryParameters, - body: formParams, - }, initOverrides); - - return new runtime.JSONApiResponse(response, (jsonValue) => ModelApiResponseFromJSON(jsonValue)); - } - - /** - * uploads an image - */ - async uploadFile(requestParameters: UploadFileRequest, initOverrides?: RequestInit): Promise { - const response = await this.uploadFileRaw(requestParameters, initOverrides); - return await response.value(); - } - -} - -/** - * @export - * @enum {string} - */ -export enum FindPetsByStatusStatusEnum { - Available = 'available', - Pending = 'pending', - Sold = 'sold' -} + if (this.configuration && this.configuration.api \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts index e85797baebc1..9808bc699fa8 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts @@ -601,69 +601,4 @@ export class PetApiResponseProcessor { throw new ApiException(response.httpStatusCode, "Pet not found", undefined, response.headers); } if (isCodeInRange("405", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Validation exception", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 updatePetWithForm - * @throws ApiException if the response code was not in [200, 299] - */ - public async updatePetWithForm(response: ResponseContext): Promise< void> { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("405", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid input", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - return; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 uploadFile - * @throws ApiException if the response code was not in [200, 299] - */ - public async uploadFile(response: ResponseContext): Promise { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: ApiResponse = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "ApiResponse", "" - ) as ApiResponse; - return body; - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: ApiResponse = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "ApiResponse", "" - ) as ApiResponse; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - -} + throw new ApiException(response.httpStatusCode, "Val \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts index f11b208baf24..456e4fa2b7a3 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts @@ -214,454 +214,4 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["api_key"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default - if (defaultAuth?.applySecurityAuthentication) { - await defaultAuth?.applySecurityAuthentication(requestContext); - } - - return requestContext; - } - - /** - * Update an existing pet - * @param pet Pet object that needs to be added to the store - */ - public async updatePet(pet: Pet, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'pet' is not null or undefined - if (pet === null || pet === undefined) { - throw new RequiredError("PetApi", "updatePet", "pet"); - } - - - // Path Params - const localVarPath = '/pet'; - - // Make Request Context - const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); - requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") - - - // Body Params - const contentType = ObjectSerializer.getPreferredMediaType([ - "application/json", - - "application/xml" - ]); - requestContext.setHeaderParam("Content-Type", contentType); - const serializedBody = ObjectSerializer.stringify( - ObjectSerializer.serialize(pet, "Pet", ""), - contentType - ); - requestContext.setBody(serializedBody); - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default - if (defaultAuth?.applySecurityAuthentication) { - await defaultAuth?.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 async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'petId' is not null or undefined - if (petId === null || petId === undefined) { - throw new RequiredError("PetApi", "updatePetWithForm", "petId"); - } - - - - - // 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, */*;q=0.8") - - // Form Params - const useForm = canConsumeForm([ - 'application/x-www-form-urlencoded', - ]); - - let localVarFormParams - if (useForm) { - localVarFormParams = new FormData(); - } else { - localVarFormParams = new URLSearchParams(); - } - - 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); - - if(!useForm) { - const contentType = ObjectSerializer.getPreferredMediaType([ - "application/x-www-form-urlencoded" - ]); - requestContext.setHeaderParam("Content-Type", contentType); - } - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default - if (defaultAuth?.applySecurityAuthentication) { - await defaultAuth?.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 async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'petId' is not null or undefined - if (petId === null || petId === undefined) { - throw new RequiredError("PetApi", "uploadFile", "petId"); - } - - - - - // 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, */*;q=0.8") - - // Form Params - const useForm = canConsumeForm([ - 'multipart/form-data', - ]); - - let localVarFormParams - if (useForm) { - localVarFormParams = new FormData(); - } else { - localVarFormParams = new URLSearchParams(); - } - - if (additionalMetadata !== undefined) { - // TODO: replace .append with .set - localVarFormParams.append('additionalMetadata', additionalMetadata as any); - } - if (file !== undefined) { - // TODO: replace .append with .set - if (localVarFormParams instanceof FormData) { - localVarFormParams.append('file', file, file.name); - } - } - - requestContext.setBody(localVarFormParams); - - if(!useForm) { - const contentType = ObjectSerializer.getPreferredMediaType([ - "multipart/form-data" - ]); - requestContext.setHeaderParam("Content-Type", contentType); - } - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default - if (defaultAuth?.applySecurityAuthentication) { - await defaultAuth?.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 addPet - * @throws ApiException if the response code was not in [200, 299] - */ - public async addPet(response: ResponseContext): Promise { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - if (isCodeInRange("405", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid input", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 deletePet - * @throws ApiException if the response code was not in [200, 299] - */ - public async deletePet(response: ResponseContext): Promise< void> { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid pet value", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - return; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 findPetsByStatus - * @throws ApiException if the response code was not in [200, 299] - */ - public async findPetsByStatus(response: ResponseContext): Promise > { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Array = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Array", "" - ) as Array; - return body; - } - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid status value", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Array = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Array", "" - ) as Array; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 findPetsByTags - * @throws ApiException if the response code was not in [200, 299] - */ - public async findPetsByTags(response: ResponseContext): Promise > { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Array = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Array", "" - ) as Array; - return body; - } - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid tag value", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Array = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Array", "" - ) as Array; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 getPetById - * @throws ApiException if the response code was not in [200, 299] - */ - public async getPetById(response: ResponseContext): Promise { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid ID supplied", undefined, response.headers); - } - if (isCodeInRange("404", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Pet not found", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 updatePet - * @throws ApiException if the response code was not in [200, 299] - */ - public async updatePet(response: ResponseContext): Promise { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid ID supplied", undefined, response.headers); - } - if (isCodeInRange("404", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Pet not found", undefined, response.headers); - } - if (isCodeInRange("405", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Validation exception", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 updatePetWithForm - * @throws ApiException if the response code was not in [200, 299] - */ - public async updatePetWithForm(response: ResponseContext): Promise< void> { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("405", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid input", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - return; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 uploadFile - * @throws ApiException if the response code was not in [200, 299] - */ - public async uploadFile(response: ResponseContext): Promise { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: ApiResponse = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "ApiResponse", "" - ) as ApiResponse; - return body; - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: ApiResponse = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "ApiResponse", "" - ) as ApiResponse; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - -} + let authMethod: SecurityAuth \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts index 81a75d96bcec..e69de29bb2d1 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts @@ -1,640 +0,0 @@ -// 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 { URLSearchParams } from 'url'; -import {ObjectSerializer} from '../models/ObjectSerializer'; -import {ApiException} from './exception'; -import {canConsumeForm, isCodeInRange} from '../util'; -import {SecurityAuthentication} from '../auth/auth'; - -import { injectable } from "inversify"; - -import { ApiResponse } from '../models/ApiResponse'; -import { Pet } from '../models/Pet'; - -/** - * no description - */ -@injectable() -export class PetApiRequestFactory extends BaseAPIRequestFactory { - - /** - * Add a new pet to the store - * @param pet Pet object that needs to be added to the store - */ - public async addPet(pet: Pet, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'pet' is not null or undefined - if (pet === null || pet === undefined) { - throw new RequiredError("PetApi", "addPet", "pet"); - } - - - // Path Params - const localVarPath = '/pet'; - - // Make Request Context - const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); - requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") - - - // Body Params - const contentType = ObjectSerializer.getPreferredMediaType([ - "application/json", - - "application/xml" - ]); - requestContext.setHeaderParam("Content-Type", contentType); - const serializedBody = ObjectSerializer.stringify( - ObjectSerializer.serialize(pet, "Pet", ""), - contentType - ); - requestContext.setBody(serializedBody); - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - - return requestContext; - } - - /** - * Deletes a pet - * @param petId Pet id to delete - * @param apiKey - */ - public async deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'petId' is not null or undefined - if (petId === null || petId === undefined) { - throw new RequiredError("PetApi", "deletePet", "petId"); - } - - - - // 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, */*;q=0.8") - - // Header Params - requestContext.setHeaderParam("api_key", ObjectSerializer.serialize(apiKey, "string", "")); - - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await 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 async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'status' is not null or undefined - if (status === null || status === undefined) { - throw new RequiredError("PetApi", "findPetsByStatus", "status"); - } - - - // Path Params - const localVarPath = '/pet/findByStatus'; - - // Make Request Context - const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); - requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") - - // Query Params - if (status !== undefined) { - requestContext.setQueryParam("status", ObjectSerializer.serialize(status, "Array<'available' | 'pending' | 'sold'>", "")); - } - - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await 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 async findPetsByTags(tags: Array, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'tags' is not null or undefined - if (tags === null || tags === undefined) { - throw new RequiredError("PetApi", "findPetsByTags", "tags"); - } - - - // Path Params - const localVarPath = '/pet/findByTags'; - - // Make Request Context - const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); - requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") - - // Query Params - if (tags !== undefined) { - requestContext.setQueryParam("tags", ObjectSerializer.serialize(tags, "Array", "")); - } - - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - - return requestContext; - } - - /** - * Returns a single pet - * Find pet by ID - * @param petId ID of pet to return - */ - public async getPetById(petId: number, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'petId' is not null or undefined - if (petId === null || petId === undefined) { - throw new RequiredError("PetApi", "getPetById", "petId"); - } - - - // 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, */*;q=0.8") - - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["api_key"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - - return requestContext; - } - - /** - * Update an existing pet - * @param pet Pet object that needs to be added to the store - */ - public async updatePet(pet: Pet, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'pet' is not null or undefined - if (pet === null || pet === undefined) { - throw new RequiredError("PetApi", "updatePet", "pet"); - } - - - // Path Params - const localVarPath = '/pet'; - - // Make Request Context - const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); - requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") - - - // Body Params - const contentType = ObjectSerializer.getPreferredMediaType([ - "application/json", - - "application/xml" - ]); - requestContext.setHeaderParam("Content-Type", contentType); - const serializedBody = ObjectSerializer.stringify( - ObjectSerializer.serialize(pet, "Pet", ""), - contentType - ); - requestContext.setBody(serializedBody); - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await 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 async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'petId' is not null or undefined - if (petId === null || petId === undefined) { - throw new RequiredError("PetApi", "updatePetWithForm", "petId"); - } - - - - - // 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, */*;q=0.8") - - // Form Params - const useForm = canConsumeForm([ - 'application/x-www-form-urlencoded', - ]); - - let localVarFormParams - if (useForm) { - localVarFormParams = new FormData(); - } else { - localVarFormParams = new URLSearchParams(); - } - - 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); - - if(!useForm) { - const contentType = ObjectSerializer.getPreferredMediaType([ - "application/x-www-form-urlencoded" - ]); - requestContext.setHeaderParam("Content-Type", contentType); - } - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await 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 async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'petId' is not null or undefined - if (petId === null || petId === undefined) { - throw new RequiredError("PetApi", "uploadFile", "petId"); - } - - - - - // 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, */*;q=0.8") - - // Form Params - const useForm = canConsumeForm([ - 'multipart/form-data', - ]); - - let localVarFormParams - if (useForm) { - localVarFormParams = new FormData(); - } else { - localVarFormParams = new URLSearchParams(); - } - - if (additionalMetadata !== undefined) { - // TODO: replace .append with .set - localVarFormParams.append('additionalMetadata', additionalMetadata as any); - } - if (file !== undefined) { - // TODO: replace .append with .set - if (localVarFormParams instanceof FormData) { - localVarFormParams.append('file', file.data, file.name); - } - } - - requestContext.setBody(localVarFormParams); - - if(!useForm) { - const contentType = ObjectSerializer.getPreferredMediaType([ - "multipart/form-data" - ]); - requestContext.setHeaderParam("Content-Type", contentType); - } - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - - return requestContext; - } - -} - -@injectable() -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 addPet - * @throws ApiException if the response code was not in [200, 299] - */ - public async addPet(response: ResponseContext): Promise { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - if (isCodeInRange("405", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid input", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 deletePet - * @throws ApiException if the response code was not in [200, 299] - */ - public async deletePet(response: ResponseContext): Promise< void> { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid pet value", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - return; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 findPetsByStatus - * @throws ApiException if the response code was not in [200, 299] - */ - public async findPetsByStatus(response: ResponseContext): Promise > { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Array = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Array", "" - ) as Array; - return body; - } - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid status value", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Array = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Array", "" - ) as Array; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 findPetsByTags - * @throws ApiException if the response code was not in [200, 299] - */ - public async findPetsByTags(response: ResponseContext): Promise > { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Array = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Array", "" - ) as Array; - return body; - } - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid tag value", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Array = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Array", "" - ) as Array; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 getPetById - * @throws ApiException if the response code was not in [200, 299] - */ - public async getPetById(response: ResponseContext): Promise { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid ID supplied", undefined, response.headers); - } - if (isCodeInRange("404", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Pet not found", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 updatePet - * @throws ApiException if the response code was not in [200, 299] - */ - public async updatePet(response: ResponseContext): Promise { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid ID supplied", undefined, response.headers); - } - if (isCodeInRange("404", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Pet not found", undefined, response.headers); - } - if (isCodeInRange("405", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Validation exception", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 updatePetWithForm - * @throws ApiException if the response code was not in [200, 299] - */ - public async updatePetWithForm(response: ResponseContext): Promise< void> { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("405", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid input", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - return; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 uploadFile - * @throws ApiException if the response code was not in [200, 299] - */ - public async uploadFile(response: ResponseContext): Promise { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: ApiResponse = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "ApiResponse", "" - ) as ApiResponse; - return body; - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: ApiResponse = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "ApiResponse", "" - ) as ApiResponse; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - -} diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts index fe20e750a839..e69de29bb2d1 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts @@ -1,667 +0,0 @@ -// 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 {canConsumeForm, isCodeInRange} from '../util'; -import {SecurityAuthentication} from '../auth/auth'; - - -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 pet Pet object that needs to be added to the store - */ - public async addPet(pet: Pet, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'pet' is not null or undefined - if (pet === null || pet === undefined) { - throw new RequiredError("PetApi", "addPet", "pet"); - } - - - // Path Params - const localVarPath = '/pet'; - - // Make Request Context - const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); - requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") - - - // Body Params - const contentType = ObjectSerializer.getPreferredMediaType([ - "application/json", - - "application/xml" - ]); - requestContext.setHeaderParam("Content-Type", contentType); - const serializedBody = ObjectSerializer.stringify( - ObjectSerializer.serialize(pet, "Pet", ""), - contentType - ); - requestContext.setBody(serializedBody); - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default - if (defaultAuth?.applySecurityAuthentication) { - await defaultAuth?.applySecurityAuthentication(requestContext); - } - - return requestContext; - } - - /** - * Deletes a pet - * @param petId Pet id to delete - * @param apiKey - */ - public async deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'petId' is not null or undefined - if (petId === null || petId === undefined) { - throw new RequiredError("PetApi", "deletePet", "petId"); - } - - - - // 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, */*;q=0.8") - - // Header Params - requestContext.setHeaderParam("api_key", ObjectSerializer.serialize(apiKey, "string", "")); - - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default - if (defaultAuth?.applySecurityAuthentication) { - await defaultAuth?.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 async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'status' is not null or undefined - if (status === null || status === undefined) { - throw new RequiredError("PetApi", "findPetsByStatus", "status"); - } - - - // Path Params - const localVarPath = '/pet/findByStatus'; - - // Make Request Context - const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); - requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") - - // Query Params - if (status !== undefined) { - requestContext.setQueryParam("status", ObjectSerializer.serialize(status, "Array<'available' | 'pending' | 'sold'>", "")); - } - - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default - if (defaultAuth?.applySecurityAuthentication) { - await defaultAuth?.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 async findPetsByTags(tags: Array, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'tags' is not null or undefined - if (tags === null || tags === undefined) { - throw new RequiredError("PetApi", "findPetsByTags", "tags"); - } - - - // Path Params - const localVarPath = '/pet/findByTags'; - - // Make Request Context - const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); - requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") - - // Query Params - if (tags !== undefined) { - requestContext.setQueryParam("tags", ObjectSerializer.serialize(tags, "Array", "")); - } - - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default - if (defaultAuth?.applySecurityAuthentication) { - await defaultAuth?.applySecurityAuthentication(requestContext); - } - - return requestContext; - } - - /** - * Returns a single pet - * Find pet by ID - * @param petId ID of pet to return - */ - public async getPetById(petId: number, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'petId' is not null or undefined - if (petId === null || petId === undefined) { - throw new RequiredError("PetApi", "getPetById", "petId"); - } - - - // 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, */*;q=0.8") - - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["api_key"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default - if (defaultAuth?.applySecurityAuthentication) { - await defaultAuth?.applySecurityAuthentication(requestContext); - } - - return requestContext; - } - - /** - * Update an existing pet - * @param pet Pet object that needs to be added to the store - */ - public async updatePet(pet: Pet, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'pet' is not null or undefined - if (pet === null || pet === undefined) { - throw new RequiredError("PetApi", "updatePet", "pet"); - } - - - // Path Params - const localVarPath = '/pet'; - - // Make Request Context - const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); - requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") - - - // Body Params - const contentType = ObjectSerializer.getPreferredMediaType([ - "application/json", - - "application/xml" - ]); - requestContext.setHeaderParam("Content-Type", contentType); - const serializedBody = ObjectSerializer.stringify( - ObjectSerializer.serialize(pet, "Pet", ""), - contentType - ); - requestContext.setBody(serializedBody); - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default - if (defaultAuth?.applySecurityAuthentication) { - await defaultAuth?.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 async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'petId' is not null or undefined - if (petId === null || petId === undefined) { - throw new RequiredError("PetApi", "updatePetWithForm", "petId"); - } - - - - - // 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, */*;q=0.8") - - // Form Params - const useForm = canConsumeForm([ - 'application/x-www-form-urlencoded', - ]); - - let localVarFormParams - if (useForm) { - localVarFormParams = new FormData(); - } else { - localVarFormParams = new URLSearchParams(); - } - - 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); - - if(!useForm) { - const contentType = ObjectSerializer.getPreferredMediaType([ - "application/x-www-form-urlencoded" - ]); - requestContext.setHeaderParam("Content-Type", contentType); - } - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default - if (defaultAuth?.applySecurityAuthentication) { - await defaultAuth?.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 async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { - let _config = _options || this.configuration; - - // verify required parameter 'petId' is not null or undefined - if (petId === null || petId === undefined) { - throw new RequiredError("PetApi", "uploadFile", "petId"); - } - - - - - // 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, */*;q=0.8") - - // Form Params - const useForm = canConsumeForm([ - 'multipart/form-data', - ]); - - let localVarFormParams - if (useForm) { - localVarFormParams = new FormData(); - } else { - localVarFormParams = new URLSearchParams(); - } - - if (additionalMetadata !== undefined) { - // TODO: replace .append with .set - localVarFormParams.append('additionalMetadata', additionalMetadata as any); - } - if (file !== undefined) { - // TODO: replace .append with .set - if (localVarFormParams instanceof FormData) { - localVarFormParams.append('file', file, file.name); - } - } - - requestContext.setBody(localVarFormParams); - - if(!useForm) { - const contentType = ObjectSerializer.getPreferredMediaType([ - "multipart/form-data" - ]); - requestContext.setHeaderParam("Content-Type", contentType); - } - - let authMethod: SecurityAuthentication | undefined; - // Apply auth methods - authMethod = _config.authMethods["petstore_auth"] - if (authMethod?.applySecurityAuthentication) { - await authMethod?.applySecurityAuthentication(requestContext); - } - - const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default - if (defaultAuth?.applySecurityAuthentication) { - await defaultAuth?.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 addPet - * @throws ApiException if the response code was not in [200, 299] - */ - public async addPet(response: ResponseContext): Promise { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - if (isCodeInRange("405", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid input", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 deletePet - * @throws ApiException if the response code was not in [200, 299] - */ - public async deletePet(response: ResponseContext): Promise< void> { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid pet value", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - return; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 findPetsByStatus - * @throws ApiException if the response code was not in [200, 299] - */ - public async findPetsByStatus(response: ResponseContext): Promise > { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Array = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Array", "" - ) as Array; - return body; - } - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid status value", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Array = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Array", "" - ) as Array; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 findPetsByTags - * @throws ApiException if the response code was not in [200, 299] - */ - public async findPetsByTags(response: ResponseContext): Promise > { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Array = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Array", "" - ) as Array; - return body; - } - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid tag value", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Array = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Array", "" - ) as Array; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 getPetById - * @throws ApiException if the response code was not in [200, 299] - */ - public async getPetById(response: ResponseContext): Promise { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid ID supplied", undefined, response.headers); - } - if (isCodeInRange("404", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Pet not found", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 updatePet - * @throws ApiException if the response code was not in [200, 299] - */ - public async updatePet(response: ResponseContext): Promise { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - if (isCodeInRange("400", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid ID supplied", undefined, response.headers); - } - if (isCodeInRange("404", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Pet not found", undefined, response.headers); - } - if (isCodeInRange("405", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Validation exception", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: Pet = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "Pet", "" - ) as Pet; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 updatePetWithForm - * @throws ApiException if the response code was not in [200, 299] - */ - public async updatePetWithForm(response: ResponseContext): Promise< void> { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("405", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Invalid input", undefined, response.headers); - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - return; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - - /** - * 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 uploadFile - * @throws ApiException if the response code was not in [200, 299] - */ - public async uploadFile(response: ResponseContext): Promise { - const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); - if (isCodeInRange("200", response.httpStatusCode)) { - const body: ApiResponse = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "ApiResponse", "" - ) as ApiResponse; - return body; - } - - // Work around for missing responses in specification, e.g. for petstore.yaml - if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { - const body: ApiResponse = ObjectSerializer.deserialize( - ObjectSerializer.parse(await response.body.text(), contentType), - "ApiResponse", "" - ) as ApiResponse; - return body; - } - - throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); - } - -} diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/git_push.sh b/samples/openapi3/client/petstore/typescript/builds/object_params/git_push.sh index b253029754ed..e69de29bb2d1 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/git_push.sh +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/git_push.sh @@ -1,51 +0,0 @@ -#!/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-petstore-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' From c1c11f9e4357ea1d32b75159ef1a168e3a6cf943 Mon Sep 17 00:00:00 2001 From: David Gamero Date: Tue, 25 Jan 2022 14:35:33 -0500 Subject: [PATCH 6/8] samples again --- .../PetstoreClient/Configuration.swift | 14 ----- .../git_push.sh | 57 +++++++++++++++++++ .../package.json | 30 ---------- .../builds/enum/models/StringEnum.ts | 37 ------------ 4 files changed, 57 insertions(+), 81 deletions(-) diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Configuration.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Configuration.swift index db8707ad7a7f..e69de29bb2d1 100644 --- a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Configuration.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Configuration.swift @@ -1,14 +0,0 @@ -// Configuration.swift -// -// Generated by openapi-generator -// https://openapi-generator.tech -// - -import Foundation -import Vapor - -open class Configuration { - public static var apiClient: Vapor.Client? = nil - public static var apiWrapper: (inout Vapor.ClientRequest) throws -> () = { _ in } - public static var contentConfiguration = ContentConfiguration.default() -} diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/git_push.sh b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/git_push.sh index e69de29bb2d1..f53a75d4fabe 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/git_push.sh +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/git_push.sh @@ -0,0 +1,57 @@ +#!/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-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +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://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${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://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json index 86412c07b3db..e69de29bb2d1 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json @@ -1,30 +0,0 @@ -{ - "name": "@openapitools/typescript-axios-petstore", - "version": "1.0.0", - "description": "OpenAPI client for @openapitools/typescript-axios-petstore", - "author": "OpenAPI-Generator Contributors", - "keywords": [ - "axios", - "typescript", - "openapi-client", - "openapi-generator", - "@openapitools/typescript-axios-petstore" - ], - "license": "Unlicense", - "main": "./dist/index.js", - "typings": "./dist/index.d.ts", - "scripts": { - "build": "tsc --outDir dist/", - "prepare": "npm run build" - }, - "dependencies": { - "axios": "^0.21.4" - }, - "devDependencies": { - "@types/node": "^12.11.5", - "typescript": "^3.6.4" - }, - "publishConfig": { - "registry": "https://skimdb.npmjs.com/registry" - } -} diff --git a/samples/client/petstore/typescript-fetch/builds/enum/models/StringEnum.ts b/samples/client/petstore/typescript-fetch/builds/enum/models/StringEnum.ts index 8c984c44ba86..e69de29bb2d1 100644 --- a/samples/client/petstore/typescript-fetch/builds/enum/models/StringEnum.ts +++ b/samples/client/petstore/typescript-fetch/builds/enum/models/StringEnum.ts @@ -1,37 +0,0 @@ -/* tslint:disable */ -/* eslint-disable */ -/** - * Enum test - * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) - * - * The version of the OpenAPI document: 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. - */ - -/** - * - * @export - * @enum {string} - */ -export enum StringEnum { - One = 'one', - Two = 'two', - Three = 'three' -} - -export function StringEnumFromJSON(json: any): StringEnum { - return StringEnumFromJSONTyped(json, false); -} - -export function StringEnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): StringEnum { - return json as StringEnum; -} - -export function StringEnumToJSON(value?: StringEnum | null): any { - return value as any; -} - From 23a0d74ceeef3aed5f5e5fdacebcab0b6d40ecd3 Mon Sep 17 00:00:00 2001 From: David Gamero Date: Tue, 25 Jan 2022 14:44:46 -0500 Subject: [PATCH 7/8] samples --- .../resources/typescript/http/http.mustache | 4 +- .../PetstoreClient/Configuration.swift | 14 + .../package.json | 30 + .../with-single-request-parameters/.gitignore | 4 + .../builds/default/apis/PetApi.ts | 189 ++++- .../builds/enum/models/StringEnum.ts | 37 + .../builds/es6-target/src/apis/PetApi.ts | 189 ++++- .../builds/composed-schemas/http/http.ts | 10 - .../composed-schemas/http/isomorphic-fetch.ts | 1 - .../typescript/builds/default/apis/PetApi.ts | 67 +- .../typescript/builds/default/http/http.ts | 4 +- .../typescript/builds/deno/apis/PetApi.ts | 452 +++++++++++- .../typescript/builds/deno/http/http.ts | 10 - .../builds/deno/http/isomorphic-fetch.ts | 1 - .../builds/inversify/apis/PetApi.ts | 640 +++++++++++++++++ .../typescript/builds/inversify/http/http.ts | 4 +- .../typescript/builds/jquery/apis/PetApi.ts | 667 ++++++++++++++++++ .../typescript/builds/jquery/http/http.ts | 10 - .../builds/object_params/git_push.sh | 51 ++ .../builds/object_params/http/http.ts | 4 +- 20 files changed, 2344 insertions(+), 44 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/typescript/http/http.mustache b/modules/openapi-generator/src/main/resources/typescript/http/http.mustache index 1731c1c23432..011e67a862fb 100644 --- a/modules/openapi-generator/src/main/resources/typescript/http/http.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/http/http.mustache @@ -202,8 +202,8 @@ export class RequestContext { public getAgent(): http.Agent | https.Agent | undefined { return this.agent; } - {{#node}} - {{#platforms}} + {{/node}} + {{/platforms}} } export interface ResponseBody { diff --git a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Configuration.swift b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Configuration.swift index e69de29bb2d1..db8707ad7a7f 100644 --- a/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Configuration.swift +++ b/samples/client/petstore/swift5/vaporLibrary/Sources/PetstoreClient/Configuration.swift @@ -0,0 +1,14 @@ +// Configuration.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +import Vapor + +open class Configuration { + public static var apiClient: Vapor.Client? = nil + public static var apiWrapper: (inout Vapor.ClientRequest) throws -> () = { _ in } + public static var contentConfiguration = ContentConfiguration.default() +} diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json index e69de29bb2d1..86412c07b3db 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json @@ -0,0 +1,30 @@ +{ + "name": "@openapitools/typescript-axios-petstore", + "version": "1.0.0", + "description": "OpenAPI client for @openapitools/typescript-axios-petstore", + "author": "OpenAPI-Generator Contributors", + "keywords": [ + "axios", + "typescript", + "openapi-client", + "openapi-generator", + "@openapitools/typescript-axios-petstore" + ], + "license": "Unlicense", + "main": "./dist/index.js", + "typings": "./dist/index.d.ts", + "scripts": { + "build": "tsc --outDir dist/", + "prepare": "npm run build" + }, + "dependencies": { + "axios": "^0.21.4" + }, + "devDependencies": { + "@types/node": "^12.11.5", + "typescript": "^3.6.4" + }, + "publishConfig": { + "registry": "https://skimdb.npmjs.com/registry" + } +} diff --git a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.gitignore b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.gitignore index e69de29bb2d1..149b57654723 100644 --- a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.gitignore +++ b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/petstore/typescript-fetch/builds/default/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/default/apis/PetApi.ts index 232d4b3f1fa3..e4ddf7e853a0 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/apis/PetApi.ts @@ -235,4 +235,191 @@ export class PetApi extends runtime.BaseAPI { const headerParameters: runtime.HTTPHeaders = {}; - if (this.configuration && this.configuration.api \ No newline at end of file + if (this.configuration && this.configuration.apiKey) { + headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication + } + + const response = await this.request({ + path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => PetFromJSON(jsonValue)); + } + + /** + * Returns a single pet + * Find pet by ID + */ + async getPetById(requestParameters: GetPetByIdRequest, initOverrides?: RequestInit): Promise { + const response = await this.getPetByIdRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Update an existing pet + */ + async updatePetRaw(requestParameters: UpdatePetRequest, initOverrides?: RequestInit): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updatePet.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const response = await this.request({ + path: `/pet`, + method: 'PUT', + headers: headerParameters, + query: queryParameters, + body: PetToJSON(requestParameters.body), + }, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Update an existing pet + */ + async updatePet(requestParameters: UpdatePetRequest, initOverrides?: RequestInit): Promise { + await this.updatePetRaw(requestParameters, initOverrides); + } + + /** + * Updates a pet in the store with form data + */ + async updatePetWithFormRaw(requestParameters: UpdatePetWithFormRequest, initOverrides?: RequestInit): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling updatePetWithForm.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const consumes: runtime.Consume[] = [ + { contentType: 'application/x-www-form-urlencoded' }, + ]; + // @ts-ignore: canConsumeForm may be unused + const canConsumeForm = runtime.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): any }; + let useForm = false; + if (useForm) { + formParams = new FormData(); + } else { + formParams = new URLSearchParams(); + } + + if (requestParameters.name !== undefined) { + formParams.append('name', requestParameters.name as any); + } + + if (requestParameters.status !== undefined) { + formParams.append('status', requestParameters.status as any); + } + + const response = await this.request({ + path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: formParams, + }, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Updates a pet in the store with form data + */ + async updatePetWithForm(requestParameters: UpdatePetWithFormRequest, initOverrides?: RequestInit): Promise { + await this.updatePetWithFormRaw(requestParameters, initOverrides); + } + + /** + * uploads an image + */ + async uploadFileRaw(requestParameters: UploadFileRequest, initOverrides?: RequestInit): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling uploadFile.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const consumes: runtime.Consume[] = [ + { contentType: 'multipart/form-data' }, + ]; + // @ts-ignore: canConsumeForm may be unused + const canConsumeForm = runtime.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): any }; + let useForm = false; + // use FormData to transmit files using content-type "multipart/form-data" + useForm = canConsumeForm; + if (useForm) { + formParams = new FormData(); + } else { + formParams = new URLSearchParams(); + } + + if (requestParameters.additionalMetadata !== undefined) { + formParams.append('additionalMetadata', requestParameters.additionalMetadata as any); + } + + if (requestParameters.file !== undefined) { + formParams.append('file', requestParameters.file as any); + } + + const response = await this.request({ + path: `/pet/{petId}/uploadImage`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: formParams, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => ModelApiResponseFromJSON(jsonValue)); + } + + /** + * uploads an image + */ + async uploadFile(requestParameters: UploadFileRequest, initOverrides?: RequestInit): Promise { + const response = await this.uploadFileRaw(requestParameters, initOverrides); + return await response.value(); + } + +} + +/** + * @export + * @enum {string} + */ +export enum FindPetsByStatusStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} diff --git a/samples/client/petstore/typescript-fetch/builds/enum/models/StringEnum.ts b/samples/client/petstore/typescript-fetch/builds/enum/models/StringEnum.ts index e69de29bb2d1..8c984c44ba86 100644 --- a/samples/client/petstore/typescript-fetch/builds/enum/models/StringEnum.ts +++ b/samples/client/petstore/typescript-fetch/builds/enum/models/StringEnum.ts @@ -0,0 +1,37 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Enum test + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 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. + */ + +/** + * + * @export + * @enum {string} + */ +export enum StringEnum { + One = 'one', + Two = 'two', + Three = 'three' +} + +export function StringEnumFromJSON(json: any): StringEnum { + return StringEnumFromJSONTyped(json, false); +} + +export function StringEnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): StringEnum { + return json as StringEnum; +} + +export function StringEnumToJSON(value?: StringEnum | null): any { + return value as any; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/src/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/src/apis/PetApi.ts index 232d4b3f1fa3..e4ddf7e853a0 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/src/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/src/apis/PetApi.ts @@ -235,4 +235,191 @@ export class PetApi extends runtime.BaseAPI { const headerParameters: runtime.HTTPHeaders = {}; - if (this.configuration && this.configuration.api \ No newline at end of file + if (this.configuration && this.configuration.apiKey) { + headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication + } + + const response = await this.request({ + path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => PetFromJSON(jsonValue)); + } + + /** + * Returns a single pet + * Find pet by ID + */ + async getPetById(requestParameters: GetPetByIdRequest, initOverrides?: RequestInit): Promise { + const response = await this.getPetByIdRaw(requestParameters, initOverrides); + return await response.value(); + } + + /** + * Update an existing pet + */ + async updatePetRaw(requestParameters: UpdatePetRequest, initOverrides?: RequestInit): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updatePet.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const response = await this.request({ + path: `/pet`, + method: 'PUT', + headers: headerParameters, + query: queryParameters, + body: PetToJSON(requestParameters.body), + }, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Update an existing pet + */ + async updatePet(requestParameters: UpdatePetRequest, initOverrides?: RequestInit): Promise { + await this.updatePetRaw(requestParameters, initOverrides); + } + + /** + * Updates a pet in the store with form data + */ + async updatePetWithFormRaw(requestParameters: UpdatePetWithFormRequest, initOverrides?: RequestInit): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling updatePetWithForm.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const consumes: runtime.Consume[] = [ + { contentType: 'application/x-www-form-urlencoded' }, + ]; + // @ts-ignore: canConsumeForm may be unused + const canConsumeForm = runtime.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): any }; + let useForm = false; + if (useForm) { + formParams = new FormData(); + } else { + formParams = new URLSearchParams(); + } + + if (requestParameters.name !== undefined) { + formParams.append('name', requestParameters.name as any); + } + + if (requestParameters.status !== undefined) { + formParams.append('status', requestParameters.status as any); + } + + const response = await this.request({ + path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: formParams, + }, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Updates a pet in the store with form data + */ + async updatePetWithForm(requestParameters: UpdatePetWithFormRequest, initOverrides?: RequestInit): Promise { + await this.updatePetWithFormRaw(requestParameters, initOverrides); + } + + /** + * uploads an image + */ + async uploadFileRaw(requestParameters: UploadFileRequest, initOverrides?: RequestInit): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling uploadFile.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } + + const consumes: runtime.Consume[] = [ + { contentType: 'multipart/form-data' }, + ]; + // @ts-ignore: canConsumeForm may be unused + const canConsumeForm = runtime.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): any }; + let useForm = false; + // use FormData to transmit files using content-type "multipart/form-data" + useForm = canConsumeForm; + if (useForm) { + formParams = new FormData(); + } else { + formParams = new URLSearchParams(); + } + + if (requestParameters.additionalMetadata !== undefined) { + formParams.append('additionalMetadata', requestParameters.additionalMetadata as any); + } + + if (requestParameters.file !== undefined) { + formParams.append('file', requestParameters.file as any); + } + + const response = await this.request({ + path: `/pet/{petId}/uploadImage`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: formParams, + }, initOverrides); + + return new runtime.JSONApiResponse(response, (jsonValue) => ModelApiResponseFromJSON(jsonValue)); + } + + /** + * uploads an image + */ + async uploadFile(requestParameters: UploadFileRequest, initOverrides?: RequestInit): Promise { + const response = await this.uploadFileRaw(requestParameters, initOverrides); + return await response.value(); + } + +} + +/** + * @export + * @enum {string} + */ +export enum FindPetsByStatusStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/http.ts index 473c679e5697..02aa71eb57f7 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/http.ts @@ -2,8 +2,6 @@ // @ts-ignore import * as URLParse from "url-parse"; import { Observable, from } from '../rxjsStub'; -import * as http from 'http'; -import * as https from 'https'; export * from './isomorphic-fetch'; @@ -46,7 +44,6 @@ export class RequestContext { private headers: { [key: string]: string } = {}; private body: RequestBody = undefined; private url: URLParse; - private agent: http.Agent | https.Agent | undefined = undefined; /** * Creates the request context using a http method and request resource url @@ -120,13 +117,6 @@ export class RequestContext { this.headers[key] = value; } - public setAgent(agent: http.Agent | https.Agent) { - this.agent = agent; - } - - public getAgent(): http.Agent | https.Agent | undefined { - return this.agent; - } } export interface ResponseBody { diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/isomorphic-fetch.ts b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/isomorphic-fetch.ts index 80c114d36daf..3af85f3d902c 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/isomorphic-fetch.ts +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/isomorphic-fetch.ts @@ -12,7 +12,6 @@ export class IsomorphicFetchHttpLibrary implements HttpLibrary { method: method, body: body as any, headers: request.getHeaders(), - agent: request.getAgent(), credentials: "same-origin" }).then((resp: any) => { const headers: { [name: string]: string } = {}; diff --git a/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts index 9808bc699fa8..e85797baebc1 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/apis/PetApi.ts @@ -601,4 +601,69 @@ export class PetApiResponseProcessor { throw new ApiException(response.httpStatusCode, "Pet not found", undefined, response.headers); } if (isCodeInRange("405", response.httpStatusCode)) { - throw new ApiException(response.httpStatusCode, "Val \ No newline at end of file + throw new ApiException(response.httpStatusCode, "Validation exception", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 updatePetWithForm + * @throws ApiException if the response code was not in [200, 299] + */ + public async updatePetWithForm(response: ResponseContext): Promise< void> { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("405", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid input", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 uploadFile + * @throws ApiException if the response code was not in [200, 299] + */ + public async uploadFile(response: ResponseContext): Promise { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: ApiResponse = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "ApiResponse", "" + ) as ApiResponse; + return body; + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: ApiResponse = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "ApiResponse", "" + ) as ApiResponse; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + +} diff --git a/samples/openapi3/client/petstore/typescript/builds/default/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/default/http/http.ts index d4e5df9191dc..4c5ea2a918ba 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/http/http.ts @@ -1,12 +1,12 @@ // TODO: evaluate if we can easily get rid of this library import * as FormData from "form-data"; import { URLSearchParams } from 'url'; +import * as http from 'http'; +import * as https from 'https'; // typings of url-parse are incorrect... // @ts-ignore import * as URLParse from "url-parse"; import { Observable, from } from '../rxjsStub'; -import * as http from 'http'; -import * as https from 'https'; export * from './isomorphic-fetch'; diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts index 456e4fa2b7a3..f11b208baf24 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/apis/PetApi.ts @@ -214,4 +214,454 @@ export class PetApiRequestFactory extends BaseAPIRequestFactory { requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") - let authMethod: SecurityAuth \ No newline at end of file + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["api_key"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default + if (defaultAuth?.applySecurityAuthentication) { + await defaultAuth?.applySecurityAuthentication(requestContext); + } + + return requestContext; + } + + /** + * Update an existing pet + * @param pet Pet object that needs to be added to the store + */ + public async updatePet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'pet' is not null or undefined + if (pet === null || pet === undefined) { + throw new RequiredError("PetApi", "updatePet", "pet"); + } + + + // Path Params + const localVarPath = '/pet'; + + // Make Request Context + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") + + + // Body Params + const contentType = ObjectSerializer.getPreferredMediaType([ + "application/json", + + "application/xml" + ]); + requestContext.setHeaderParam("Content-Type", contentType); + const serializedBody = ObjectSerializer.stringify( + ObjectSerializer.serialize(pet, "Pet", ""), + contentType + ); + requestContext.setBody(serializedBody); + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default + if (defaultAuth?.applySecurityAuthentication) { + await defaultAuth?.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 async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError("PetApi", "updatePetWithForm", "petId"); + } + + + + + // 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, */*;q=0.8") + + // Form Params + const useForm = canConsumeForm([ + 'application/x-www-form-urlencoded', + ]); + + let localVarFormParams + if (useForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new URLSearchParams(); + } + + 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); + + if(!useForm) { + const contentType = ObjectSerializer.getPreferredMediaType([ + "application/x-www-form-urlencoded" + ]); + requestContext.setHeaderParam("Content-Type", contentType); + } + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default + if (defaultAuth?.applySecurityAuthentication) { + await defaultAuth?.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 async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError("PetApi", "uploadFile", "petId"); + } + + + + + // 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, */*;q=0.8") + + // Form Params + const useForm = canConsumeForm([ + 'multipart/form-data', + ]); + + let localVarFormParams + if (useForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new URLSearchParams(); + } + + if (additionalMetadata !== undefined) { + // TODO: replace .append with .set + localVarFormParams.append('additionalMetadata', additionalMetadata as any); + } + if (file !== undefined) { + // TODO: replace .append with .set + if (localVarFormParams instanceof FormData) { + localVarFormParams.append('file', file, file.name); + } + } + + requestContext.setBody(localVarFormParams); + + if(!useForm) { + const contentType = ObjectSerializer.getPreferredMediaType([ + "multipart/form-data" + ]); + requestContext.setHeaderParam("Content-Type", contentType); + } + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default + if (defaultAuth?.applySecurityAuthentication) { + await defaultAuth?.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 addPet + * @throws ApiException if the response code was not in [200, 299] + */ + public async addPet(response: ResponseContext): Promise { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + if (isCodeInRange("405", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid input", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 deletePet + * @throws ApiException if the response code was not in [200, 299] + */ + public async deletePet(response: ResponseContext): Promise< void> { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid pet value", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 findPetsByStatus + * @throws ApiException if the response code was not in [200, 299] + */ + public async findPetsByStatus(response: ResponseContext): Promise > { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Array = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Array", "" + ) as Array; + return body; + } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid status value", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Array = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Array", "" + ) as Array; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 findPetsByTags + * @throws ApiException if the response code was not in [200, 299] + */ + public async findPetsByTags(response: ResponseContext): Promise > { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Array = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Array", "" + ) as Array; + return body; + } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid tag value", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Array = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Array", "" + ) as Array; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 getPetById + * @throws ApiException if the response code was not in [200, 299] + */ + public async getPetById(response: ResponseContext): Promise { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid ID supplied", undefined, response.headers); + } + if (isCodeInRange("404", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Pet not found", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 updatePet + * @throws ApiException if the response code was not in [200, 299] + */ + public async updatePet(response: ResponseContext): Promise { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid ID supplied", undefined, response.headers); + } + if (isCodeInRange("404", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Pet not found", undefined, response.headers); + } + if (isCodeInRange("405", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Validation exception", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 updatePetWithForm + * @throws ApiException if the response code was not in [200, 299] + */ + public async updatePetWithForm(response: ResponseContext): Promise< void> { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("405", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid input", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 uploadFile + * @throws ApiException if the response code was not in [200, 299] + */ + public async uploadFile(response: ResponseContext): Promise { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: ApiResponse = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "ApiResponse", "" + ) as ApiResponse; + return body; + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: ApiResponse = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "ApiResponse", "" + ) as ApiResponse; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + +} diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/deno/http/http.ts index 46539f64ef44..065cd703c506 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/http/http.ts @@ -1,6 +1,4 @@ import { Observable, from } from '../rxjsStub.ts'; -import * as http from 'http'; -import * as https from 'https'; /** @@ -75,7 +73,6 @@ export class RequestContext { private headers: { [key: string]: string } = {}; private body: RequestBody = undefined; private url: URLParse; - private agent: http.Agent | https.Agent | undefined = undefined; /** * Creates the request context using a http method and request resource url @@ -149,13 +146,6 @@ export class RequestContext { this.headers[key] = value; } - public setAgent(agent: http.Agent | https.Agent) { - this.agent = agent; - } - - public getAgent(): http.Agent | https.Agent | undefined { - return this.agent; - } } export interface ResponseBody { diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/http/isomorphic-fetch.ts b/samples/openapi3/client/petstore/typescript/builds/deno/http/isomorphic-fetch.ts index 450533765e60..a7521351e065 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/http/isomorphic-fetch.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/http/isomorphic-fetch.ts @@ -11,7 +11,6 @@ export class IsomorphicFetchHttpLibrary implements HttpLibrary { method: method, body: body as any, headers: request.getHeaders(), - agent: request.getAgent(), }).then((resp: any) => { const headers: { [name: string]: string } = {}; resp.headers.forEach((value: string, name: string) => { diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts index e69de29bb2d1..81a75d96bcec 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/apis/PetApi.ts @@ -0,0 +1,640 @@ +// 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 { URLSearchParams } from 'url'; +import {ObjectSerializer} from '../models/ObjectSerializer'; +import {ApiException} from './exception'; +import {canConsumeForm, isCodeInRange} from '../util'; +import {SecurityAuthentication} from '../auth/auth'; + +import { injectable } from "inversify"; + +import { ApiResponse } from '../models/ApiResponse'; +import { Pet } from '../models/Pet'; + +/** + * no description + */ +@injectable() +export class PetApiRequestFactory extends BaseAPIRequestFactory { + + /** + * Add a new pet to the store + * @param pet Pet object that needs to be added to the store + */ + public async addPet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'pet' is not null or undefined + if (pet === null || pet === undefined) { + throw new RequiredError("PetApi", "addPet", "pet"); + } + + + // Path Params + const localVarPath = '/pet'; + + // Make Request Context + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") + + + // Body Params + const contentType = ObjectSerializer.getPreferredMediaType([ + "application/json", + + "application/xml" + ]); + requestContext.setHeaderParam("Content-Type", contentType); + const serializedBody = ObjectSerializer.stringify( + ObjectSerializer.serialize(pet, "Pet", ""), + contentType + ); + requestContext.setBody(serializedBody); + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + + return requestContext; + } + + /** + * Deletes a pet + * @param petId Pet id to delete + * @param apiKey + */ + public async deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError("PetApi", "deletePet", "petId"); + } + + + + // 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, */*;q=0.8") + + // Header Params + requestContext.setHeaderParam("api_key", ObjectSerializer.serialize(apiKey, "string", "")); + + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await 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 async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'status' is not null or undefined + if (status === null || status === undefined) { + throw new RequiredError("PetApi", "findPetsByStatus", "status"); + } + + + // Path Params + const localVarPath = '/pet/findByStatus'; + + // Make Request Context + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") + + // Query Params + if (status !== undefined) { + requestContext.setQueryParam("status", ObjectSerializer.serialize(status, "Array<'available' | 'pending' | 'sold'>", "")); + } + + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await 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 async findPetsByTags(tags: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'tags' is not null or undefined + if (tags === null || tags === undefined) { + throw new RequiredError("PetApi", "findPetsByTags", "tags"); + } + + + // Path Params + const localVarPath = '/pet/findByTags'; + + // Make Request Context + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") + + // Query Params + if (tags !== undefined) { + requestContext.setQueryParam("tags", ObjectSerializer.serialize(tags, "Array", "")); + } + + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + + return requestContext; + } + + /** + * Returns a single pet + * Find pet by ID + * @param petId ID of pet to return + */ + public async getPetById(petId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError("PetApi", "getPetById", "petId"); + } + + + // 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, */*;q=0.8") + + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["api_key"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + + return requestContext; + } + + /** + * Update an existing pet + * @param pet Pet object that needs to be added to the store + */ + public async updatePet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'pet' is not null or undefined + if (pet === null || pet === undefined) { + throw new RequiredError("PetApi", "updatePet", "pet"); + } + + + // Path Params + const localVarPath = '/pet'; + + // Make Request Context + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") + + + // Body Params + const contentType = ObjectSerializer.getPreferredMediaType([ + "application/json", + + "application/xml" + ]); + requestContext.setHeaderParam("Content-Type", contentType); + const serializedBody = ObjectSerializer.stringify( + ObjectSerializer.serialize(pet, "Pet", ""), + contentType + ); + requestContext.setBody(serializedBody); + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await 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 async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError("PetApi", "updatePetWithForm", "petId"); + } + + + + + // 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, */*;q=0.8") + + // Form Params + const useForm = canConsumeForm([ + 'application/x-www-form-urlencoded', + ]); + + let localVarFormParams + if (useForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new URLSearchParams(); + } + + 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); + + if(!useForm) { + const contentType = ObjectSerializer.getPreferredMediaType([ + "application/x-www-form-urlencoded" + ]); + requestContext.setHeaderParam("Content-Type", contentType); + } + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await 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 async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError("PetApi", "uploadFile", "petId"); + } + + + + + // 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, */*;q=0.8") + + // Form Params + const useForm = canConsumeForm([ + 'multipart/form-data', + ]); + + let localVarFormParams + if (useForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new URLSearchParams(); + } + + if (additionalMetadata !== undefined) { + // TODO: replace .append with .set + localVarFormParams.append('additionalMetadata', additionalMetadata as any); + } + if (file !== undefined) { + // TODO: replace .append with .set + if (localVarFormParams instanceof FormData) { + localVarFormParams.append('file', file.data, file.name); + } + } + + requestContext.setBody(localVarFormParams); + + if(!useForm) { + const contentType = ObjectSerializer.getPreferredMediaType([ + "multipart/form-data" + ]); + requestContext.setHeaderParam("Content-Type", contentType); + } + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + + return requestContext; + } + +} + +@injectable() +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 addPet + * @throws ApiException if the response code was not in [200, 299] + */ + public async addPet(response: ResponseContext): Promise { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + if (isCodeInRange("405", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid input", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 deletePet + * @throws ApiException if the response code was not in [200, 299] + */ + public async deletePet(response: ResponseContext): Promise< void> { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid pet value", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 findPetsByStatus + * @throws ApiException if the response code was not in [200, 299] + */ + public async findPetsByStatus(response: ResponseContext): Promise > { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Array = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Array", "" + ) as Array; + return body; + } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid status value", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Array = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Array", "" + ) as Array; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 findPetsByTags + * @throws ApiException if the response code was not in [200, 299] + */ + public async findPetsByTags(response: ResponseContext): Promise > { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Array = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Array", "" + ) as Array; + return body; + } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid tag value", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Array = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Array", "" + ) as Array; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 getPetById + * @throws ApiException if the response code was not in [200, 299] + */ + public async getPetById(response: ResponseContext): Promise { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid ID supplied", undefined, response.headers); + } + if (isCodeInRange("404", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Pet not found", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 updatePet + * @throws ApiException if the response code was not in [200, 299] + */ + public async updatePet(response: ResponseContext): Promise { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid ID supplied", undefined, response.headers); + } + if (isCodeInRange("404", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Pet not found", undefined, response.headers); + } + if (isCodeInRange("405", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Validation exception", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 updatePetWithForm + * @throws ApiException if the response code was not in [200, 299] + */ + public async updatePetWithForm(response: ResponseContext): Promise< void> { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("405", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid input", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 uploadFile + * @throws ApiException if the response code was not in [200, 299] + */ + public async uploadFile(response: ResponseContext): Promise { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: ApiResponse = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "ApiResponse", "" + ) as ApiResponse; + return body; + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: ApiResponse = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "ApiResponse", "" + ) as ApiResponse; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + +} diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/http/http.ts index d4e5df9191dc..4c5ea2a918ba 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/http/http.ts @@ -1,12 +1,12 @@ // TODO: evaluate if we can easily get rid of this library import * as FormData from "form-data"; import { URLSearchParams } from 'url'; +import * as http from 'http'; +import * as https from 'https'; // typings of url-parse are incorrect... // @ts-ignore import * as URLParse from "url-parse"; import { Observable, from } from '../rxjsStub'; -import * as http from 'http'; -import * as https from 'https'; export * from './isomorphic-fetch'; diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts index e69de29bb2d1..fe20e750a839 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/apis/PetApi.ts @@ -0,0 +1,667 @@ +// 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 {canConsumeForm, isCodeInRange} from '../util'; +import {SecurityAuthentication} from '../auth/auth'; + + +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 pet Pet object that needs to be added to the store + */ + public async addPet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'pet' is not null or undefined + if (pet === null || pet === undefined) { + throw new RequiredError("PetApi", "addPet", "pet"); + } + + + // Path Params + const localVarPath = '/pet'; + + // Make Request Context + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.POST); + requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") + + + // Body Params + const contentType = ObjectSerializer.getPreferredMediaType([ + "application/json", + + "application/xml" + ]); + requestContext.setHeaderParam("Content-Type", contentType); + const serializedBody = ObjectSerializer.stringify( + ObjectSerializer.serialize(pet, "Pet", ""), + contentType + ); + requestContext.setBody(serializedBody); + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default + if (defaultAuth?.applySecurityAuthentication) { + await defaultAuth?.applySecurityAuthentication(requestContext); + } + + return requestContext; + } + + /** + * Deletes a pet + * @param petId Pet id to delete + * @param apiKey + */ + public async deletePet(petId: number, apiKey?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError("PetApi", "deletePet", "petId"); + } + + + + // 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, */*;q=0.8") + + // Header Params + requestContext.setHeaderParam("api_key", ObjectSerializer.serialize(apiKey, "string", "")); + + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default + if (defaultAuth?.applySecurityAuthentication) { + await defaultAuth?.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 async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'status' is not null or undefined + if (status === null || status === undefined) { + throw new RequiredError("PetApi", "findPetsByStatus", "status"); + } + + + // Path Params + const localVarPath = '/pet/findByStatus'; + + // Make Request Context + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") + + // Query Params + if (status !== undefined) { + requestContext.setQueryParam("status", ObjectSerializer.serialize(status, "Array<'available' | 'pending' | 'sold'>", "")); + } + + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default + if (defaultAuth?.applySecurityAuthentication) { + await defaultAuth?.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 async findPetsByTags(tags: Array, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'tags' is not null or undefined + if (tags === null || tags === undefined) { + throw new RequiredError("PetApi", "findPetsByTags", "tags"); + } + + + // Path Params + const localVarPath = '/pet/findByTags'; + + // Make Request Context + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.GET); + requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") + + // Query Params + if (tags !== undefined) { + requestContext.setQueryParam("tags", ObjectSerializer.serialize(tags, "Array", "")); + } + + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default + if (defaultAuth?.applySecurityAuthentication) { + await defaultAuth?.applySecurityAuthentication(requestContext); + } + + return requestContext; + } + + /** + * Returns a single pet + * Find pet by ID + * @param petId ID of pet to return + */ + public async getPetById(petId: number, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError("PetApi", "getPetById", "petId"); + } + + + // 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, */*;q=0.8") + + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["api_key"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default + if (defaultAuth?.applySecurityAuthentication) { + await defaultAuth?.applySecurityAuthentication(requestContext); + } + + return requestContext; + } + + /** + * Update an existing pet + * @param pet Pet object that needs to be added to the store + */ + public async updatePet(pet: Pet, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'pet' is not null or undefined + if (pet === null || pet === undefined) { + throw new RequiredError("PetApi", "updatePet", "pet"); + } + + + // Path Params + const localVarPath = '/pet'; + + // Make Request Context + const requestContext = _config.baseServer.makeRequestContext(localVarPath, HttpMethod.PUT); + requestContext.setHeaderParam("Accept", "application/json, */*;q=0.8") + + + // Body Params + const contentType = ObjectSerializer.getPreferredMediaType([ + "application/json", + + "application/xml" + ]); + requestContext.setHeaderParam("Content-Type", contentType); + const serializedBody = ObjectSerializer.stringify( + ObjectSerializer.serialize(pet, "Pet", ""), + contentType + ); + requestContext.setBody(serializedBody); + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default + if (defaultAuth?.applySecurityAuthentication) { + await defaultAuth?.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 async updatePetWithForm(petId: number, name?: string, status?: string, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError("PetApi", "updatePetWithForm", "petId"); + } + + + + + // 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, */*;q=0.8") + + // Form Params + const useForm = canConsumeForm([ + 'application/x-www-form-urlencoded', + ]); + + let localVarFormParams + if (useForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new URLSearchParams(); + } + + 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); + + if(!useForm) { + const contentType = ObjectSerializer.getPreferredMediaType([ + "application/x-www-form-urlencoded" + ]); + requestContext.setHeaderParam("Content-Type", contentType); + } + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default + if (defaultAuth?.applySecurityAuthentication) { + await defaultAuth?.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 async uploadFile(petId: number, additionalMetadata?: string, file?: HttpFile, _options?: Configuration): Promise { + let _config = _options || this.configuration; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new RequiredError("PetApi", "uploadFile", "petId"); + } + + + + + // 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, */*;q=0.8") + + // Form Params + const useForm = canConsumeForm([ + 'multipart/form-data', + ]); + + let localVarFormParams + if (useForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new URLSearchParams(); + } + + if (additionalMetadata !== undefined) { + // TODO: replace .append with .set + localVarFormParams.append('additionalMetadata', additionalMetadata as any); + } + if (file !== undefined) { + // TODO: replace .append with .set + if (localVarFormParams instanceof FormData) { + localVarFormParams.append('file', file, file.name); + } + } + + requestContext.setBody(localVarFormParams); + + if(!useForm) { + const contentType = ObjectSerializer.getPreferredMediaType([ + "multipart/form-data" + ]); + requestContext.setHeaderParam("Content-Type", contentType); + } + + let authMethod: SecurityAuthentication | undefined; + // Apply auth methods + authMethod = _config.authMethods["petstore_auth"] + if (authMethod?.applySecurityAuthentication) { + await authMethod?.applySecurityAuthentication(requestContext); + } + + const defaultAuth: SecurityAuthentication | undefined = _options?.authMethods?.default || this.configuration?.authMethods?.default + if (defaultAuth?.applySecurityAuthentication) { + await defaultAuth?.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 addPet + * @throws ApiException if the response code was not in [200, 299] + */ + public async addPet(response: ResponseContext): Promise { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + if (isCodeInRange("405", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid input", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 deletePet + * @throws ApiException if the response code was not in [200, 299] + */ + public async deletePet(response: ResponseContext): Promise< void> { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid pet value", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 findPetsByStatus + * @throws ApiException if the response code was not in [200, 299] + */ + public async findPetsByStatus(response: ResponseContext): Promise > { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Array = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Array", "" + ) as Array; + return body; + } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid status value", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Array = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Array", "" + ) as Array; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 findPetsByTags + * @throws ApiException if the response code was not in [200, 299] + */ + public async findPetsByTags(response: ResponseContext): Promise > { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Array = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Array", "" + ) as Array; + return body; + } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid tag value", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Array = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Array", "" + ) as Array; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 getPetById + * @throws ApiException if the response code was not in [200, 299] + */ + public async getPetById(response: ResponseContext): Promise { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid ID supplied", undefined, response.headers); + } + if (isCodeInRange("404", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Pet not found", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 updatePet + * @throws ApiException if the response code was not in [200, 299] + */ + public async updatePet(response: ResponseContext): Promise { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + if (isCodeInRange("400", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid ID supplied", undefined, response.headers); + } + if (isCodeInRange("404", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Pet not found", undefined, response.headers); + } + if (isCodeInRange("405", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Validation exception", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: Pet = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "Pet", "" + ) as Pet; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 updatePetWithForm + * @throws ApiException if the response code was not in [200, 299] + */ + public async updatePetWithForm(response: ResponseContext): Promise< void> { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("405", response.httpStatusCode)) { + throw new ApiException(response.httpStatusCode, "Invalid input", undefined, response.headers); + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + return; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + + /** + * 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 uploadFile + * @throws ApiException if the response code was not in [200, 299] + */ + public async uploadFile(response: ResponseContext): Promise { + const contentType = ObjectSerializer.normalizeMediaType(response.headers["content-type"]); + if (isCodeInRange("200", response.httpStatusCode)) { + const body: ApiResponse = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "ApiResponse", "" + ) as ApiResponse; + return body; + } + + // Work around for missing responses in specification, e.g. for petstore.yaml + if (response.httpStatusCode >= 200 && response.httpStatusCode <= 299) { + const body: ApiResponse = ObjectSerializer.deserialize( + ObjectSerializer.parse(await response.body.text(), contentType), + "ApiResponse", "" + ) as ApiResponse; + return body; + } + + throw new ApiException(response.httpStatusCode, "Unknown API Status Code!", await response.getBodyAsAny(), response.headers); + } + +} diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/http/http.ts index cc443163f0e1..7a793dda2956 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/http/http.ts @@ -2,8 +2,6 @@ // @ts-ignore import * as URLParse from "url-parse"; import { Observable, from } from '../rxjsStub'; -import * as http from 'http'; -import * as https from 'https'; export * from './jquery'; @@ -46,7 +44,6 @@ export class RequestContext { private headers: { [key: string]: string } = {}; private body: RequestBody = undefined; private url: URLParse; - private agent: http.Agent | https.Agent | undefined = undefined; /** * Creates the request context using a http method and request resource url @@ -120,13 +117,6 @@ export class RequestContext { this.headers[key] = value; } - public setAgent(agent: http.Agent | https.Agent) { - this.agent = agent; - } - - public getAgent(): http.Agent | https.Agent | undefined { - return this.agent; - } } export interface ResponseBody { diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/git_push.sh b/samples/openapi3/client/petstore/typescript/builds/object_params/git_push.sh index e69de29bb2d1..b253029754ed 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/git_push.sh +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/git_push.sh @@ -0,0 +1,51 @@ +#!/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-petstore-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' diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/http/http.ts index d4e5df9191dc..4c5ea2a918ba 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/http/http.ts @@ -1,12 +1,12 @@ // TODO: evaluate if we can easily get rid of this library import * as FormData from "form-data"; import { URLSearchParams } from 'url'; +import * as http from 'http'; +import * as https from 'https'; // typings of url-parse are incorrect... // @ts-ignore import * as URLParse from "url-parse"; import { Observable, from } from '../rxjsStub'; -import * as http from 'http'; -import * as https from 'https'; export * from './isomorphic-fetch'; From 1761da7a6c2b539490d78c93bbf22b1e41558d60 Mon Sep 17 00:00:00 2001 From: David Gamero Date: Tue, 25 Jan 2022 14:49:28 -0500 Subject: [PATCH 8/8] samples once more --- .../src/main/resources/typescript/http/http.mustache | 2 +- .../petstore/typescript/builds/composed-schemas/http/http.ts | 1 - .../client/petstore/typescript/builds/default/http/http.ts | 2 +- .../client/petstore/typescript/builds/deno/http/http.ts | 1 - .../client/petstore/typescript/builds/inversify/http/http.ts | 2 +- .../client/petstore/typescript/builds/jquery/http/http.ts | 1 - .../petstore/typescript/builds/object_params/http/http.ts | 2 +- 7 files changed, 4 insertions(+), 7 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/typescript/http/http.mustache b/modules/openapi-generator/src/main/resources/typescript/http/http.mustache index 011e67a862fb..2f66d4b8996e 100644 --- a/modules/openapi-generator/src/main/resources/typescript/http/http.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/http/http.mustache @@ -192,9 +192,9 @@ export class RequestContext { public setHeaderParam(key: string, value: string): void { this.headers[key] = value; } - {{#platforms}} {{#node}} + public setAgent(agent: http.Agent | https.Agent) { this.agent = agent; } diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/http.ts index 02aa71eb57f7..f19e206b19ff 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/http/http.ts @@ -116,7 +116,6 @@ export class RequestContext { public setHeaderParam(key: string, value: string): void { this.headers[key] = value; } - } export interface ResponseBody { diff --git a/samples/openapi3/client/petstore/typescript/builds/default/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/default/http/http.ts index 4c5ea2a918ba..3b6e1461d924 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/http/http.ts @@ -125,7 +125,7 @@ export class RequestContext { public setHeaderParam(key: string, value: string): void { this.headers[key] = value; } - + public setAgent(agent: http.Agent | https.Agent) { this.agent = agent; } diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/deno/http/http.ts index 065cd703c506..139149cec973 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/http/http.ts @@ -145,7 +145,6 @@ export class RequestContext { public setHeaderParam(key: string, value: string): void { this.headers[key] = value; } - } export interface ResponseBody { diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/http/http.ts index 4c5ea2a918ba..3b6e1461d924 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/http/http.ts @@ -125,7 +125,7 @@ export class RequestContext { public setHeaderParam(key: string, value: string): void { this.headers[key] = value; } - + public setAgent(agent: http.Agent | https.Agent) { this.agent = agent; } diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/http/http.ts index 7a793dda2956..4b9ef54beeb5 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/http/http.ts @@ -116,7 +116,6 @@ export class RequestContext { public setHeaderParam(key: string, value: string): void { this.headers[key] = value; } - } export interface ResponseBody { diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/http/http.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/http/http.ts index 4c5ea2a918ba..3b6e1461d924 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/http/http.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/http/http.ts @@ -125,7 +125,7 @@ export class RequestContext { public setHeaderParam(key: string, value: string): void { this.headers[key] = value; } - + public setAgent(agent: http.Agent | https.Agent) { this.agent = agent; }