From 6914e2be590b53783965f83caa8d82ffdf9de8ff Mon Sep 17 00:00:00 2001 From: Uladzimir_Paliukhovich Date: Fri, 5 Jan 2024 11:47:12 +0300 Subject: [PATCH] Development (#705) * Fixed some issues * formatted code * updated SDK * Updated SDK and version * Fixed generation of lists of classes * Fixed generation $Items classes * Updated pubspec and changelog * Fixed #524 * Fixed #598 Generation of query enum parameters * Fixed conflicts * Fixed some issues in swaggers * Updated changelog and pubspec * Fix #583, #637, #619 and update readme (#638) * fix #583 and update readme * fix #637 * fix #619 * Fixed generation of some fields * Removed test * Fixed classes named List * Fixed generation of query parameters with ref default type * Fixed generation of DateTime parameters * Fixed generation of responses in some cases * Some fixes * Updated changelog and pubspec * Implemented not nullable fields * Fixed tests * fixed generation of some swaggers * Added ability to return String values * Returned main.dart content * Updated pubspec and changelog * Fixed generation of required and not required fields * Added check for object ref in body * Fixed some things * Fixed tests * Fixed tests * Fixed some things * Updated changelog and pubspec * Removed not needed lines in tests * Fixed generation of nullable responses * Added generation of DateTime * Updated pubspec and changelog * Fixed tests * Fixed #669 Generation models from content schema allof * Fixed #665 generation putIfAbsent for response from content schema * Fixed generation of nullable and required properties * Fixed tests * Fixed some stuff related to nullable properties * Updated changelog and pubspec * Formatted code * Formatted code * Fixed tests * Fixed generation of some enums inside classes * Implemented support of exploded parameters * Pushed constants file * Fixed generation of allOf for request bodies * Implemented overriden_models functionality * Improved overriden models logic * Fixed tests * Updated pubspec and changelog * Removed support of exploded parameters * Fixed generation of patameters contains keywords * Updated pubspec and changelog * Fixed generation of nullable and not nullable fields * Fixed generation of list parameters with specific names * Fixed formurlencoded requests * Revert "Fixed formurlencoded requests" This reverts commit d103118975e7f66ec2cbf10a1f9d28ef935be6eb. * Updated changelog and pubspec * formatted code * Fixed version in changelog * Added generation of writeOnly and readOnly fields as nullable and no required (Issue 487) * Fixed generatino of DateTime query parameters (Issue 536) * Updated pubspec and changelog * Fixed generation in some cases * Added ability to rename downloaded files * Updated example * Implemented support of deprecated fields annotations * Added support of deprecated requests annotations * Fixed tests, updated pubspec and changelog * Fixed putIfAbsent for allOf schemas #700 * Fixed tests * Implemented new build option * Some fixes * Implemented new generator option * Updated changelog, readme and pubspec * Fixed conflicts --------- Co-authored-by: Uladzimir Paliukhovich Co-authored-by: Romain --- CHANGELOG.md | 4 + README.md | 1 + example/input_folder/pet_service_json.json | 1036 ++++++++++++++++ example/input_folder/some_file_name.json | 1037 +--------------- .../pet_service_json.swagger.dart | 1047 ----------------- .../pet_service_swagger.swagger.dart | 2 + .../pet_service_yaml.swagger.dart | 2 + .../some_file_name.swagger.dart | 2 + lib/src/code_generators/constants.dart | 6 - .../swagger_enums_generator.dart | 23 +- .../swagger_requests_generator.dart | 89 +- lib/src/models/generator_options.dart | 4 + lib/src/models/generator_options.g2.dart | 3 + pubspec.yaml | 2 +- 14 files changed, 1120 insertions(+), 2138 deletions(-) create mode 100644 example/input_folder/pet_service_json.json delete mode 100644 example/lib/swagger_generated_code/pet_service_json.swagger.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e954bcc..eefda9b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 2.14.2 + +* Added option `generate_first_succeed_response` to generate first succeed response or `dynamic` ([#703](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/703)) + # 2.14.1 * ***Breaking*** Added ability to rename downloaded swagger files ([#558](https://github.com/epam-cross-platform-lab/swagger-dart-code-generator/issues/558)) diff --git a/README.md b/README.md index 36b32d1c..4d178e6c 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,7 @@ targets: | `add_base_path_to_requests` | `false` | `false` | Add swagger base path to all request path. | | `multipart_file_type` | `List` | `false` | Allow to override the generated class for multipart file (See #605). | | `override_to_string` | `bool` | `true` | Overrides `toString()` method using `jsonEncode(this)` | +| `generate_first_succeed_response` | `bool` | `true` | If request has multiple success responses, first one will be generated. Otherwice - `dynamic` | diff --git a/example/input_folder/pet_service_json.json b/example/input_folder/pet_service_json.json new file mode 100644 index 00000000..1c5db9ab --- /dev/null +++ b/example/input_folder/pet_service_json.json @@ -0,0 +1,1036 @@ +{ + "swagger": "2.0", + "info": { + "description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", + "version": "1.0.0", + "title": "Swagger Petstore", + "termsOfService": "http://swagger.io/terms/", + "contact": { + "email": "apiteam@swagger.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host": "petstore.swagger.io", + "basePath": "/v2", + "tags": [ + { + "name": "pet", + "description": "Everything about your Pets", + "externalDocs": { + "description": "Find out more", + "url": "http://swagger.io" + } + }, + { + "name": "store", + "description": "Access to Petstore orders" + }, + { + "name": "user", + "description": "Operations about user", + "externalDocs": { + "description": "Find out more about our store", + "url": "http://swagger.io" + } + } + ], + "schemes": [ + "https", + "http" + ], + "paths": { + "/pet": { + "post": { + "tags": [ + "pet" + ], + "summary": "Add a new pet to the store", + "description": "", + "operationId": "addPet", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": true, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "put": { + "tags": [ + "pet" + ], + "summary": "Update an existing pet", + "description": "", + "operationId": "updatePet", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": true, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + }, + "405": { + "description": "Validation exception" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByStatus": { + "get": { + "tags": [ + "pet" + ], + "summary": "Finds Pets by status", + "description": "Multiple status values can be provided with comma separated strings", + "operationId": "findPetsByStatus", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "status", + "in": "query", + "description": "Status values that need to be considered for filter", + "required": true, + "type": "array", + "items": { + "type": "string", + "enum": [ + "available", + "pending", + "sold" + ], + "default": "available" + }, + "collectionFormat": "multi" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid status value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByTags": { + "get": { + "tags": [ + "pet" + ], + "summary": "Finds Pets by tags", + "description": "Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId": "findPetsByTags", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "Tags to filter by", + "required": true, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid tag value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ], + "deprecated": true + } + }, + "/pet/{petId}": { + "get": { + "tags": [ + "pet" + ], + "summary": "Find pet by ID", + "description": "Returns a single pet", + "operationId": "getPetById", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to return", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + } + }, + "security": [ + { + "api_key": [] + } + ] + }, + "post": { + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "description": "", + "operationId": "updatePetWithForm", + "consumes": [ + "application/x-www-form-urlencoded" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "name", + "in": "formData", + "description": "Updated name of the pet", + "required": false, + "type": "string" + }, + { + "name": "status", + "in": "formData", + "description": "Updated status of the pet", + "required": false, + "type": "string" + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "delete": { + "tags": [ + "pet" + ], + "summary": "Deletes a pet", + "description": "", + "operationId": "deletePet", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "api_key", + "in": "header", + "required": false, + "type": "string" + }, + { + "name": "petId", + "in": "path", + "description": "Pet id to delete", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/{petId}/uploadImage": { + "post": { + "tags": [ + "pet" + ], + "summary": "uploads an image", + "description": "", + "operationId": "uploadFile", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to update", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "additionalMetadata", + "in": "formData", + "description": "Additional data to pass to server", + "required": false, + "type": "string" + }, + { + "name": "file", + "in": "formData", + "description": "file to upload", + "required": false, + "type": "file" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/ApiResponse" + } + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/store/inventory": { + "get": { + "tags": [ + "store" + ], + "summary": "Returns pet inventories by status", + "description": "Returns a map of status codes to quantities", + "operationId": "getInventory", + "produces": [ + "application/json" + ], + "parameters": [], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int32" + } + } + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/store/order": { + "post": { + "tags": [ + "store" + ], + "summary": "Place an order for a pet", + "description": "", + "operationId": "placeOrder", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "order placed for purchasing the pet", + "required": true, + "schema": { + "$ref": "#/definitions/Order" + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid Order" + } + } + } + }, + "/store/order/{orderId}": { + "get": { + "tags": [ + "store" + ], + "summary": "Find purchase order by ID", + "description": "For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions", + "operationId": "getOrderById", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "integer", + "maximum": 10, + "minimum": 1, + "format": "int64" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Order not found" + } + } + }, + "delete": { + "tags": [ + "store" + ], + "summary": "Delete purchase order by ID", + "description": "For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors", + "operationId": "deleteOrder", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of the order that needs to be deleted", + "required": true, + "type": "integer", + "minimum": 1, + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Order not found" + } + } + } + }, + "/user": { + "post": { + "tags": [ + "user" + ], + "summary": "Create user", + "description": "This can only be done by the logged in user.", + "operationId": "createUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Created user object", + "required": true, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithArray": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithArrayInput", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithList": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithListInput", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/login": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs user into the system", + "description": "", + "operationId": "loginUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "query", + "description": "The user name for login", + "required": true, + "type": "string" + }, + { + "name": "password", + "in": "query", + "description": "The password for login in clear text", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "string" + }, + "headers": { + "X-Rate-Limit": { + "type": "integer", + "format": "int32", + "description": "calls per hour allowed by the user" + }, + "X-Expires-After": { + "type": "string", + "format": "date-time", + "description": "date in UTC when token expires" + } + } + }, + "400": { + "description": "Invalid username/password supplied" + } + } + } + }, + "/user/logout": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs out current logged in user session", + "description": "", + "operationId": "logoutUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/{username}": { + "get": { + "tags": [ + "user" + ], + "summary": "Get user by user name", + "description": "", + "operationId": "getUserByName", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be fetched. Use user1 for testing. ", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/User" + } + }, + "400": { + "description": "Invalid username supplied" + }, + "404": { + "description": "User not found" + } + } + }, + "put": { + "tags": [ + "user" + ], + "summary": "Updated user", + "description": "This can only be done by the logged in user.", + "operationId": "updateUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "name that need to be updated", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "body", + "description": "Updated user object", + "required": true, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "400": { + "description": "Invalid user supplied" + }, + "404": { + "description": "User not found" + } + } + }, + "delete": { + "tags": [ + "user" + ], + "summary": "Delete user", + "description": "This can only be done by the logged in user.", + "operationId": "deleteUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "400": { + "description": "Invalid username supplied" + }, + "404": { + "description": "User not found" + } + } + } + } + }, + "securityDefinitions": { + "petstore_auth": { + "type": "oauth2", + "authorizationUrl": "http://petstore.swagger.io/oauth/dialog", + "flow": "implicit", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + }, + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + } + }, + "definitions": { + "Order": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "petId": { + "type": "integer", + "format": "int64" + }, + "quantity": { + "type": "integer", + "format": "int32" + }, + "shipDate": { + "type": "string", + "format": "date-time" + }, + "status": { + "type": "string", + "description": "Order Status", + "enum": [ + "placed", + "approved", + "delivered" + ] + }, + "complete": { + "type": "boolean", + "default": false + } + }, + "xml": { + "name": "Order" + } + }, + "Category": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Category" + } + }, + "User": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "username": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "email": { + "type": "string" + }, + "password": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "userStatus": { + "type": "integer", + "format": "int32", + "description": "User Status" + } + }, + "xml": { + "name": "User" + } + }, + "Tag": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Tag" + } + }, + "Pet": { + "type": "object", + "required": [ + "name", + "photoUrls" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "category": { + "$ref": "#/definitions/Category" + }, + "name": { + "type": "string", + "example": "doggie" + }, + "photoUrls": { + "type": "array", + "xml": { + "name": "photoUrl", + "wrapped": true + }, + "items": { + "type": "string" + } + }, + "tags": { + "type": "array", + "xml": { + "name": "tag", + "wrapped": true + }, + "items": { + "$ref": "#/definitions/Tag" + } + }, + "status": { + "type": "string", + "description": "pet status in the store", + "enum": [ + "available", + "pending", + "sold" + ] + } + }, + "xml": { + "name": "Pet" + } + }, + "ApiResponse": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "type": { + "type": "string" + }, + "message": { + "type": "string" + } + } + } + }, + "externalDocs": { + "description": "Find out more about Swagger", + "url": "http://swagger.io" + } +} \ No newline at end of file diff --git a/example/input_folder/some_file_name.json b/example/input_folder/some_file_name.json index ca1a8f69..1becba2b 100644 --- a/example/input_folder/some_file_name.json +++ b/example/input_folder/some_file_name.json @@ -1,1036 +1 @@ -{ - "swagger": "2.0", - "info": { - "description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", - "version": "1.0.0", - "title": "Swagger Petstore", - "termsOfService": "http://swagger.io/terms/", - "contact": { - "email": "apiteam@swagger.io" - }, - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - } - }, - "host": "petstore.swagger.io", - "basePath": "/v2", - "tags": [ - { - "name": "pet", - "description": "Everything about your Pets", - "externalDocs": { - "description": "Find out more", - "url": "http://swagger.io" - } - }, - { - "name": "store", - "description": "Access to Petstore orders" - }, - { - "name": "user", - "description": "Operations about user", - "externalDocs": { - "description": "Find out more about our store", - "url": "http://swagger.io" - } - } - ], - "schemes": [ - "https", - "http" - ], - "paths": { - "/pet": { - "post": { - "tags": [ - "pet" - ], - "summary": "Add a new pet to the store", - "description": "", - "operationId": "addPet", - "consumes": [ - "application/json", - "application/xml" - ], - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "in": "body", - "name": "body", - "description": "Pet object that needs to be added to the store", - "required": true, - "schema": { - "$ref": "#/definitions/Pet" - } - } - ], - "responses": { - "405": { - "description": "Invalid input" - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] - }, - "put": { - "tags": [ - "pet" - ], - "summary": "Update an existing pet", - "description": "", - "operationId": "updatePet", - "consumes": [ - "application/json", - "application/xml" - ], - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "in": "body", - "name": "body", - "description": "Pet object that needs to be added to the store", - "required": true, - "schema": { - "$ref": "#/definitions/Pet" - } - } - ], - "responses": { - "400": { - "description": "Invalid ID supplied" - }, - "404": { - "description": "Pet not found" - }, - "405": { - "description": "Validation exception" - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] - } - }, - "/pet/findByStatus": { - "get": { - "tags": [ - "pet" - ], - "summary": "Finds Pets by status", - "description": "Multiple status values can be provided with comma separated strings", - "operationId": "findPetsByStatus", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "status", - "in": "query", - "description": "Status values that need to be considered for filter", - "required": true, - "type": "array", - "items": { - "type": "string", - "enum": [ - "available", - "pending", - "sold" - ], - "default": "available" - }, - "collectionFormat": "multi" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Pet" - } - } - }, - "400": { - "description": "Invalid status value" - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] - } - }, - "/pet/findByTags": { - "get": { - "tags": [ - "pet" - ], - "summary": "Finds Pets by tags", - "description": "Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", - "operationId": "findPetsByTags", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "tags", - "in": "query", - "description": "Tags to filter by", - "required": true, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "multi" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Pet" - } - } - }, - "400": { - "description": "Invalid tag value" - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ], - "deprecated": true - } - }, - "/pet/{petId}": { - "get": { - "tags": [ - "pet" - ], - "summary": "Find pet by ID", - "description": "Returns a single pet", - "operationId": "getPetById", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet to return", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "400": { - "description": "Invalid ID supplied" - }, - "404": { - "description": "Pet not found" - } - }, - "security": [ - { - "api_key": [] - } - ] - }, - "post": { - "tags": [ - "pet" - ], - "summary": "Updates a pet in the store with form data", - "description": "", - "operationId": "updatePetWithForm", - "consumes": [ - "application/x-www-form-urlencoded" - ], - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet that needs to be updated", - "required": true, - "type": "integer", - "format": "int64" - }, - { - "name": "name", - "in": "formData", - "description": "Updated name of the pet", - "required": false, - "type": "string" - }, - { - "name": "status", - "in": "formData", - "description": "Updated status of the pet", - "required": false, - "type": "string" - } - ], - "responses": { - "405": { - "description": "Invalid input" - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] - }, - "delete": { - "tags": [ - "pet" - ], - "summary": "Deletes a pet", - "description": "", - "operationId": "deletePet", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "api_key", - "in": "header", - "required": false, - "type": "string" - }, - { - "name": "petId", - "in": "path", - "description": "Pet id to delete", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "400": { - "description": "Invalid ID supplied" - }, - "404": { - "description": "Pet not found" - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] - } - }, - "/pet/{petId}/uploadImage": { - "post": { - "tags": [ - "pet" - ], - "summary": "uploads an image", - "description": "", - "operationId": "uploadFile", - "consumes": [ - "multipart/form-data" - ], - "produces": [ - "application/json" - ], - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet to update", - "required": true, - "type": "integer", - "format": "int64" - }, - { - "name": "additionalMetadata", - "in": "formData", - "description": "Additional data to pass to server", - "required": false, - "type": "string" - }, - { - "name": "file", - "in": "formData", - "description": "file to upload", - "required": false, - "type": "file" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "$ref": "#/definitions/ApiResponse" - } - } - }, - "security": [ - { - "petstore_auth": [ - "write:pets", - "read:pets" - ] - } - ] - } - }, - "/store/inventory": { - "get": { - "tags": [ - "store" - ], - "summary": "Returns pet inventories by status", - "description": "Returns a map of status codes to quantities", - "operationId": "getInventory", - "produces": [ - "application/json" - ], - "parameters": [], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "type": "object", - "additionalProperties": { - "type": "integer", - "format": "int32" - } - } - } - }, - "security": [ - { - "api_key": [] - } - ] - } - }, - "/store/order": { - "post": { - "tags": [ - "store" - ], - "summary": "Place an order for a pet", - "description": "", - "operationId": "placeOrder", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "in": "body", - "name": "body", - "description": "order placed for purchasing the pet", - "required": true, - "schema": { - "$ref": "#/definitions/Order" - } - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "$ref": "#/definitions/Order" - } - }, - "400": { - "description": "Invalid Order" - } - } - } - }, - "/store/order/{orderId}": { - "get": { - "tags": [ - "store" - ], - "summary": "Find purchase order by ID", - "description": "For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions", - "operationId": "getOrderById", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "orderId", - "in": "path", - "description": "ID of pet that needs to be fetched", - "required": true, - "type": "integer", - "maximum": 10, - "minimum": 1, - "format": "int64" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "$ref": "#/definitions/Order" - } - }, - "400": { - "description": "Invalid ID supplied" - }, - "404": { - "description": "Order not found" - } - } - }, - "delete": { - "tags": [ - "store" - ], - "summary": "Delete purchase order by ID", - "description": "For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors", - "operationId": "deleteOrder", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "orderId", - "in": "path", - "description": "ID of the order that needs to be deleted", - "required": true, - "type": "integer", - "minimum": 1, - "format": "int64" - } - ], - "responses": { - "400": { - "description": "Invalid ID supplied" - }, - "404": { - "description": "Order not found" - } - } - } - }, - "/user": { - "post": { - "tags": [ - "user" - ], - "summary": "Create user", - "description": "This can only be done by the logged in user.", - "operationId": "createUser", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "in": "body", - "name": "body", - "description": "Created user object", - "required": true, - "schema": { - "$ref": "#/definitions/User" - } - } - ], - "responses": { - "default": { - "description": "successful operation" - } - } - } - }, - "/user/createWithArray": { - "post": { - "tags": [ - "user" - ], - "summary": "Creates list of users with given input array", - "description": "", - "operationId": "createUsersWithArrayInput", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "in": "body", - "name": "body", - "description": "List of user object", - "required": true, - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/User" - } - } - } - ], - "responses": { - "default": { - "description": "successful operation" - } - } - } - }, - "/user/createWithList": { - "post": { - "tags": [ - "user" - ], - "summary": "Creates list of users with given input array", - "description": "", - "operationId": "createUsersWithListInput", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "in": "body", - "name": "body", - "description": "List of user object", - "required": true, - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/User" - } - } - } - ], - "responses": { - "default": { - "description": "successful operation" - } - } - } - }, - "/user/login": { - "get": { - "tags": [ - "user" - ], - "summary": "Logs user into the system", - "description": "", - "operationId": "loginUser", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "username", - "in": "query", - "description": "The user name for login", - "required": true, - "type": "string" - }, - { - "name": "password", - "in": "query", - "description": "The password for login in clear text", - "required": true, - "type": "string" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "type": "string" - }, - "headers": { - "X-Rate-Limit": { - "type": "integer", - "format": "int32", - "description": "calls per hour allowed by the user" - }, - "X-Expires-After": { - "type": "string", - "format": "date-time", - "description": "date in UTC when token expires" - } - } - }, - "400": { - "description": "Invalid username/password supplied" - } - } - } - }, - "/user/logout": { - "get": { - "tags": [ - "user" - ], - "summary": "Logs out current logged in user session", - "description": "", - "operationId": "logoutUser", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [], - "responses": { - "default": { - "description": "successful operation" - } - } - } - }, - "/user/{username}": { - "get": { - "tags": [ - "user" - ], - "summary": "Get user by user name", - "description": "", - "operationId": "getUserByName", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "username", - "in": "path", - "description": "The name that needs to be fetched. Use user1 for testing. ", - "required": true, - "type": "string" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "$ref": "#/definitions/User" - } - }, - "400": { - "description": "Invalid username supplied" - }, - "404": { - "description": "User not found" - } - } - }, - "put": { - "tags": [ - "user" - ], - "summary": "Updated user", - "description": "This can only be done by the logged in user.", - "operationId": "updateUser", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "username", - "in": "path", - "description": "name that need to be updated", - "required": true, - "type": "string" - }, - { - "in": "body", - "name": "body", - "description": "Updated user object", - "required": true, - "schema": { - "$ref": "#/definitions/User" - } - } - ], - "responses": { - "400": { - "description": "Invalid user supplied" - }, - "404": { - "description": "User not found" - } - } - }, - "delete": { - "tags": [ - "user" - ], - "summary": "Delete user", - "description": "This can only be done by the logged in user.", - "operationId": "deleteUser", - "produces": [ - "application/xml", - "application/json" - ], - "parameters": [ - { - "name": "username", - "in": "path", - "description": "The name that needs to be deleted", - "required": true, - "type": "string" - } - ], - "responses": { - "400": { - "description": "Invalid username supplied" - }, - "404": { - "description": "User not found" - } - } - } - } - }, - "securityDefinitions": { - "petstore_auth": { - "type": "oauth2", - "authorizationUrl": "http://petstore.swagger.io/oauth/dialog", - "flow": "implicit", - "scopes": { - "write:pets": "modify pets in your account", - "read:pets": "read your pets" - } - }, - "api_key": { - "type": "apiKey", - "name": "api_key", - "in": "header" - } - }, - "definitions": { - "Order": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "petId": { - "type": "integer", - "format": "int64" - }, - "quantity": { - "type": "integer", - "format": "int32" - }, - "shipDate": { - "type": "string", - "format": "date-time" - }, - "status": { - "type": "string", - "description": "Order Status", - "enum": [ - "placed", - "approved", - "delivered" - ] - }, - "complete": { - "type": "boolean", - "default": false - } - }, - "xml": { - "name": "Order" - } - }, - "Category": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - }, - "xml": { - "name": "Category" - } - }, - "User": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "username": { - "type": "string" - }, - "firstName": { - "type": "string" - }, - "lastName": { - "type": "string" - }, - "email": { - "type": "string" - }, - "password": { - "type": "string" - }, - "phone": { - "type": "string" - }, - "userStatus": { - "type": "integer", - "format": "int32", - "description": "User Status" - } - }, - "xml": { - "name": "User" - } - }, - "Tag": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - }, - "xml": { - "name": "Tag" - } - }, - "Pet": { - "type": "object", - "required": [ - "name", - "photoUrls" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "category": { - "$ref": "#/definitions/Category" - }, - "name": { - "type": "string", - "example": "doggie" - }, - "photoUrls": { - "type": "array", - "xml": { - "name": "photoUrl", - "wrapped": true - }, - "items": { - "type": "string" - } - }, - "tags": { - "type": "array", - "xml": { - "name": "tag", - "wrapped": true - }, - "items": { - "$ref": "#/definitions/Tag" - } - }, - "status": { - "type": "string", - "description": "pet status in the store", - "enum": [ - "available", - "pending", - "sold" - ] - } - }, - "xml": { - "name": "Pet" - } - }, - "ApiResponse": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "type": { - "type": "string" - }, - "message": { - "type": "string" - } - } - } - }, - "externalDocs": { - "description": "Find out more about Swagger", - "url": "http://swagger.io" - } -} \ No newline at end of file +404: Not Found \ No newline at end of file diff --git a/example/lib/swagger_generated_code/pet_service_json.swagger.dart b/example/lib/swagger_generated_code/pet_service_json.swagger.dart deleted file mode 100644 index 1a51d210..00000000 --- a/example/lib/swagger_generated_code/pet_service_json.swagger.dart +++ /dev/null @@ -1,1047 +0,0 @@ -// ignore_for_file: type=lint - -import 'package:json_annotation/json_annotation.dart'; -import 'package:collection/collection.dart'; -import 'dart:convert'; - -import '../overriden_models.dart'; -import 'package:chopper/chopper.dart'; - -import 'client_mapping.dart'; -import 'dart:async'; -import 'package:http/http.dart' as http; -import 'package:http/http.dart' show MultipartFile; -import 'package:chopper/chopper.dart' as chopper; -import 'pet_service_json.enums.swagger.dart' as enums; -export 'pet_service_json.enums.swagger.dart'; - -part 'pet_service_json.swagger.chopper.dart'; -part 'pet_service_json.swagger.g.dart'; - -// ************************************************************************** -// SwaggerChopperGenerator -// ************************************************************************** - -@ChopperApi() -abstract class PetServiceJson extends ChopperService { - static PetServiceJson create({ - ChopperClient? client, - http.Client? httpClient, - Authenticator? authenticator, - ErrorConverter? errorConverter, - Converter? converter, - Uri? baseUrl, - Iterable? interceptors, - }) { - if (client != null) { - return _$PetServiceJson(client); - } - - final newClient = ChopperClient( - services: [_$PetServiceJson()], - converter: converter ?? $JsonSerializableConverter(), - interceptors: interceptors ?? [], - client: httpClient, - authenticator: authenticator, - errorConverter: errorConverter, - baseUrl: baseUrl ?? Uri.parse('http://petstore.swagger.io/v2')); - return _$PetServiceJson(newClient); - } - - ///Add a new pet to the store - ///@param body Pet object that needs to be added to the store - Future petPost({ - required Pet? body, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - - return _petPost(body: body, cacheControl: cacheControl?.toString()); - } - - ///Add a new pet to the store - ///@param body Pet object that needs to be added to the store - @Post(path: '/pet') - Future _petPost({ - @Body() required Pet? body, - @Header('Cache-Control') String? cacheControl, - }); - - ///Update an existing pet - ///@param body Pet object that needs to be added to the store - Future petPut({ - required Pet? body, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - - return _petPut(body: body, cacheControl: cacheControl?.toString()); - } - - ///Update an existing pet - ///@param body Pet object that needs to be added to the store - @Put(path: '/pet') - Future _petPut({ - @Body() required Pet? body, - @Header('Cache-Control') String? cacheControl, - }); - - ///Finds Pets by status - ///@param status Status values that need to be considered for filter - Future>> petFindByStatusGet({ - required List? status, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - - return _petFindByStatusGet( - status: petFindByStatusGetStatusListToJson(status), - cacheControl: cacheControl?.toString()); - } - - ///Finds Pets by status - ///@param status Status values that need to be considered for filter - @Get(path: '/pet/findByStatus') - Future>> _petFindByStatusGet({ - @Query('status') required List? status, - @Header('Cache-Control') String? cacheControl, - }); - - ///Finds Pets by tags - ///@param tags Tags to filter by - Future>> petFindByTagsGet({ - required List? tags, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - - return _petFindByTagsGet( - tags: tags, cacheControl: cacheControl?.toString()); - } - - ///Finds Pets by tags - ///@param tags Tags to filter by - @Get(path: '/pet/findByTags') - Future>> _petFindByTagsGet({ - @Query('tags') required List? tags, - @Header('Cache-Control') String? cacheControl, - }); - - ///Find pet by ID - ///@param petId ID of pet to return - Future> petPetIdGet({ - required int? petId, - dynamic apiKey, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(Pet, () => Pet.fromJsonFactory); - - return _petPetIdGet( - petId: petId, - apiKey: apiKey?.toString(), - cacheControl: cacheControl?.toString()); - } - - ///Find pet by ID - ///@param petId ID of pet to return - @Get(path: '/pet/{petId}') - Future> _petPetIdGet({ - @Path('petId') required int? petId, - @Header('api_key') String? apiKey, - @Header('Cache-Control') String? cacheControl, - }); - - ///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 - Future petPetIdPost({ - required int? petId, - String? name, - String? status, - dynamic cacheControl, - }) { - return _petPetIdPost( - petId: petId, - name: name, - status: status, - cacheControl: cacheControl?.toString()); - } - - ///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 - @Post( - path: '/pet/{petId}', - optionalBody: true, - ) - Future _petPetIdPost({ - @Path('petId') required int? petId, - @Field('name') String? name, - @Field('status') String? status, - @Header('Cache-Control') String? cacheControl, - }); - - ///Deletes a pet - ///@param api_key - ///@param petId Pet id to delete - Future petPetIdDelete({ - String? apiKey, - required int? petId, - dynamic cacheControl, - }) { - return _petPetIdDelete( - apiKey: apiKey?.toString(), - petId: petId, - cacheControl: cacheControl?.toString()); - } - - ///Deletes a pet - ///@param api_key - ///@param petId Pet id to delete - @Delete(path: '/pet/{petId}') - Future _petPetIdDelete({ - @Header('api_key') String? apiKey, - @Path('petId') required int? petId, - @Header('Cache-Control') String? cacheControl, - }); - - ///uploads an image - ///@param petId ID of pet to update - ///@param additionalMetadata Additional data to pass to server - ///@param file file to upload - Future> petPetIdUploadImagePost({ - required int? petId, - String? additionalMetadata, - List? file, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent( - ApiResponse, () => ApiResponse.fromJsonFactory); - - return _petPetIdUploadImagePost( - petId: petId, - additionalMetadata: additionalMetadata, - file: file, - cacheControl: cacheControl?.toString()); - } - - ///uploads an image - ///@param petId ID of pet to update - ///@param additionalMetadata Additional data to pass to server - ///@param file file to upload - @Post( - path: '/pet/{petId}/uploadImage', - optionalBody: true, - ) - Future> _petPetIdUploadImagePost({ - @Path('petId') required int? petId, - @Field('additionalMetadata') String? additionalMetadata, - @Field('file') List? file, - @Header('Cache-Control') String? cacheControl, - }); - - ///Returns pet inventories by status - Future> storeInventoryGet({ - dynamic apiKey, - dynamic cacheControl, - }) { - return _storeInventoryGet( - apiKey: apiKey?.toString(), cacheControl: cacheControl?.toString()); - } - - ///Returns pet inventories by status - @Get(path: '/store/inventory') - Future> _storeInventoryGet({ - @Header('api_key') String? apiKey, - @Header('Cache-Control') String? cacheControl, - }); - - ///Place an order for a pet - ///@param body order placed for purchasing the pet - Future> storeOrderPost({ - required Order? body, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(Order, () => Order.fromJsonFactory); - - return _storeOrderPost(body: body, cacheControl: cacheControl?.toString()); - } - - ///Place an order for a pet - ///@param body order placed for purchasing the pet - @Post(path: '/store/order') - Future> _storeOrderPost({ - @Body() required Order? body, - @Header('Cache-Control') String? cacheControl, - }); - - ///Find purchase order by ID - ///@param orderId ID of pet that needs to be fetched - Future> storeOrderOrderIdGet({ - required int? orderId, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(Order, () => Order.fromJsonFactory); - - return _storeOrderOrderIdGet( - orderId: orderId, cacheControl: cacheControl?.toString()); - } - - ///Find purchase order by ID - ///@param orderId ID of pet that needs to be fetched - @Get(path: '/store/order/{orderId}') - Future> _storeOrderOrderIdGet({ - @Path('orderId') required int? orderId, - @Header('Cache-Control') String? cacheControl, - }); - - ///Delete purchase order by ID - ///@param orderId ID of the order that needs to be deleted - Future storeOrderOrderIdDelete({ - required int? orderId, - dynamic cacheControl, - }) { - return _storeOrderOrderIdDelete( - orderId: orderId, cacheControl: cacheControl?.toString()); - } - - ///Delete purchase order by ID - ///@param orderId ID of the order that needs to be deleted - @Delete(path: '/store/order/{orderId}') - Future _storeOrderOrderIdDelete({ - @Path('orderId') required int? orderId, - @Header('Cache-Control') String? cacheControl, - }); - - ///Create user - ///@param body Created user object - Future userPost({ - required User? body, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); - - return _userPost(body: body, cacheControl: cacheControl?.toString()); - } - - ///Create user - ///@param body Created user object - @Post(path: '/user') - Future _userPost({ - @Body() required User? body, - @Header('Cache-Control') String? cacheControl, - }); - - ///Creates list of users with given input array - ///@param body List of user object - Future userCreateWithArrayPost({ - required List? body, - dynamic cacheControl, - }) { - return _userCreateWithArrayPost( - body: body, cacheControl: cacheControl?.toString()); - } - - ///Creates list of users with given input array - ///@param body List of user object - @Post(path: '/user/createWithArray') - Future _userCreateWithArrayPost({ - @Body() required List? body, - @Header('Cache-Control') String? cacheControl, - }); - - ///Creates list of users with given input array - ///@param body List of user object - Future userCreateWithListPost({ - required List? body, - dynamic cacheControl, - }) { - return _userCreateWithListPost( - body: body, cacheControl: cacheControl?.toString()); - } - - ///Creates list of users with given input array - ///@param body List of user object - @Post(path: '/user/createWithList') - Future _userCreateWithListPost({ - @Body() required List? body, - @Header('Cache-Control') String? cacheControl, - }); - - ///Logs user into the system - ///@param username The user name for login - ///@param password The password for login in clear text - Future> userLoginGet({ - required String? username, - required String? password, - dynamic cacheControl, - }) { - return _userLoginGet( - username: username, - password: password, - cacheControl: cacheControl?.toString()); - } - - ///Logs user into the system - ///@param username The user name for login - ///@param password The password for login in clear text - @Get(path: '/user/login') - Future> _userLoginGet({ - @Query('username') required String? username, - @Query('password') required String? password, - @Header('Cache-Control') String? cacheControl, - }); - - ///Logs out current logged in user session - Future userLogoutGet({dynamic cacheControl}) { - return _userLogoutGet(cacheControl: cacheControl?.toString()); - } - - ///Logs out current logged in user session - @Get(path: '/user/logout') - Future _userLogoutGet( - {@Header('Cache-Control') String? cacheControl}); - - ///Get user by user name - ///@param username The name that needs to be fetched. Use user1 for testing. - Future> userUsernameGet({ - required String? username, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); - - return _userUsernameGet( - username: username, cacheControl: cacheControl?.toString()); - } - - ///Get user by user name - ///@param username The name that needs to be fetched. Use user1 for testing. - @Get(path: '/user/{username}') - Future> _userUsernameGet({ - @Path('username') required String? username, - @Header('Cache-Control') String? cacheControl, - }); - - ///Updated user - ///@param username name that need to be updated - ///@param body Updated user object - Future userUsernamePut({ - required String? username, - required User? body, - dynamic cacheControl, - }) { - generatedMapping.putIfAbsent(User, () => User.fromJsonFactory); - - return _userUsernamePut( - username: username, body: body, cacheControl: cacheControl?.toString()); - } - - ///Updated user - ///@param username name that need to be updated - ///@param body Updated user object - @Put(path: '/user/{username}') - Future _userUsernamePut({ - @Path('username') required String? username, - @Body() required User? body, - @Header('Cache-Control') String? cacheControl, - }); - - ///Delete user - ///@param username The name that needs to be deleted - Future userUsernameDelete({ - required String? username, - dynamic cacheControl, - }) { - return _userUsernameDelete( - username: username, cacheControl: cacheControl?.toString()); - } - - ///Delete user - ///@param username The name that needs to be deleted - @Delete(path: '/user/{username}') - Future _userUsernameDelete({ - @Path('username') required String? username, - @Header('Cache-Control') String? cacheControl, - }); -} - -@JsonSerializable(explicitToJson: true) -class Category { - const Category({ - this.id, - this.name, - }); - - factory Category.fromJson(Map json) => - _$CategoryFromJson(json); - - static const toJsonFactory = _$CategoryToJson; - Map toJson() => _$CategoryToJson(this); - - @JsonKey(name: 'id', includeIfNull: false) - final int? id; - @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') - final String? name; - static const fromJsonFactory = _$CategoryFromJson; - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other is Category && - (identical(other.id, id) || - const DeepCollectionEquality().equals(other.id, id)) && - (identical(other.name, name) || - const DeepCollectionEquality().equals(other.name, name))); - } - - @override - String toString() => jsonEncode(this); - - @override - int get hashCode => - const DeepCollectionEquality().hash(id) ^ - const DeepCollectionEquality().hash(name) ^ - runtimeType.hashCode; -} - -extension $CategoryExtension on Category { - Category copyWith({int? id, String? name}) { - return Category(id: id ?? this.id, name: name ?? this.name); - } - - Category copyWithWrapped({Wrapped? id, Wrapped? name}) { - return Category( - id: (id != null ? id.value : this.id), - name: (name != null ? name.value : this.name)); - } -} - -@JsonSerializable(explicitToJson: true) -class User { - const User({ - this.id, - this.username, - this.firstName, - this.lastName, - this.email, - this.password, - this.phone, - this.userStatus, - }); - - factory User.fromJson(Map json) => _$UserFromJson(json); - - static const toJsonFactory = _$UserToJson; - Map toJson() => _$UserToJson(this); - - @JsonKey(name: 'id', includeIfNull: false) - final int? id; - @JsonKey(name: 'username', includeIfNull: false, defaultValue: '') - final String? username; - @JsonKey(name: 'firstName', includeIfNull: false, defaultValue: '') - final String? firstName; - @JsonKey(name: 'lastName', includeIfNull: false, defaultValue: '') - final String? lastName; - @JsonKey(name: 'email', includeIfNull: false, defaultValue: '') - final String? email; - @JsonKey(name: 'password', includeIfNull: false, defaultValue: '') - final String? password; - @JsonKey(name: 'phone', includeIfNull: false, defaultValue: '') - final String? phone; - @JsonKey(name: 'userStatus', includeIfNull: false) - final int? userStatus; - static const fromJsonFactory = _$UserFromJson; - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other is User && - (identical(other.id, id) || - const DeepCollectionEquality().equals(other.id, id)) && - (identical(other.username, username) || - const DeepCollectionEquality() - .equals(other.username, username)) && - (identical(other.firstName, firstName) || - const DeepCollectionEquality() - .equals(other.firstName, firstName)) && - (identical(other.lastName, lastName) || - const DeepCollectionEquality() - .equals(other.lastName, lastName)) && - (identical(other.email, email) || - const DeepCollectionEquality().equals(other.email, email)) && - (identical(other.password, password) || - const DeepCollectionEquality() - .equals(other.password, password)) && - (identical(other.phone, phone) || - const DeepCollectionEquality().equals(other.phone, phone)) && - (identical(other.userStatus, userStatus) || - const DeepCollectionEquality() - .equals(other.userStatus, userStatus))); - } - - @override - String toString() => jsonEncode(this); - - @override - int get hashCode => - const DeepCollectionEquality().hash(id) ^ - const DeepCollectionEquality().hash(username) ^ - const DeepCollectionEquality().hash(firstName) ^ - const DeepCollectionEquality().hash(lastName) ^ - const DeepCollectionEquality().hash(email) ^ - const DeepCollectionEquality().hash(password) ^ - const DeepCollectionEquality().hash(phone) ^ - const DeepCollectionEquality().hash(userStatus) ^ - runtimeType.hashCode; -} - -extension $UserExtension on User { - User copyWith( - {int? id, - String? username, - String? firstName, - String? lastName, - String? email, - String? password, - String? phone, - int? userStatus}) { - return User( - id: id ?? this.id, - username: username ?? this.username, - firstName: firstName ?? this.firstName, - lastName: lastName ?? this.lastName, - email: email ?? this.email, - password: password ?? this.password, - phone: phone ?? this.phone, - userStatus: userStatus ?? this.userStatus); - } - - User copyWithWrapped( - {Wrapped? id, - Wrapped? username, - Wrapped? firstName, - Wrapped? lastName, - Wrapped? email, - Wrapped? password, - Wrapped? phone, - Wrapped? userStatus}) { - return User( - id: (id != null ? id.value : this.id), - username: (username != null ? username.value : this.username), - firstName: (firstName != null ? firstName.value : this.firstName), - lastName: (lastName != null ? lastName.value : this.lastName), - email: (email != null ? email.value : this.email), - password: (password != null ? password.value : this.password), - phone: (phone != null ? phone.value : this.phone), - userStatus: (userStatus != null ? userStatus.value : this.userStatus)); - } -} - -@JsonSerializable(explicitToJson: true) -class Tag { - const Tag({ - this.id, - this.name, - }); - - factory Tag.fromJson(Map json) => _$TagFromJson(json); - - static const toJsonFactory = _$TagToJson; - Map toJson() => _$TagToJson(this); - - @JsonKey(name: 'id', includeIfNull: false) - final int? id; - @JsonKey(name: 'name', includeIfNull: false, defaultValue: '') - final String? name; - static const fromJsonFactory = _$TagFromJson; - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other is Tag && - (identical(other.id, id) || - const DeepCollectionEquality().equals(other.id, id)) && - (identical(other.name, name) || - const DeepCollectionEquality().equals(other.name, name))); - } - - @override - String toString() => jsonEncode(this); - - @override - int get hashCode => - const DeepCollectionEquality().hash(id) ^ - const DeepCollectionEquality().hash(name) ^ - runtimeType.hashCode; -} - -extension $TagExtension on Tag { - Tag copyWith({int? id, String? name}) { - return Tag(id: id ?? this.id, name: name ?? this.name); - } - - Tag copyWithWrapped({Wrapped? id, Wrapped? name}) { - return Tag( - id: (id != null ? id.value : this.id), - name: (name != null ? name.value : this.name)); - } -} - -@JsonSerializable(explicitToJson: true) -class ApiResponse { - const ApiResponse({ - this.code, - this.type, - this.message, - }); - - factory ApiResponse.fromJson(Map json) => - _$ApiResponseFromJson(json); - - static const toJsonFactory = _$ApiResponseToJson; - Map toJson() => _$ApiResponseToJson(this); - - @JsonKey(name: 'code', includeIfNull: false) - final int? code; - @JsonKey(name: 'type', includeIfNull: false, defaultValue: '') - final String? type; - @JsonKey(name: 'message', includeIfNull: false, defaultValue: '') - final String? message; - static const fromJsonFactory = _$ApiResponseFromJson; - - @override - bool operator ==(dynamic other) { - return identical(this, other) || - (other is ApiResponse && - (identical(other.code, code) || - const DeepCollectionEquality().equals(other.code, code)) && - (identical(other.type, type) || - const DeepCollectionEquality().equals(other.type, type)) && - (identical(other.message, message) || - const DeepCollectionEquality().equals(other.message, message))); - } - - @override - String toString() => jsonEncode(this); - - @override - int get hashCode => - const DeepCollectionEquality().hash(code) ^ - const DeepCollectionEquality().hash(type) ^ - const DeepCollectionEquality().hash(message) ^ - runtimeType.hashCode; -} - -extension $ApiResponseExtension on ApiResponse { - ApiResponse copyWith({int? code, String? type, String? message}) { - return ApiResponse( - code: code ?? this.code, - type: type ?? this.type, - message: message ?? this.message); - } - - ApiResponse copyWithWrapped( - {Wrapped? code, - Wrapped? type, - Wrapped? message}) { - return ApiResponse( - code: (code != null ? code.value : this.code), - type: (type != null ? type.value : this.type), - message: (message != null ? message.value : this.message)); - } -} - -String? orderStatusNullableToJson(enums.OrderStatus? orderStatus) { - return orderStatus?.value; -} - -String? orderStatusToJson(enums.OrderStatus orderStatus) { - return orderStatus.value; -} - -enums.OrderStatus orderStatusFromJson( - Object? orderStatus, [ - enums.OrderStatus? defaultValue, -]) { - return enums.OrderStatus.values.firstWhereOrNull((e) => - e.value.toString().toLowerCase() == - orderStatus?.toString().toLowerCase()) ?? - defaultValue ?? - enums.OrderStatus.swaggerGeneratedUnknown; -} - -enums.OrderStatus? orderStatusNullableFromJson( - Object? orderStatus, [ - enums.OrderStatus? defaultValue, -]) { - if (orderStatus == null) { - return null; - } - return enums.OrderStatus.values - .firstWhereOrNull((e) => e.value == orderStatus) ?? - defaultValue; -} - -String orderStatusExplodedListToJson(List? orderStatus) { - return orderStatus?.map((e) => e.value!).join(',') ?? ''; -} - -List orderStatusListToJson(List? orderStatus) { - if (orderStatus == null) { - return []; - } - - return orderStatus.map((e) => e.value!).toList(); -} - -List orderStatusListFromJson( - List? orderStatus, [ - List? defaultValue, -]) { - if (orderStatus == null) { - return defaultValue ?? []; - } - - return orderStatus.map((e) => orderStatusFromJson(e.toString())).toList(); -} - -List? orderStatusNullableListFromJson( - List? orderStatus, [ - List? defaultValue, -]) { - if (orderStatus == null) { - return defaultValue; - } - - return orderStatus.map((e) => orderStatusFromJson(e.toString())).toList(); -} - -String? petStatusNullableToJson(enums.PetStatus? petStatus) { - return petStatus?.value; -} - -String? petStatusToJson(enums.PetStatus petStatus) { - return petStatus.value; -} - -enums.PetStatus petStatusFromJson( - Object? petStatus, [ - enums.PetStatus? defaultValue, -]) { - return enums.PetStatus.values.firstWhereOrNull((e) => - e.value.toString().toLowerCase() == - petStatus?.toString().toLowerCase()) ?? - defaultValue ?? - enums.PetStatus.swaggerGeneratedUnknown; -} - -enums.PetStatus? petStatusNullableFromJson( - Object? petStatus, [ - enums.PetStatus? defaultValue, -]) { - if (petStatus == null) { - return null; - } - return enums.PetStatus.values.firstWhereOrNull((e) => e.value == petStatus) ?? - defaultValue; -} - -String petStatusExplodedListToJson(List? petStatus) { - return petStatus?.map((e) => e.value!).join(',') ?? ''; -} - -List petStatusListToJson(List? petStatus) { - if (petStatus == null) { - return []; - } - - return petStatus.map((e) => e.value!).toList(); -} - -List petStatusListFromJson( - List? petStatus, [ - List? defaultValue, -]) { - if (petStatus == null) { - return defaultValue ?? []; - } - - return petStatus.map((e) => petStatusFromJson(e.toString())).toList(); -} - -List? petStatusNullableListFromJson( - List? petStatus, [ - List? defaultValue, -]) { - if (petStatus == null) { - return defaultValue; - } - - return petStatus.map((e) => petStatusFromJson(e.toString())).toList(); -} - -String? petFindByStatusGetStatusNullableToJson( - enums.PetFindByStatusGetStatus? petFindByStatusGetStatus) { - return petFindByStatusGetStatus?.value; -} - -String? petFindByStatusGetStatusToJson( - enums.PetFindByStatusGetStatus petFindByStatusGetStatus) { - return petFindByStatusGetStatus.value; -} - -enums.PetFindByStatusGetStatus petFindByStatusGetStatusFromJson( - Object? petFindByStatusGetStatus, [ - enums.PetFindByStatusGetStatus? defaultValue, -]) { - return enums.PetFindByStatusGetStatus.values.firstWhereOrNull((e) => - e.value.toString().toLowerCase() == - petFindByStatusGetStatus?.toString().toLowerCase()) ?? - defaultValue ?? - enums.PetFindByStatusGetStatus.swaggerGeneratedUnknown; -} - -enums.PetFindByStatusGetStatus? petFindByStatusGetStatusNullableFromJson( - Object? petFindByStatusGetStatus, [ - enums.PetFindByStatusGetStatus? defaultValue, -]) { - if (petFindByStatusGetStatus == null) { - return null; - } - return enums.PetFindByStatusGetStatus.values - .firstWhereOrNull((e) => e.value == petFindByStatusGetStatus) ?? - defaultValue; -} - -String petFindByStatusGetStatusExplodedListToJson( - List? petFindByStatusGetStatus) { - return petFindByStatusGetStatus?.map((e) => e.value!).join(',') ?? ''; -} - -List petFindByStatusGetStatusListToJson( - List? petFindByStatusGetStatus) { - if (petFindByStatusGetStatus == null) { - return []; - } - - return petFindByStatusGetStatus.map((e) => e.value!).toList(); -} - -List petFindByStatusGetStatusListFromJson( - List? petFindByStatusGetStatus, [ - List? defaultValue, -]) { - if (petFindByStatusGetStatus == null) { - return defaultValue ?? []; - } - - return petFindByStatusGetStatus - .map((e) => petFindByStatusGetStatusFromJson(e.toString())) - .toList(); -} - -List? - petFindByStatusGetStatusNullableListFromJson( - List? petFindByStatusGetStatus, [ - List? defaultValue, -]) { - if (petFindByStatusGetStatus == null) { - return defaultValue; - } - - return petFindByStatusGetStatus - .map((e) => petFindByStatusGetStatusFromJson(e.toString())) - .toList(); -} - -typedef $JsonFactory = T Function(Map json); - -class $CustomJsonDecoder { - $CustomJsonDecoder(this.factories); - - final Map factories; - - dynamic decode(dynamic entity) { - if (entity is Iterable) { - return _decodeList(entity); - } - - if (entity is T) { - return entity; - } - - if (isTypeOf()) { - return entity; - } - - if (isTypeOf()) { - return entity; - } - - if (entity is Map) { - return _decodeMap(entity); - } - - return entity; - } - - T _decodeMap(Map values) { - final jsonFactory = factories[T]; - if (jsonFactory == null || jsonFactory is! $JsonFactory) { - return throw "Could not find factory for type $T. Is '$T: $T.fromJsonFactory' included in the CustomJsonDecoder instance creation in bootstrapper.dart?"; - } - - return jsonFactory(values); - } - - List _decodeList(Iterable values) => - values.where((v) => v != null).map((v) => decode(v) as T).toList(); -} - -class $JsonSerializableConverter extends chopper.JsonConverter { - @override - FutureOr> convertResponse( - chopper.Response response) async { - if (response.bodyString.isEmpty) { - // In rare cases, when let's say 204 (no content) is returned - - // we cannot decode the missing json with the result type specified - return chopper.Response(response.base, null, error: response.error); - } - - if (ResultType == String) { - return response.copyWith(); - } - - if (ResultType == DateTime) { - return response.copyWith( - body: DateTime.parse((response.body as String).replaceAll('"', '')) - as ResultType); - } - - final jsonRes = await super.convertResponse(response); - return jsonRes.copyWith( - body: $jsonDecoder.decode(jsonRes.body) as ResultType); - } -} - -final $jsonDecoder = $CustomJsonDecoder(generatedMapping); - -// ignore: unused_element -String? _dateToJson(DateTime? date) { - if (date == null) { - return null; - } - - final year = date.year.toString(); - final month = date.month < 10 ? '0${date.month}' : date.month.toString(); - final day = date.day < 10 ? '0${date.day}' : date.day.toString(); - - return '$year-$month-$day'; -} - -class Wrapped { - final T value; - const Wrapped.value(this.value); -} diff --git a/example/lib/swagger_generated_code/pet_service_swagger.swagger.dart b/example/lib/swagger_generated_code/pet_service_swagger.swagger.dart index 263cc308..d4f90f5d 100644 --- a/example/lib/swagger_generated_code/pet_service_swagger.swagger.dart +++ b/example/lib/swagger_generated_code/pet_service_swagger.swagger.dart @@ -108,6 +108,7 @@ abstract class PetServiceSwagger extends ChopperService { ///Finds Pets by tags ///@param tags Tags to filter by + @deprecated Future>> petFindByTagsGet({ required List? tags, dynamic cacheControl, @@ -120,6 +121,7 @@ abstract class PetServiceSwagger extends ChopperService { ///Finds Pets by tags ///@param tags Tags to filter by + @deprecated @Get(path: '/pet/findByTags') Future>> _petFindByTagsGet({ @Query('tags') required List? tags, diff --git a/example/lib/swagger_generated_code/pet_service_yaml.swagger.dart b/example/lib/swagger_generated_code/pet_service_yaml.swagger.dart index 8c7565c6..fe321815 100644 --- a/example/lib/swagger_generated_code/pet_service_yaml.swagger.dart +++ b/example/lib/swagger_generated_code/pet_service_yaml.swagger.dart @@ -108,6 +108,7 @@ abstract class PetServiceYaml extends ChopperService { ///Finds Pets by tags ///@param tags Tags to filter by + @deprecated Future>> petFindByTagsGet({ required List? tags, dynamic cacheControl, @@ -120,6 +121,7 @@ abstract class PetServiceYaml extends ChopperService { ///Finds Pets by tags ///@param tags Tags to filter by + @deprecated @Get(path: '/pet/findByTags') Future>> _petFindByTagsGet({ @Query('tags') required List? tags, diff --git a/example/lib/swagger_generated_code/some_file_name.swagger.dart b/example/lib/swagger_generated_code/some_file_name.swagger.dart index e222bfc9..3777b6d3 100644 --- a/example/lib/swagger_generated_code/some_file_name.swagger.dart +++ b/example/lib/swagger_generated_code/some_file_name.swagger.dart @@ -108,6 +108,7 @@ abstract class SomeFileName extends ChopperService { ///Finds Pets by tags ///@param tags Tags to filter by + @deprecated Future>> petFindByTagsGet({ required List? tags, dynamic cacheControl, @@ -120,6 +121,7 @@ abstract class SomeFileName extends ChopperService { ///Finds Pets by tags ///@param tags Tags to filter by + @deprecated @Get(path: '/pet/findByTags') Future>> _petFindByTagsGet({ @Query('tags') required List? tags, diff --git a/lib/src/code_generators/constants.dart b/lib/src/code_generators/constants.dart index 473eea5b..f42dbcdc 100644 --- a/lib/src/code_generators/constants.dart +++ b/lib/src/code_generators/constants.dart @@ -1,9 +1,3 @@ -const List successResponseCodes = [ - '200', - '201', - '202', -]; - const List kKeyClasses = [ 'Response', 'Request', diff --git a/lib/src/code_generators/swagger_enums_generator.dart b/lib/src/code_generators/swagger_enums_generator.dart index acd0ae12..cc7fe650 100644 --- a/lib/src/code_generators/swagger_enums_generator.dart +++ b/lib/src/code_generators/swagger_enums_generator.dart @@ -156,17 +156,20 @@ ${allEnums.map((e) => e.toString()).join('\n')} swaggerRoot.paths.forEach((String path, SwaggerPath swaggerPath) { swaggerPath.requests .forEach((String requestType, SwaggerRequest swaggerRequest) { - final successResponse = SwaggerRequestsGenerator.getSuccessedResponse( + final successResponses = SwaggerRequestsGenerator.getSuccessedResponses( responses: swaggerRequest.responses); - final successResponseSchema = - successResponse?.schema ?? successResponse?.content?.schema; - - if (successResponseSchema != null) { - final responseEnums = generateEnumsFromSchemaMap({ - '${path.pascalCase}${requestType.pascalCase}\$$kResponse': - successResponseSchema - }); - result.addAll(responseEnums); + + for (final successResponse in successResponses) { + final successResponseSchema = + successResponse.schema ?? successResponse.content?.schema; + + if (successResponseSchema != null) { + final responseEnums = generateEnumsFromSchemaMap({ + '${path.pascalCase}${requestType.pascalCase}\$$kResponse': + successResponseSchema + }); + result.addAll(responseEnums); + } } final parameters = [ diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 10101d58..3f125a0d 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -325,46 +325,49 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { } } - //Models from response - final successResponse = getSuccessedResponse(responses: request.responses); - final responseRef = successResponse?.anyRef ?? ''; + //Models from responses + final successResponses = + getSuccessedResponses(responses: request.responses); + for (final successResponse in successResponses) { + final responseRef = successResponse.anyRef; - if (responseRef.isNotEmpty) { - final schema = root.allSchemas[responseRef.getUnformattedRef()]; + if (responseRef.isNotEmpty) { + final schema = root.allSchemas[responseRef.getUnformattedRef()]; - if (schema?.type == kArray) { - if (schema?.items?.ref.isNotEmpty == true) { - final ref = schema!.items!.ref; - final itemType = getValidatedClassName(ref.getUnformattedRef()); - results.add(itemType); - } else { - final itemsType = schema?.items?.type; + if (schema?.type == kArray) { + if (schema?.items?.ref.isNotEmpty == true) { + final ref = schema!.items!.ref; + final itemType = getValidatedClassName(ref.getUnformattedRef()); + results.add(itemType); + } else { + final itemsType = schema?.items?.type; - if (!kBasicTypes.contains(itemsType) && - schema?.items?.properties != null) { - final itemClassName = '$response\$Item'; + if (!kBasicTypes.contains(itemsType) && + schema?.items?.properties != null) { + final itemClassName = '$response\$Item'; - results.add(itemClassName); + results.add(itemClassName); + } } - } - } else { - if (!response.startsWith('$kMap<')) { - final neededResponse = response.removeListOrStream(); + } else { + if (!response.startsWith('$kMap<')) { + final neededResponse = response.removeListOrStream(); - if (!kBasicTypes.contains(neededResponse) && - neededResponse != kDynamic) { - results.add(getValidatedClassName(neededResponse)); + if (!kBasicTypes.contains(neededResponse) && + neededResponse != kDynamic) { + results.add(getValidatedClassName(neededResponse)); + } } } + } else if (successResponse.schema?.properties.isNotEmpty == true) { + results.add(response); + } else if (successResponse.content?.schema?.properties.isNotEmpty == + true) { + results.add(response); + } else if (successResponse.content?.schema?.allOf.isNotEmpty == true && + successResponse.content?.schema?.title.isNotEmpty == true) { + results.add(response); } - } else if (successResponse?.schema?.properties.isNotEmpty == true) { - results.add(response); - } else if (successResponse?.content?.schema?.properties.isNotEmpty == - true) { - results.add(response); - } else if (successResponse?.content?.schema?.allOf.isNotEmpty == true && - successResponse?.content?.schema?.title.isNotEmpty == true) { - results.add(response); } return results.where((element) => _isValidModelName(element)).toList(); @@ -1108,14 +1111,18 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return methodName; } - static SwaggerResponse? getSuccessedResponse({ + static List getSuccessedResponses({ required Map responses, }) { return responses.entries - .firstWhereOrNull((responseEntry) => - successResponseCodes.contains(responseEntry.key) || - successDescriptions.contains(responseEntry.value.description)) - ?.value; + .where((responseEntry) { + final code = int.tryParse(responseEntry.key) ?? 0; + + return code ~/ 100 == 2 || + successDescriptions.contains(responseEntry.value.description); + }) + .map((e) => e.value) + .toList(); } String _getResponseModelName({ @@ -1349,14 +1356,20 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return overridenResponses[path]!.overriddenValue; } - final neededResponse = getSuccessedResponse( + final neededResponses = getSuccessedResponses( responses: responses, ); - if (neededResponse == null) { + if (neededResponses.isEmpty) { return ''; } + if (neededResponses.length > 1 && !options.generateFirstSucceedResponse) { + return ''; + } + + final neededResponse = neededResponses.first; + if (neededResponse.schema?.type == kObject && neededResponse.schema?.properties.isNotEmpty == true) { return _getResponseModelName( diff --git a/lib/src/models/generator_options.dart b/lib/src/models/generator_options.dart index 997dcee4..a96971d7 100644 --- a/lib/src/models/generator_options.dart +++ b/lib/src/models/generator_options.dart @@ -38,6 +38,7 @@ class GeneratorOptions { this.generateToJsonFor = const [], this.multipartFileType = 'List', this.urlencodedFileType = 'Map', + this.generateFirstSucceedResponse = true, }); /// Build options from a JSON map. @@ -47,6 +48,9 @@ class GeneratorOptions { @JsonKey(defaultValue: true) final bool usePathForRequestNames; + @JsonKey(defaultValue: true) + final bool generateFirstSucceedResponse; + @JsonKey(defaultValue: true) final bool withBaseUrl; diff --git a/lib/src/models/generator_options.g2.dart b/lib/src/models/generator_options.g2.dart index 4a532b2b..a6d8bbcb 100644 --- a/lib/src/models/generator_options.g2.dart +++ b/lib/src/models/generator_options.g2.dart @@ -88,6 +88,8 @@ GeneratorOptions _$GeneratorOptionsFromJson(Map json) => GeneratorOptions( multipartFileType: json['multipart_file_type'] as String? ?? 'List', urlencodedFileType: json['urlencoded_file_type'] as String? ?? 'Map', + generateFirstSucceedResponse: + json['generate_first_succeed_response'] as bool? ?? true, ); Map _$GeneratorOptionsToJson(GeneratorOptions instance) => @@ -125,6 +127,7 @@ Map _$GeneratorOptionsToJson(GeneratorOptions instance) => 'import_paths': instance.importPaths, 'custom_return_type': instance.customReturnType, 'exclude_paths': instance.excludePaths, + 'generate_first_succeed_response': instance.generateFirstSucceedResponse, }; DefaultValueMap _$DefaultValueMapFromJson(Map json) => diff --git a/pubspec.yaml b/pubspec.yaml index d77d6e5c..d7f28715 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: swagger_dart_code_generator -version: 2.14.1 +version: 2.14.2 homepage: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator repository: https://github.com/epam-cross-platform-lab/swagger-dart-code-generator