├── .github └── fabricbot.json ├── .gitignore ├── .jshintrc ├── .npmignore ├── .travis.yml ├── .vscode └── settings.json ├── Gruntfile.js ├── LICENSE ├── README.md ├── __tests__ ├── __snapshots__ │ └── runner.js.snap ├── fixtures │ ├── addProps │ │ └── swagger.json │ ├── collectionFormat │ │ └── swagger.json │ ├── petshop │ │ └── swagger.json │ ├── protected │ │ └── swagger.json │ ├── ref │ │ └── swagger.json │ ├── responses │ │ └── swagger.json │ ├── rootPath │ │ └── swagger.json │ ├── uber │ │ └── swagger.json │ └── users │ │ └── swagger.json └── runner.js ├── bin └── swagger2ts.js ├── package-lock.json ├── package.json ├── src ├── cli.ts ├── codegen.test.ts ├── codegen.ts ├── enhance │ ├── beautify.test.ts │ ├── beautify.ts │ ├── index.test.ts │ └── index.ts ├── generators │ ├── codeGenerator.ts │ └── swagger2.ts ├── getViewForSwagger2.test.ts ├── getViewForSwagger2.ts ├── options │ ├── options.test.ts │ └── options.ts ├── swagger │ └── Swagger.ts ├── test-helpers │ └── testHelpers.ts ├── transform │ ├── transformToCodeWithMustache.test.ts │ └── transformToCodeWithMustache.ts ├── type-mappers │ ├── any.ts │ ├── array.ts │ ├── boolean.ts │ ├── enum.ts │ ├── number.ts │ ├── object.ts │ ├── reference.ts │ ├── schema.ts │ ├── string.ts │ └── void.ts ├── typescript.test.ts ├── typescript.ts ├── typespec.ts └── view-data │ ├── definition.ts │ ├── headers.ts │ ├── method.ts │ ├── operation.ts │ ├── parameter.ts │ ├── responseType.ts │ └── version.ts ├── templates ├── class.mustache ├── method.mustache └── type.mustache ├── tests ├── apis │ ├── allOf.json │ ├── protected.json │ ├── ref.json │ ├── rootPath.json │ ├── test.json │ ├── uber.json │ └── users.json └── generation.js └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | node_modules/ 3 | *.iml 4 | wks.* 5 | .DS_Store 6 | *.swp 7 | 8 | tmp-* 9 | 10 | lib/ 11 | coverage/ 12 | yarn-error.log -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "node": true, 3 | "browser": false, 4 | "esnext": true, 5 | "bitwise": false, 6 | "camelcase": false, 7 | "curly": true, 8 | "eqeqeq": true, 9 | "immed": true, 10 | "indent": 4, 11 | "latedef": true, 12 | "newcap": false, 13 | "noarg": true, 14 | "quotmark": "single", 15 | "regexp": true, 16 | "undef": true, 17 | "unused": true, 18 | "strict": true, 19 | "trailing": true, 20 | "smarttabs": true, 21 | "globals": { 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .git* 2 | test/ 3 | .DS_Store 4 | *.swp 5 | src/ 6 | coverage/ 7 | yarn-error.log -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "10" 4 | deploy: 5 | provider: npm 6 | email: mariust@outlook.com 7 | skip_cleanup: true 8 | api_key: 9 | secure: lreacC7XuNx3oR4buSB/ToxWx23Wg/6UvNUId9sVh2CoY74GreJVzxGJAb1Rjngoa+w6vL/e67QDD0+PXN+9APuDMLBPX/8ohGeQtzeNpSGfv4/7h45tmzwAVvWKW29EDdvR3RZ1PXkD8nTtZmzVX6yRHrm9UhvyotnX7lpAww4YTFX7+CEHcQkFluBrJHzPrEQKC8iYDgCdqwLH0ZBS5N2i41wxj63v6f47QLGCcJFjFiblROcEJENZf2Z1rE5vQ4rle4GLQeh13RKj+jC4I9QwfXs8LC3oNnWL3iA69+/H5vr4kZt/mHGrFGRuwyhOhNIpS3DcsOSWL788Ru7TLZ23TgQ18vQ6T3lyPXzsa+NFW6zlPx1XB5RNbvWU4lDvsIjcZoYUff3Y1CV6JR3XM4VNcOkQ42BKFkGYrwecszTY0WTLkeeHqnqig/lG5bHg256ytIjPC+IVMei76OWeMlw0wgd/cpimPCQpR40zM8SLl16DwMF5A1owIQMWaH97IM7ydX1VIcHWCDSZ1W8+vVeihj1LgJvs3zEHUyA4iu/96UhCAp6AniPKe5SXkF9FzJH0PJ1X5VLpGERZDwC9yBXqiTIueUxFvd3hAxB6fOcQ72uKLZBCxgIyysxQX6l7FyIZ/0cuE758aIzhhIjJh8fHrjBKNDyqygeSlfBQ244= 10 | on: 11 | tags: true 12 | repo: mtennoe/swagger-typescript-codegen 13 | branch: master 14 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true 3 | } -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | module.exports = function (grunt) { 2 | 'use strict'; 3 | 4 | require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); 5 | // Load local tasks. 6 | //grunt.loadTasks('tasks'); 7 | 8 | // Project configuration. 9 | grunt.initConfig({ 10 | vows: { 11 | all: { 12 | options: { 13 | verbose: true, 14 | colors: true, 15 | coverage: 'json' 16 | }, 17 | // String or array of strings 18 | // determining which files to include. 19 | // This option is grunt's "full" file format. 20 | src: ['tests/*.js'] 21 | } 22 | }, 23 | jsonlint: { 24 | all: { 25 | src: ['package.json', 'tests/apis/*.json', '.jshintrc'] 26 | } 27 | } 28 | }); 29 | 30 | // Default task. 31 | grunt.registerTask('default', ['jsonlint', 'vows']); 32 | }; 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Swagger to Typescript Codegen 2 | 3 | [![Build Status](https://travis-ci.com/mtennoe/swagger-typescript-codegen.svg?branch=master)](https://travis-ci.com/mtennoe/swagger-typescript-codegen) 4 | 5 | This package generates a TypeScript class from a [swagger specification file](https://github.com/wordnik/swagger-spec). The code is generated using [mustache templates](https://github.com/mtennoe/swagger-js-codegen/tree/master/templates) and is quality checked by [jshint](https://github.com/jshint/jshint/) and beautified by [js-beautify](https://github.com/beautify-web/js-beautify). 6 | 7 | The typescript generator is based on [superagent](https://github.com/visionmedia/superagent) and can be used for both nodejs and the browser via browserify/webpack. 8 | 9 | This fork was made to simplify some parts, add some more features, and tailor it more to specific use cases. 10 | 11 | ## Installation 12 | 13 | ```bash 14 | npm install swagger-typescript-codegen 15 | ``` 16 | 17 | ## Example 18 | 19 | ```javascript 20 | var fs = require("fs"); 21 | var CodeGen = require("swagger-typescript-codegen").CodeGen; 22 | 23 | var file = "swagger/spec.json"; 24 | var swagger = JSON.parse(fs.readFileSync(file, "UTF-8")); 25 | var tsSourceCode = CodeGen.getTypescriptCode({ 26 | className: "Test", 27 | swagger: swagger, 28 | imports: ["../../typings/tsd.d.ts"] 29 | }); 30 | console.log(tsSourceCode); 31 | ``` 32 | 33 | ## Custom template 34 | 35 | ```javascript 36 | var source = CodeGen.getCustomCode({ 37 | moduleName: "Test", 38 | className: "Test", 39 | swagger: swaggerSpec, 40 | template: { 41 | class: fs.readFileSync("my-class.mustache", "utf-8"), 42 | method: fs.readFileSync("my-method.mustache", "utf-8"), 43 | type: fs.readFileSync("my-type.mustache", "utf-8") 44 | } 45 | }); 46 | ``` 47 | 48 | ## Options 49 | 50 | In addition to the common options listed below, `getCustomCode()` _requires_ a `template` field: 51 | 52 | template: { class: "...", method: "..." } 53 | 54 | `getTypescriptCode()`, `getCustomCode()` each support the following options: 55 | 56 | ```yaml 57 | moduleName: 58 | type: string 59 | description: Your module name 60 | className: 61 | type: string 62 | beautify: 63 | type: boolean 64 | description: whether or not to beautify the generated code 65 | beautifyOptions: 66 | type: object 67 | description: Options to be passed to the beautify command. See js-beautify for all available options. 68 | mustache: 69 | type: object 70 | description: See the 'Custom Mustache Variables' section below 71 | imports: 72 | type: array 73 | description: Typescript definition files to be imported. 74 | convertQueryParamsToFormDataInPOST: 75 | type: boolean 76 | description: whether or not to convert query parameters in a POST request to form data. 77 | swagger: 78 | type: object 79 | required: true 80 | description: swagger object 81 | ``` 82 | 83 | ### Template Variables 84 | 85 | The following data are passed to the [mustache templates](https://github.com/janl/mustache.js): 86 | 87 | ```yaml 88 | isES6: 89 | type: boolean 90 | description: 91 | type: string 92 | description: Provided by your options field: 'swagger.info.description' 93 | isSecure: 94 | type: boolean 95 | description: false unless 'swagger.securityDefinitions' is defined 96 | moduleName: 97 | type: string 98 | description: Your module name - provided by your options field 99 | className: 100 | type: string 101 | description: Provided by your options field 102 | domain: 103 | type: string 104 | description: If all options defined: swagger.schemes[0] + '://' + swagger.host + swagger.basePath 105 | methods: 106 | type: array 107 | items: 108 | type: object 109 | properties: 110 | path: 111 | type: string 112 | pathFormatString: 113 | type: string 114 | className: 115 | type: string 116 | description: Provided by your options field 117 | methodName: 118 | type: string 119 | description: Generated from the HTTP method and path elements or 'x-swagger-js-method-name' field 120 | method: 121 | type: string 122 | description: 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'COPY', 'HEAD', 'OPTIONS', 'LINK', 'UNLINK', 'PURGE', 'LOCK', 'UNLOCK', 'PROPFIND' 123 | enum: 124 | - GET 125 | - POST 126 | - PUT 127 | - DELETE 128 | - PATCH 129 | - COPY 130 | - HEAD 131 | - OPTIONS 132 | - LINK 133 | - UNLINK 134 | - PURGE 135 | - LOCK 136 | - UNLOCK 137 | - PROPFIND 138 | isGET: 139 | type: string 140 | description: true if method === 'GET' 141 | summary: 142 | type: string 143 | description: Provided by the 'description' or 'summary' field in the schema 144 | externalDocs: 145 | type: object 146 | properties: 147 | url: 148 | type: string 149 | description: The URL for the target documentation. Value MUST be in the format of a URL. 150 | required: true 151 | description: 152 | type: string 153 | description: A short description of the target documentation. GitHub-Markdown syntax can be used for rich text representation. 154 | isSecure: 155 | type: boolean 156 | description: true if the 'security' is defined for the method in the schema 157 | version: 158 | type: string 159 | description: Version part of the path, if the path starts with the prefix '/api/vXXX/'. 160 | intVersion: 161 | type: integer 162 | description: Integer part of the version string. 163 | isLatestVersion: 164 | type: boolean 165 | description: True iff this is the latest version of the method. 166 | parameters: 167 | type: array 168 | description: Includes all of the properties defined for the parameter in the schema plus: 169 | items: 170 | camelCaseName: 171 | type: string 172 | isSingleton: 173 | type: boolean 174 | description: true if there was only one 'enum' defined for the parameter 175 | singleton: 176 | type: string 177 | description: the one and only 'enum' defined for the parameter (if there is only one) 178 | isBodyParameter: 179 | type: boolean 180 | isPathParameter: 181 | type: boolean 182 | isQueryParameter: 183 | type: boolean 184 | isPatternType: 185 | type: boolean 186 | description: true if *in* is 'query', and 'pattern' is defined 187 | isHeaderParameter: 188 | type: boolean 189 | isFormParameter: 190 | type: boolean 191 | collectionFormat: 192 | type: string 193 | successfulResponseType: 194 | type: string 195 | description: The type of a successful response. Defaults to any for non-parsable types or Swagger 1.0 spec files 196 | successfulResponseTypeIsRef: 197 | type: boolean 198 | description: True iff the successful response type is the name of a type defined in the Swagger schema. 199 | convertQueryParamsToFormDataInPOST: 200 | type: boolean 201 | description: Provided by your options field 202 | ``` 203 | 204 | #### Custom Mustache Variables 205 | 206 | You can also pass in your own variables for the mustache templates by adding a `mustache` object: 207 | 208 | ```javascript 209 | var source = CodeGen.getCustomCode({ 210 | ... 211 | mustache: { 212 | foo: 'bar', 213 | app_build_id: env.BUILD_ID, 214 | app_version: pkg.version 215 | } 216 | }); 217 | ``` 218 | 219 | ## Swagger Extensions 220 | 221 | ### x-proxy-header 222 | 223 | Some proxies and application servers inject HTTP headers into the requests. Server-side code 224 | may use these fields, but they are not required in the client API. 225 | 226 | eg: https://cloud.google.com/appengine/docs/go/requests#Go_Request_headers 227 | 228 | ```yaml 229 | /locations: 230 | get: 231 | parameters: 232 | - name: X-AppEngine-Country 233 | in: header 234 | x-proxy-header: true 235 | type: string 236 | description: Provided by AppEngine eg - US, AU, GB 237 | - name: country 238 | in: query 239 | type: string 240 | description: | 241 | 2 character country code. 242 | If not specified, will default to the country provided in the X-AppEngine-Country header 243 | ... 244 | ``` 245 | 246 | ## Development 247 | 248 | To run the typescript compiler on the source files run. This will start a watch process on the sources and build them into the `lib` folder. 249 | 250 | ```bash 251 | npm run build:watch 252 | ``` 253 | 254 | In addition you can run the test watcher in a separate tab to run the tests in watch mode on the files in the `lib` folder. 255 | 256 | ```bash 257 | npm run test:watch 258 | ``` 259 | -------------------------------------------------------------------------------- /__tests__/fixtures/addProps/swagger.json: -------------------------------------------------------------------------------- 1 | { 2 | "swagger": "2.0", 3 | "info": { "version": "0.0.1", "title": "your title" }, 4 | "paths": { 5 | "/persons": { 6 | "get": { 7 | "operationId": "get_person", 8 | "description": "Gets `Person` object.", 9 | "responses": { "200": { "description": "empty schema" } } 10 | } 11 | } 12 | }, 13 | "definitions": { 14 | "some_def": { "type": "object", "properties": { "some_def": { "type": "string" } }, "additionalProperties": false }, 15 | 16 | "test_add_props_01": { "type": "object", "properties": { "some_prop": { "type": "string" } } }, 17 | "test_add_props_02": { "type": "object", "properties": { "some_prop": { "type": "string" } }, "additionalProperties": false }, 18 | "test_add_props_03": { "type": "object", "properties": { "some_prop": { "type": "string" } }, "additionalProperties": true }, 19 | "test_add_props_04": { "type": "object", "properties": { "some_prop": { "type": "string" } }, "additionalProperties": { "type": "string" } }, 20 | "test_add_props_05": { "type": "object", "properties": { "some_prop": { "type": "string" } }, "additionalProperties": { "type": "object", "properties": { "nested_prop": { "type": "string" } } } }, 21 | "test_add_props_06": { "type": "object", "properties": { "some_prop": { "type": "string" } }, "additionalProperties": { "$ref": "#/definitions/some_def" } }, 22 | "test_add_props_07": { "type": "object" }, 23 | "test_add_props_08": { "type": "object", "additionalProperties": false }, 24 | "test_add_props_09": { "type": "object", "additionalProperties": true }, 25 | "test_add_props_10": { "type": "object", "additionalProperties": { "type": "string" } }, 26 | "test_add_props_11": { "type": "object", "additionalProperties": { "type": "object", "properties": { "nested_prop": { "type": "string" } } } }, 27 | "test_add_props_12": { "type": "object", "additionalProperties": { "$ref": "#/definitions/some_def" } } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /__tests__/fixtures/collectionFormat/swagger.json: -------------------------------------------------------------------------------- 1 | { 2 | "swagger": "2.0", 3 | "info": { 4 | "title": "API", 5 | "version": "1.0.0" 6 | }, 7 | "paths": { 8 | "/collection-format": { 9 | "get": { 10 | "operationId": "getDummy", 11 | "summary": "simple dummy request with different collection formats", 12 | "parameters": [ 13 | { 14 | "name": "stringParam", 15 | "type": "string", 16 | "in": "query" 17 | }, 18 | { 19 | "name": "csvParam", 20 | "type": "array", 21 | "items": { 22 | "type": "string" 23 | }, 24 | "in": "query", 25 | "collectionFormat": "csv" 26 | }, 27 | { 28 | "name": "ssvParam", 29 | "type": "array", 30 | "items": { 31 | "type": "string" 32 | }, 33 | "in": "query", 34 | "collectionFormat": "ssv" 35 | }, 36 | { 37 | "name": "tsvParam", 38 | "type": "array", 39 | "items": { 40 | "type": "string" 41 | }, 42 | "in": "query", 43 | "collectionFormat": "tsv" 44 | }, 45 | { 46 | "name": "pipesParam", 47 | "type": "array", 48 | "items": { 49 | "type": "string" 50 | }, 51 | "in": "query", 52 | "collectionFormat": "pipes" 53 | }, 54 | { 55 | "name": "multiParam", 56 | "type": "array", 57 | "items": { 58 | "type": "string" 59 | }, 60 | "in": "query", 61 | "collectionFormat": "multi" 62 | } 63 | ], 64 | "responses": { 65 | "200": { 66 | "description": "Successful response", 67 | "schema": { 68 | "type": "object", 69 | "properties": { 70 | "name": { 71 | "type": "string" 72 | } 73 | } 74 | } 75 | } 76 | } 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /__tests__/fixtures/protected/swagger.json: -------------------------------------------------------------------------------- 1 | { 2 | "swagger": "2.0", 3 | "info": { 4 | "version": "0.0.1", 5 | "title": "title" 6 | }, 7 | "host": "portal.28.io", 8 | "basePath": "/api", 9 | "schemes": [ 10 | "http" 11 | ], 12 | "securityDefinitions": { 13 | "oauth2": { 14 | "type": "oauth2", 15 | "scopes": {}, 16 | "flow": "password", 17 | "tokenUrl": "" 18 | } 19 | }, 20 | "paths": { 21 | "/auth": { 22 | "post": { 23 | "description": "Get token", 24 | "operationId": "auth", 25 | "parameters": [ 26 | { 27 | "name": "grant_type", 28 | "description": "Authorization grant type. Use client_credentials to create a token or refresh_token to refresh a token", 29 | "required": true, 30 | "type": "string", 31 | "enum": ["client_credentials", "refresh_token"], 32 | "in": "query" 33 | }, 34 | { 35 | "name": "email", 36 | "description": "The account email. Mandatory if grant_type=client_credentials.", 37 | "required": false, 38 | "type": "string", 39 | "in": "query" 40 | }, 41 | { 42 | "name": "password", 43 | "description": "The account password. Mandatory if grant_type=client_credentials.", 44 | "required": false, 45 | "type": "string", 46 | "in": "query" 47 | }, 48 | { 49 | "name": "refresh_token", 50 | "description": "The refresh_token obtained in the last successful request to this endpoint. Mandatory if grant_type=refresh_token.", 51 | "required": false, 52 | "type": "string", 53 | "in": "query" 54 | } 55 | ], 56 | "responses": { 57 | "200": { 58 | "description": "Token", 59 | "schema": { 60 | "$ref": "#/definitions/Authentication" 61 | } 62 | }, 63 | "security": [ 64 | { 65 | "oauth2": [] 66 | } 67 | ], 68 | "401": { 69 | "description": "Unauthorized", 70 | "schema": { 71 | "$ref": "#/definitions/Error" 72 | } 73 | }, 74 | "default": { 75 | "description": "Error", 76 | "schema": { 77 | "$ref": "#/definitions/Error" 78 | } 79 | } 80 | } 81 | } 82 | }, 83 | "/project": { 84 | "get": { 85 | "description": "Get secure", 86 | "operationId": "getSecure", 87 | "parameters": [ 88 | { 89 | "name": "token", 90 | "description": "Auth token", 91 | "required": false, 92 | "type": "string", 93 | "in": "query" 94 | } 95 | ], 96 | "security": [ 97 | { 98 | "oauth2": [] 99 | } 100 | ], 101 | "responses": { 102 | "200": { 103 | "description": "Secure response returned" 104 | }, 105 | "401": { 106 | "description": "Unauthorized" 107 | } 108 | } 109 | } 110 | } 111 | }, 112 | "definitions": { 113 | "Authentication": { 114 | "required": [ 115 | "token_type", 116 | "expiration_date", 117 | "access_token", 118 | "refresh_token", 119 | "project_tokens" 120 | ], 121 | "properties": { 122 | "token_type": { 123 | "type": "string", 124 | "description": "The API token type", 125 | "enum": [ 126 | "bearer" 127 | ] 128 | }, 129 | "expiration_date": { 130 | "type": "date-time", 131 | "description": "The expiration date of all the tokens in the response" 132 | }, 133 | "access_token": { 134 | "type": "string", 135 | "description": "The API token" 136 | }, 137 | "refresh_token": { 138 | "type": "string", 139 | "description": "The refresh token which can be used to refresh both the API and project tokens" 140 | }, 141 | "project_tokens": { 142 | "type": "ProjectTokens", 143 | "description": "The project tokens which can be used to make request to the APIs on the project endpoints" 144 | } 145 | } 146 | }, 147 | "Error": { 148 | "required": [ 149 | "code", 150 | "message" 151 | ], 152 | "properties": { 153 | "code": { 154 | "type": "string", 155 | "description": "The XQuery error code of the error" 156 | }, 157 | "message": { 158 | "type": "string", 159 | "description": "A formatted string which contain the error code (always) and the module name, line and column-number and error description (when available)" 160 | }, 161 | "description": { 162 | "type": "string", 163 | "description": "The error description" 164 | }, 165 | "module": { 166 | "type": "string", 167 | "description": "The error module" 168 | }, 169 | "line-number": { 170 | "type": "string", 171 | "description": "The error line number" 172 | }, 173 | "column-number": { 174 | "type": "string", 175 | "description": "The error column number" 176 | } 177 | } 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /__tests__/fixtures/ref/swagger.json: -------------------------------------------------------------------------------- 1 | { 2 | "swagger": "2.0", 3 | "info": { 4 | "version": "0.0.0", 5 | "title": "" 6 | }, 7 | "parameters": { 8 | "id": { 9 | "name": "id", 10 | "in": "query", 11 | "description": "id", 12 | "required": true, 13 | "type": "string" 14 | } 15 | }, 16 | "paths": { 17 | "/persons": { 18 | "parameters": [ 19 | { 20 | "$ref": "#/parameters/id" 21 | } 22 | ], 23 | "get": { 24 | "description": "Gets `Person` object.", 25 | "responses": { 26 | "200": { 27 | "description": "Successful response", 28 | "schema": { 29 | "type": "object", 30 | "properties": { 31 | "name": { 32 | "type": "string" 33 | } 34 | } 35 | } 36 | } 37 | } 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /__tests__/fixtures/responses/swagger.json: -------------------------------------------------------------------------------- 1 | { 2 | "swagger": "2.0", 3 | "info": { 4 | "version": "0.0.1", 5 | "title": "your title" 6 | }, 7 | "paths": { 8 | "/persons": { 9 | "get": { 10 | "operationId": "get_person", 11 | "description": "Gets `Person` object.", 12 | "responses": { 13 | "200": { "description": "empty schema" }, 14 | "201": { 15 | "description": "inline schema", 16 | "schema": { "type": "object", "properties": { "inline_schema": { "type": "string" } } } 17 | }, 18 | "202": { 19 | "description": "inline schema ref", 20 | "schema": { "$ref": "#/definitions/direct_schema_ref" } 21 | }, 22 | "203": { "$ref": "#/responses/empty_schema" }, 23 | "204": { "$ref": "#/responses/regular_schema" }, 24 | "205": { "$ref": "#/responses/indirect_schema" }, 25 | "206": { "$ref": "#/responses/same_name" }, 26 | "207": { "$ref": "#/responses/same_name_clash" } 27 | } 28 | } 29 | } 30 | }, 31 | "responses": { 32 | "empty_schema": { "description": "empty schema" }, 33 | "regular_schema": { 34 | "description": "regular schema", 35 | "schema": { "type": "object", "properties": { "regular_schema": { "type": "string" } } } 36 | }, 37 | "indirect_schema": { 38 | "description": "indirect schema", 39 | "schema": { "$ref": "#/definitions/some_def" } 40 | }, 41 | "same_name": { 42 | "description": "same name schema", 43 | "schema": { "$ref": "#/definitions/same_name" } 44 | }, 45 | "same_name_clash": { 46 | "description": "same name clash schema", 47 | "schema": { "type": "object", "properties": { "same_name_clash_response": { "type": "string" } } } 48 | } 49 | }, 50 | "definitions": { 51 | "direct_schema_ref": { "type": "object", "properties": { "direct_schema_ref": { "type": "string" } } }, 52 | "some_def": { "type": "object", "properties": { "some_def": { "type": "string" } } }, 53 | "same_name": { "type": "object", "properties": { "same_name": { "type": "string" } } }, 54 | "same_name_clash": { "type": "object", "properties": { "same_name_clash_definition": { "type": "string" } } } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /__tests__/fixtures/rootPath/swagger.json: -------------------------------------------------------------------------------- 1 | { 2 | "swagger": "2.0", 3 | "info": { 4 | "version": "0.0.0", 5 | "title": "" 6 | }, 7 | "parameters": { 8 | "id": { 9 | "name": "id", 10 | "in": "query", 11 | "description": "id", 12 | "required": true, 13 | "type": "string" 14 | } 15 | }, 16 | "paths": { 17 | "/": { 18 | "get": { 19 | "description": "Just root path", 20 | "responses": { 21 | "200": { 22 | "description": "Successful response" 23 | } 24 | } 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /__tests__/fixtures/uber/swagger.json: -------------------------------------------------------------------------------- 1 | { 2 | "swagger": "2.0", 3 | "info": { 4 | "title": "Uber API", 5 | "description": "Move your app forward with the Uber API", 6 | "version": "1.0.0" 7 | }, 8 | "host": "api.uber.com", 9 | "schemes": [ 10 | "https" 11 | ], 12 | "basePath": "/v1", 13 | "produces": [ 14 | "application/json" 15 | ], 16 | "parameters": { 17 | "id": { 18 | "name": "id", 19 | "in": "path", 20 | "type": "integer", 21 | "format": "int32", 22 | "required": true 23 | } 24 | }, 25 | "paths": { 26 | "/products": { 27 | "get": { 28 | "summary": "Product Types", 29 | "description": "The Products endpoint returns information about the Uber products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order.", 30 | "parameters": [ 31 | { 32 | "name": "latitude", 33 | "in": "query", 34 | "description": "Latitude component of location.", 35 | "required": true, 36 | "type": "number", 37 | "format": "double" 38 | }, 39 | { 40 | "name": "longitude", 41 | "in": "query", 42 | "description": "Longitude component of location.", 43 | "required": true, 44 | "type": "number", 45 | "format": "double" 46 | }, 47 | { 48 | "name": "format", 49 | "in": "query", 50 | "x-exclude-from-bindings": true 51 | } 52 | ], 53 | "tags": [ 54 | "Products" 55 | ], 56 | "responses": { 57 | "200": { 58 | "description": "An array of products", 59 | "schema": { 60 | "type": "array", 61 | "items": { 62 | "$ref": "Product" 63 | } 64 | } 65 | }, 66 | "default": { 67 | "description": "Unexpected error", 68 | "schema": { 69 | "$ref": "Error" 70 | } 71 | } 72 | } 73 | } 74 | }, 75 | "/products/{id}": { 76 | "get": { 77 | "summary": "Product Types", 78 | "description": "The Products endpoint returns information about the Uber products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order.", 79 | "parameters": [ 80 | { 81 | "$ref": "id" 82 | }, 83 | { 84 | "name": "latitude", 85 | "in": "query", 86 | "description": "Latitude component of location.", 87 | "required": true, 88 | "type": "number", 89 | "format": "double" 90 | }, 91 | { 92 | "name": "longitude", 93 | "in": "query", 94 | "description": "Longitude component of location.", 95 | "required": true, 96 | "type": "number", 97 | "format": "double" 98 | } 99 | ], 100 | "tags": [ 101 | "Products" 102 | ], 103 | "responses": { 104 | "200": { 105 | "description": "An array of products", 106 | "schema": { 107 | "type": "array", 108 | "items": { 109 | "$ref": "Product" 110 | } 111 | } 112 | }, 113 | "default": { 114 | "description": "Unexpected error", 115 | "schema": { 116 | "$ref": "Error" 117 | } 118 | } 119 | } 120 | } 121 | }, 122 | "/estimates/price": { 123 | "get": { 124 | "summary": "Price Estimates", 125 | "description": "The Price Estimates endpoint returns an estimated price range for each product offered at a given location. The price estimate is provided as a formatted string with the full price range and the localized currency symbol.

The response also includes low and high estimates, and the [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for situations requiring currency conversion. When surge is active for a particular product, its surge_multiplier will be greater than 1, but the price estimate already factors in this multiplier.", 126 | "parameters": [ 127 | { 128 | "name": "start_latitude", 129 | "in": "query", 130 | "description": "Latitude component of start location.", 131 | "required": true, 132 | "type": "number", 133 | "format": "double" 134 | }, 135 | { 136 | "name": "start_longitude", 137 | "in": "query", 138 | "description": "Longitude component of start location.", 139 | "required": true, 140 | "type": "number", 141 | "format": "double" 142 | }, 143 | { 144 | "name": "end_latitude", 145 | "in": "query", 146 | "description": "Latitude component of end location.", 147 | "required": true, 148 | "type": "number", 149 | "format": "double" 150 | }, 151 | { 152 | "name": "end_longitude", 153 | "in": "query", 154 | "description": "Longitude component of end location.", 155 | "required": true, 156 | "type": "number", 157 | "format": "double" 158 | } 159 | ], 160 | "tags": [ 161 | "Estimates" 162 | ], 163 | "responses": { 164 | "200": { 165 | "description": "An array of price estimates by product", 166 | "schema": { 167 | "type": "array", 168 | "items": { 169 | "$ref": "PriceEstimate" 170 | } 171 | } 172 | }, 173 | "default": { 174 | "description": "Unexpected error", 175 | "schema": { 176 | "$ref": "Error" 177 | } 178 | } 179 | } 180 | } 181 | }, 182 | "/estimates/time": { 183 | "get": { 184 | "summary": "Time Estimates", 185 | "description": "The Time Estimates endpoint returns ETAs for all products offered at a given location, with the responses expressed as integers in seconds. We recommend that this endpoint be called every minute to provide the most accurate, up-to-date ETAs.", 186 | "parameters": [ 187 | { 188 | "name": "start_latitude", 189 | "in": "query", 190 | "description": "Latitude component of start location.", 191 | "required": true, 192 | "type": "number", 193 | "format": "double" 194 | }, 195 | { 196 | "name": "start_longitude", 197 | "in": "query", 198 | "description": "Longitude component of start location.", 199 | "required": true, 200 | "type": "number", 201 | "format": "double" 202 | }, 203 | { 204 | "name": "customer_uuid", 205 | "in": "query", 206 | "type": "string", 207 | "format": "uuid", 208 | "description": "Unique customer identifier to be used for experience customization." 209 | }, 210 | { 211 | "name": "product_id", 212 | "in": "query", 213 | "type": "string", 214 | "description": "Unique identifier representing a specific product for a given latitude & longitude." 215 | } 216 | ], 217 | "tags": [ 218 | "Estimates" 219 | ], 220 | "responses": { 221 | "200": { 222 | "description": "An array of products", 223 | "schema": { 224 | "type": "array", 225 | "items": { 226 | "$ref": "Product" 227 | } 228 | } 229 | }, 230 | "default": { 231 | "description": "Unexpected error", 232 | "schema": { 233 | "$ref": "Error" 234 | } 235 | } 236 | } 237 | } 238 | }, 239 | "/me": { 240 | "get": { 241 | "summary": "User Profile", 242 | "description": "The User Profile endpoint returns information about the Uber user that has authorized with the application.", 243 | "tags": [ 244 | "User" 245 | ], 246 | "responses": { 247 | "200": { 248 | "description": "Profile information for a user", 249 | "schema": { 250 | "$ref": "Profile" 251 | } 252 | }, 253 | "default": { 254 | "description": "Unexpected error", 255 | "schema": { 256 | "$ref": "Error" 257 | } 258 | } 259 | } 260 | } 261 | }, 262 | "/history": { 263 | "get": { 264 | "summary": "User Activity", 265 | "description": "The User Activity endpoint returns data about a user's lifetime activity with Uber. The response will include pickup locations and times, dropoff locations and times, the distance of past requests, and information about which products were requested.

The history array in the response will have a maximum length based on the limit parameter. The response value count may exceed limit, therefore subsequent API requests may be necessary.", 266 | "parameters": [ 267 | { 268 | "name": "offset", 269 | "in": "query", 270 | "type": "integer", 271 | "format": "int32", 272 | "description": "Offset the list of returned results by this amount. Default is zero." 273 | }, 274 | { 275 | "name": "limit", 276 | "in": "query", 277 | "type": "integer", 278 | "format": "int32", 279 | "description": "Number of items to retrieve. Default is 5, maximum is 100." 280 | } 281 | ], 282 | "tags": [ 283 | "User" 284 | ], 285 | "responses": { 286 | "200": { 287 | "description": "History information for the given user", 288 | "schema": { 289 | "$ref": "Activities" 290 | } 291 | }, 292 | "default": { 293 | "description": "Unexpected error", 294 | "schema": { 295 | "$ref": "Error" 296 | } 297 | } 298 | } 299 | } 300 | } 301 | }, 302 | "definitions": { 303 | "Product": { 304 | "properties": { 305 | "product_id": { 306 | "type": "string", 307 | "description": "Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles." 308 | }, 309 | "description": { 310 | "type": "string", 311 | "description": "Description of product." 312 | }, 313 | "display_name": { 314 | "type": "string", 315 | "description": "Display name of product." 316 | }, 317 | "capacity": { 318 | "type": "string", 319 | "description": "Capacity of product. For example, 4 people." 320 | }, 321 | "image": { 322 | "type": "string", 323 | "description": "Image URL representing the product." 324 | } 325 | } 326 | }, 327 | "PriceEstimate": { 328 | "properties": { 329 | "product_id": { 330 | "type": "string", 331 | "description": "Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles" 332 | }, 333 | "currency_code": { 334 | "type": "string", 335 | "description": "[ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code." 336 | }, 337 | "display_name": { 338 | "type": "string", 339 | "description": "Display name of product." 340 | }, 341 | "estimate": { 342 | "type": "string", 343 | "description": "Formatted string of estimate in local currency of the start location. Estimate could be a range, a single number (flat rate) or \"Metered\" for TAXI." 344 | }, 345 | "low_estimate": { 346 | "type": "number", 347 | "description": "Lower bound of the estimated price." 348 | }, 349 | "high_estimate": { 350 | "type": "number", 351 | "description": "Upper bound of the estimated price." 352 | }, 353 | "surge_multiplier": { 354 | "type": "number", 355 | "description": "Expected surge multiplier. Surge is active if surge_multiplier is greater than 1. Price estimate already factors in the surge multiplier." 356 | } 357 | } 358 | }, 359 | "Profile": { 360 | "properties": { 361 | "first_name": { 362 | "type": "string", 363 | "description": "First name of the Uber user." 364 | }, 365 | "last_name": { 366 | "type": "string", 367 | "description": "Last name of the Uber user." 368 | }, 369 | "email": { 370 | "type": "string", 371 | "description": "Email address of the Uber user" 372 | }, 373 | "picture": { 374 | "type": "string", 375 | "description": "Image URL of the Uber user." 376 | }, 377 | "promo_code": { 378 | "type": "string", 379 | "description": "Promo code of the Uber user." 380 | } 381 | } 382 | }, 383 | "Activity": { 384 | "properties": { 385 | "uuid": { 386 | "type": "string", 387 | "description": "Unique identifier for the activity" 388 | } 389 | } 390 | }, 391 | "Activities": { 392 | "properties": { 393 | "offset": { 394 | "type": "integer", 395 | "format": "int32", 396 | "description": "Position in pagination." 397 | }, 398 | "limit": { 399 | "type": "integer", 400 | "format": "int32", 401 | "description": "Number of items to retrieve (100 max)." 402 | }, 403 | "count": { 404 | "type": "integer", 405 | "format": "int32", 406 | "description": "Total number of items available." 407 | }, 408 | "history": { 409 | "type": "array", 410 | "$ref": "Activity" 411 | } 412 | } 413 | }, 414 | "Error": { 415 | "properties": { 416 | "code": { 417 | "type": "integer", 418 | "format": "int32" 419 | }, 420 | "message": { 421 | "type": "string" 422 | }, 423 | "fields": { 424 | "type": "string" 425 | } 426 | } 427 | } 428 | } 429 | } 430 | -------------------------------------------------------------------------------- /__tests__/fixtures/users/swagger.json: -------------------------------------------------------------------------------- 1 | { 2 | "swagger": "2.0", 3 | "info": { 4 | "version": "0.0.0", 5 | "title": "" 6 | }, 7 | "paths": { 8 | "/users/{userId}": { 9 | "parameters": [ 10 | { 11 | "name": "userId", 12 | "in": "path", 13 | "description": "User's id", 14 | "required": true, 15 | "type": "string" 16 | } 17 | ], 18 | "get": { 19 | "description": "Get user", 20 | "operationId": "findById", 21 | "responses": { 22 | "200": { 23 | "description": "User returned", 24 | "schema": { 25 | "type": "object", 26 | "properties": { 27 | "name": { 28 | "type": "string" 29 | } 30 | } 31 | } 32 | }, 33 | "404": { 34 | "description": "User not found" 35 | } 36 | } 37 | }, 38 | "delete": { 39 | "description": "Delete user", 40 | "operationId": "delete", 41 | "responses": { 42 | "200": { 43 | "description": "User deleted" 44 | } 45 | } 46 | } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /__tests__/runner.js: -------------------------------------------------------------------------------- 1 | var fs = require("fs"); 2 | var path = require("path"); 3 | var _ = require("lodash"); 4 | 5 | var CodeGen = require("../lib/codegen").CodeGen; 6 | 7 | var testCases = [ 8 | { 9 | desc: "Should resolve protected api", 10 | fixture: "protected" 11 | }, 12 | { 13 | desc: "Should resolve root path without an error", 14 | fixture: "rootPath" 15 | }, 16 | { 17 | desc: "Should resolve references", 18 | fixture: "ref" 19 | }, 20 | { 21 | desc: "Should resolve \"additionalProperties\"", 22 | fixture: "addProps" 23 | }, 24 | { 25 | desc: "Should resolve response references", 26 | fixture: "responses" 27 | }, 28 | { 29 | desc: "Real world: Uber", 30 | fixture: "uber" 31 | }, 32 | { 33 | desc: "Real world: users", 34 | fixture: "users" 35 | }, 36 | { 37 | desc: "Real world: petshop", 38 | fixture: "petshop" 39 | }, 40 | { 41 | desc: "Should resolve collection format", 42 | fixture: "collectionFormat" 43 | } 44 | ]; 45 | 46 | testCases.forEach(function(testCase) { 47 | test(testCase.desc, function() { 48 | var sourcePath = path.join( 49 | __dirname, 50 | "fixtures", 51 | testCase.fixture, 52 | "swagger.json" 53 | ); 54 | var swagger = JSON.parse(fs.readFileSync(sourcePath, "UTF-8")); 55 | 56 | var actual = CodeGen.getTypescriptCode({ 57 | moduleName: testCase.fixture, 58 | className: _.capitalize(testCase.fixture) + "Api", 59 | swagger: swagger, 60 | beautify: true 61 | }); 62 | 63 | expect(actual).toMatchSnapshot(); 64 | }); 65 | }); 66 | -------------------------------------------------------------------------------- /bin/swagger2ts.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | var path = require('path'); 3 | var fs = require('fs'); 4 | var lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib'); 5 | var updateNotifier = require('update-notifier'); 6 | 7 | //1. Update Notifier 8 | var pkg = require('../package.json'); 9 | updateNotifier({packageName: pkg.name, packageVersion: pkg.version}).notify(); 10 | 11 | //4. CLI Script 12 | require(lib + '/cli.js'); -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "swagger-typescript-codegen", 3 | "main": "./lib/codegen.js", 4 | "version": "3.2.4", 5 | "description": "A Swagger Codegenerator tailored for typescript.", 6 | "scripts": { 7 | "pretest": "npm run build", 8 | "test": "grunt && jest", 9 | "updateSnapshots": "grunt && jest --updateSnapshot", 10 | "clean": "rm -rf tmp-*", 11 | "build": "tsc --project tsconfig.json", 12 | "build:watch": "npm run build -- --watch", 13 | "test:watch": "jest --watch", 14 | "prepublishOnly": "npm run build", 15 | "prettier": "prettier --write \"src/**/*.ts\"" 16 | }, 17 | "bin": { 18 | "swagger2ts": "bin/swagger2ts.js" 19 | }, 20 | "bugs": { 21 | "url": "https://github.com/mtennoe/swagger-typescript-codegen/issues" 22 | }, 23 | "repository": { 24 | "type": "git", 25 | "url": "git://github.com/mtennoe/swagger-typescript-codegen.git" 26 | }, 27 | "keywords": [ 28 | "swagger", 29 | "rest" 30 | ], 31 | "author": { 32 | "name": "Marius Tennøe", 33 | "email": "mariust@outlook.com" 34 | }, 35 | "license": "Apache-2.0", 36 | "homepage": "https://github.com/mtennoe/swagger-typescript-codegen", 37 | "dependencies": { 38 | "commander": "^2.19.0", 39 | "js-beautify": "^1.8.9", 40 | "jshint": "^2.9.7", 41 | "lodash": "^4.17.19", 42 | "mustache": "^3.0.1", 43 | "update-notifier": "^4.1.0" 44 | }, 45 | "devDependencies": { 46 | "@types/commander": "^2.12.2", 47 | "@types/jest": "^23.3.10", 48 | "@types/js-beautify": "^1.8.0", 49 | "@types/lodash": "^4.14.119", 50 | "@types/mustache": "^0.8.32", 51 | "@types/node": "^10.12.18", 52 | "final-fs": "^1.6.0", 53 | "grunt": "^1.0.3", 54 | "grunt-contrib-jshint": "^2.0.0", 55 | "grunt-jsonlint": "^1.0.4", 56 | "grunt-vows": "^0.4.1", 57 | "husky": "^1.3.1", 58 | "jest": "^23.6.0", 59 | "lint-staged": "^8.1.0", 60 | "matchdep": "^2.0.0", 61 | "prettier": "1.15.3", 62 | "request": "^2.88.0", 63 | "superagent": "^4.0.0", 64 | "tmp": "0.0.33", 65 | "typescript": "^3.2.2", 66 | "vows": "^0.8.2" 67 | }, 68 | "husky": { 69 | "hooks": { 70 | "pre-commit": "lint-staged" 71 | } 72 | }, 73 | "lint-staged": { 74 | "*.{ts,md},": [ 75 | "prettier --write", 76 | "git add" 77 | ] 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/cli.ts: -------------------------------------------------------------------------------- 1 | import * as fs from "fs"; 2 | import * as cli from "commander"; 3 | import { CodeGen } from "./codegen"; 4 | 5 | const pkg = require("../package.json"); 6 | 7 | cli 8 | .command("generate ") 9 | .description("Generate from Swagger file") 10 | .action((file: string) => { 11 | const result = CodeGen.getTypescriptCode({ 12 | moduleName: "Test", 13 | className: "Test", 14 | swagger: JSON.parse(fs.readFileSync(file, "utf-8")) 15 | }); 16 | console.log(result); 17 | }); 18 | 19 | cli.version(pkg.version); 20 | cli.parse(process.argv); 21 | 22 | if (!cli.args.length) { 23 | cli.help(); 24 | } 25 | -------------------------------------------------------------------------------- /src/codegen.test.ts: -------------------------------------------------------------------------------- 1 | import { CodeGen } from "./codegen"; 2 | import { Swagger } from "./swagger/Swagger"; 3 | import { Templates } from "./transform/transformToCodeWithMustache"; 4 | 5 | describe("CodeGen", () => { 6 | let swagger = { 7 | swagger: "2.0" 8 | } as Swagger; 9 | 10 | describe("getTypescriptCode", () => { 11 | it("throws when the swagger version is not 2.0", () => { 12 | swagger = { 13 | ...swagger, 14 | swagger: "3.0" 15 | }; 16 | 17 | expect(() => CodeGen.getTypescriptCode({ swagger })).toThrow( 18 | "Only Swagger 2 specs are supported" 19 | ); 20 | }); 21 | }); 22 | 23 | describe("getCustomCode", () => { 24 | it("throws when the swagger version is not 2.0", () => { 25 | const customTemplates = { 26 | class: "class {}", 27 | method: "function () { 36 | CodeGen.getCustomCode({ swagger, template: customTemplates }) 37 | ).toThrow("Only Swagger 2 specs are supported"); 38 | }); 39 | 40 | it("throws when the template option is not provided", () => { 41 | const customTemplates = (undefined as any) as Templates; 42 | 43 | expect(() => 44 | CodeGen.getCustomCode({ swagger, template: customTemplates }) 45 | ).toThrow( 46 | 'Unprovided custom template. Please use the following template: template: { class: "...", method: "...", request: "..." }' 47 | ); 48 | }); 49 | 50 | it("throws when the class template is not provided", () => { 51 | const customTemplates = { 52 | method: "function () {}", 53 | type: "type " 54 | }; 55 | 56 | expect(() => 57 | CodeGen.getCustomCode({ swagger, template: customTemplates }) 58 | ).toThrow( 59 | 'Unprovided custom template. Please use the following template: template: { class: "...", method: "...", request: "..." }' 60 | ); 61 | }); 62 | 63 | it("throws when the method template is not provided", () => { 64 | const customTemplates = { 65 | class: "class {}", 66 | type: "type " 67 | }; 68 | 69 | expect(() => 70 | CodeGen.getCustomCode({ swagger, template: customTemplates }) 71 | ).toThrow( 72 | 'Unprovided custom template. Please use the following template: template: { class: "...", method: "...", request: "..." }' 73 | ); 74 | }); 75 | }); 76 | }); 77 | -------------------------------------------------------------------------------- /src/codegen.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ProvidedCodeGenOptions, 3 | makeOptions, 4 | validateOptions 5 | } from "./options/options"; 6 | import { transformToCodeWithMustache } from "./transform/transformToCodeWithMustache"; 7 | import { Swagger2Gen } from "./generators/swagger2"; 8 | import { enhanceCode } from "./enhance"; 9 | 10 | export const CodeGen = { 11 | transformToViewData: Swagger2Gen.getViewData, 12 | transformToCodeWithMustache, 13 | getTypescriptCode: function(opts: ProvidedCodeGenOptions) { 14 | const options = makeOptions(opts); 15 | 16 | return enhanceCode(Swagger2Gen.getCode(options), options); 17 | }, 18 | getCustomCode: function(opts: ProvidedCodeGenOptions) { 19 | validateOptions(opts); 20 | 21 | const options = makeOptions(opts); 22 | 23 | return enhanceCode(Swagger2Gen.getCode(options), options); 24 | }, 25 | getDataAndOptionsForGeneration: function(opts: ProvidedCodeGenOptions) { 26 | const options = makeOptions(opts); 27 | const data = Swagger2Gen.getViewData(options); 28 | return { data, options }; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /src/enhance/beautify.test.ts: -------------------------------------------------------------------------------- 1 | import { beautifyCode } from "./beautify"; 2 | 3 | const beautified = `function helloWorld() { 4 | return 'hello world' 5 | };`; 6 | 7 | describe("beautify", (): void => { 8 | it("returns the beautified code when no beautify param was specified", () => { 9 | const code = `function helloWorld(){return'hello world'};`; 10 | 11 | expect(beautifyCode(undefined, code)).toBe(beautified); 12 | }); 13 | 14 | it("returns the beautified code when true was specified", () => { 15 | const code = `function helloWorld(){return'hello world'};`; 16 | 17 | expect(beautifyCode(true, code)).toBe(beautified); 18 | }); 19 | 20 | it("returns the original code when false was specified", () => { 21 | const code = `function helloWorld(){return'hello world'};`; 22 | 23 | expect(beautifyCode(false, code)).toBe(code); 24 | }); 25 | 26 | it("runs the function that was specified", () => { 27 | const code = `function helloWorld(){return'hello world'};`; 28 | const prettify = jest.fn(); 29 | 30 | beautifyCode(prettify, code); 31 | 32 | expect(prettify).toBeCalledWith(code); 33 | }); 34 | }); 35 | -------------------------------------------------------------------------------- /src/enhance/beautify.ts: -------------------------------------------------------------------------------- 1 | import { js_beautify } from "js-beautify"; 2 | import { defaults } from "lodash"; 3 | 4 | const DEFAULT_BEAUTIFY_OPTIONS: JsBeautifyOptions = { 5 | indent_size: 4, 6 | max_preserve_newlines: 2 7 | }; 8 | 9 | export type Beautify = ((source: string) => string) | boolean | undefined; 10 | 11 | export type BeautifyOptions = JsBeautifyOptions; 12 | 13 | export function beautifyCode( 14 | beautify: Beautify, 15 | source: string, 16 | options: BeautifyOptions = {} 17 | ): string { 18 | // Backwards compatible js_beautify 19 | if (beautify === undefined || beautify === true) { 20 | return js_beautify(source, defaults(options, DEFAULT_BEAUTIFY_OPTIONS)); 21 | } 22 | 23 | // Run the beautify function if it has been provided 24 | if (typeof beautify === "function") { 25 | return beautify(source); 26 | } 27 | 28 | // Return original source if no beautify option was given 29 | return source; 30 | } 31 | -------------------------------------------------------------------------------- /src/enhance/index.test.ts: -------------------------------------------------------------------------------- 1 | import { enhanceCode } from "./"; 2 | import { beautifyCode } from "./beautify"; 3 | 4 | jest.mock("./beautify"); 5 | 6 | describe("enhanceCode", () => { 7 | it("calls beautify with the correct arguments", () => { 8 | const code = `function helloWorld(){return'hello world'};`; 9 | 10 | enhanceCode(code, { beautify: undefined, beautifyOptions: {} }); 11 | 12 | expect(beautifyCode).toBeCalledWith(undefined, code, {}); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /src/enhance/index.ts: -------------------------------------------------------------------------------- 1 | import { beautifyCode, Beautify, BeautifyOptions } from "./beautify"; 2 | 3 | export interface EnhanceOptions { 4 | beautify: Beautify; 5 | beautifyOptions: BeautifyOptions; 6 | } 7 | 8 | export function enhanceCode(source: string, opts: EnhanceOptions): string { 9 | return beautifyCode(opts.beautify, source, opts.beautifyOptions); 10 | } 11 | -------------------------------------------------------------------------------- /src/generators/codeGenerator.ts: -------------------------------------------------------------------------------- 1 | import { CodeGenOptions } from "../options/options"; 2 | import { ViewData } from "../getViewForSwagger2"; 3 | 4 | /** 5 | * Abstraction over a code generator. 6 | */ 7 | export interface CodeGenerator { 8 | /** 9 | * Returns the ViewData from the provided options. 10 | * 11 | * @param {CodeGenOptions} opts 12 | * 13 | * @returns {ViewData} 14 | */ 15 | getViewData(opts: CodeGenOptions): ViewData; 16 | 17 | /** 18 | * Generate the code from the provided options. 19 | * 20 | * @param {CodeGenOptions} opts 21 | * 22 | * @returns {string} 23 | */ 24 | getCode(opts: CodeGenOptions): string; 25 | } 26 | -------------------------------------------------------------------------------- /src/generators/swagger2.ts: -------------------------------------------------------------------------------- 1 | import { CodeGenOptions } from "../options/options"; 2 | import { transformToCodeWithMustache } from "../transform/transformToCodeWithMustache"; 3 | import { getViewForSwagger2 } from "../getViewForSwagger2"; 4 | import { CodeGenerator } from "./codeGenerator"; 5 | 6 | function verifyThatWeAreGeneratingForSwagger2(opts: CodeGenOptions): void { 7 | if (opts.swagger.swagger !== "2.0") { 8 | throw new Error("Only Swagger 2 specs are supported"); 9 | } 10 | } 11 | 12 | export const Swagger2Gen: CodeGenerator = { 13 | getViewData: opts => { 14 | verifyThatWeAreGeneratingForSwagger2(opts); 15 | 16 | return getViewForSwagger2(opts); 17 | }, 18 | getCode: opts => { 19 | const data = Swagger2Gen.getViewData(opts); 20 | return transformToCodeWithMustache(data, opts.template, opts.mustache); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /src/getViewForSwagger2.test.ts: -------------------------------------------------------------------------------- 1 | import { makeOptions } from "./options/options"; 2 | import { Swagger, HttpOperation } from "./swagger/Swagger"; 3 | import { getViewForSwagger2, ViewData } from "./getViewForSwagger2"; 4 | 5 | describe("getViewForSwagger2", () => { 6 | let swagger: Swagger; 7 | 8 | beforeEach(() => { 9 | swagger = { 10 | swagger: "2.0", 11 | info: { 12 | description: "My cool Swagger schema" 13 | }, 14 | host: "localhost:8080", 15 | schemes: ["https", "wss"], 16 | definitions: {}, 17 | security: [], 18 | securityDefinitions: undefined, 19 | paths: {}, 20 | basePath: "/api", 21 | produces: ["json"], 22 | consumes: ["json"], 23 | parameters: {} 24 | }; 25 | }); 26 | 27 | it("returns the default viewData for no additonal options", () => { 28 | const options = makeOptions({ swagger }); 29 | 30 | expect(getViewForSwagger2(options)).toEqual(makeViewData()); 31 | }); 32 | 33 | it("adds imports from the options", () => { 34 | const options = makeOptions({ 35 | swagger, 36 | imports: [`import * as _ from 'lodash'`] 37 | }); 38 | 39 | expect(getViewForSwagger2(options)).toEqual( 40 | makeViewData({ imports: [`import * as _ from 'lodash'`] }) 41 | ); 42 | }); 43 | 44 | it("can handle a single path", () => { 45 | const options = makeOptions({ 46 | swagger: { 47 | ...swagger, 48 | paths: { 49 | "/user": {} 50 | } 51 | } 52 | }); 53 | 54 | expect(getViewForSwagger2(options)).toEqual(makeViewData({})); 55 | }); 56 | 57 | describe("should map objects correctly", () => { 58 | it("can handle required properties", () => { 59 | const options = makeOptions({ 60 | swagger: { 61 | ...swagger, 62 | definitions: { 63 | typeWithRequiredProperties: { 64 | minItems: 0, 65 | required: ["anyProperty", "anotherProperty"], 66 | properties: { 67 | anyProperty: { 68 | type: "string" 69 | }, 70 | anotherProperty: { 71 | type: "string" 72 | }, 73 | notRequiredProperty: { 74 | type: "string" 75 | } 76 | } 77 | } 78 | } as any 79 | } 80 | }); 81 | const view = getViewForSwagger2(options); 82 | expect(view.definitions.length).toEqual(1); 83 | expect(view.definitions[0].tsType).toEqual( 84 | expect.objectContaining({ isRequired: true }) //this still confuses me 85 | ); 86 | expect(view.definitions[0].tsType.properties).toEqual( 87 | expect.arrayContaining([ 88 | expect.objectContaining({ 89 | name: "anyProperty", 90 | isRequired: true 91 | }), 92 | expect.objectContaining({ 93 | name: "anotherProperty", 94 | isRequired: true 95 | }), 96 | expect.objectContaining({ 97 | name: "notRequiredProperty", 98 | isRequired: false 99 | }) 100 | ]) 101 | ); 102 | }); 103 | }); 104 | 105 | describe("should honor includeDeprecated option", () => { 106 | let deprecatedSwagger: Swagger; 107 | 108 | beforeEach(() => { 109 | deprecatedSwagger = { 110 | ...swagger, 111 | paths: { 112 | "/deprecated": { 113 | get: { 114 | ...makeOperation(), 115 | deprecated: true 116 | } 117 | }, 118 | "/nonDeprecated": { 119 | get: { 120 | ...makeOperation(), 121 | deprecated: false 122 | } 123 | } 124 | } 125 | }; 126 | }); 127 | 128 | it("does not include deprecated methods by default", () => { 129 | const options = makeOptions({ 130 | swagger: deprecatedSwagger 131 | }); 132 | const view = getViewForSwagger2(options); 133 | expect(view.methods).toEqual( 134 | expect.arrayContaining([ 135 | expect.objectContaining({ 136 | path: "/nonDeprecated", 137 | isDeprecated: false 138 | }) 139 | ]) 140 | ); 141 | }); 142 | it("includes deprecated methods if includeDeprecated is true", () => { 143 | const options = makeOptions({ 144 | includeDeprecated: true, 145 | swagger: deprecatedSwagger 146 | }); 147 | 148 | const view = getViewForSwagger2(options); 149 | expect(view.methods).toEqual( 150 | expect.arrayContaining([ 151 | expect.objectContaining({ path: "/deprecated", isDeprecated: true }), 152 | expect.objectContaining({ 153 | path: "/nonDeprecated", 154 | isDeprecated: false 155 | }) 156 | ]) 157 | ); 158 | }); 159 | }); 160 | }); 161 | 162 | function makeOperation(): HttpOperation { 163 | return { 164 | security: false, 165 | responses: {}, 166 | operationId: "operationId", 167 | description: "description", 168 | summary: "summary", 169 | externalDocs: "", 170 | produces: [""], 171 | consumes: [""], 172 | parameters: [], 173 | deprecated: false 174 | }; 175 | } 176 | 177 | function makeViewData(partial: Partial = {}): ViewData { 178 | return { 179 | isES6: false, 180 | description: "My cool Swagger schema", 181 | isSecure: false, 182 | isSecureToken: false, 183 | isSecureApiKey: false, 184 | isSecureBasic: false, 185 | moduleName: "", 186 | className: "", 187 | imports: [], 188 | domain: "https://localhost:8080/api", 189 | methods: [], 190 | definitions: [], 191 | ...partial 192 | }; 193 | } 194 | -------------------------------------------------------------------------------- /src/getViewForSwagger2.ts: -------------------------------------------------------------------------------- 1 | import { merge, get } from "lodash"; 2 | import { CodeGenOptions } from "./options/options"; 3 | import { Swagger } from "./swagger/Swagger"; 4 | import { 5 | makeMethod, 6 | makeMethodName, 7 | Method, 8 | getLatestVersionOfMethods 9 | } from "./view-data/method"; 10 | import { 11 | Definition, 12 | makeDefinitionsFromSwaggerDefinitions 13 | } from "./view-data/definition"; 14 | import { 15 | getHttpMethodTuplesFromSwaggerPathsObject, 16 | isAuthorizedAndNotDeprecated, 17 | isAuthorizedMethod 18 | } from "./view-data/operation"; 19 | 20 | export type GenerationTargetType = "typescript" | "custom"; 21 | 22 | export interface ViewData { 23 | isES6: boolean; 24 | description: string; 25 | isSecure: boolean; 26 | moduleName: string; 27 | className: string; 28 | imports: ReadonlyArray; 29 | domain: string; 30 | isSecureToken: boolean; 31 | isSecureApiKey: boolean; 32 | isSecureBasic: boolean; 33 | methods: Method[]; 34 | definitions: Definition[]; 35 | } 36 | 37 | export function getViewForSwagger2(opts: CodeGenOptions): ViewData { 38 | const swagger = normalizeResponseDefinitions(opts.swagger); 39 | 40 | const data: ViewData = { 41 | isES6: opts.isES6, 42 | description: swagger.info.description, 43 | isSecure: swagger.securityDefinitions !== undefined, 44 | isSecureToken: false, 45 | isSecureApiKey: false, 46 | isSecureBasic: false, 47 | moduleName: opts.moduleName, 48 | className: opts.className, 49 | imports: opts.imports, 50 | domain: 51 | swagger.schemes && 52 | swagger.schemes.length > 0 && 53 | swagger.host && 54 | swagger.basePath 55 | ? `${swagger.schemes[0]}://${swagger.host}${swagger.basePath.replace( 56 | /\/+$/g, 57 | "" 58 | )}` 59 | : "", 60 | methods: [], 61 | definitions: [] 62 | }; 63 | 64 | data.methods = makeMethodsFromPaths(data, opts, swagger); 65 | 66 | const latestVersions = getLatestVersionOfMethods(data.methods); 67 | 68 | data.methods = data.methods.map(setIsLatestVersion(latestVersions)); 69 | 70 | data.definitions = makeDefinitionsFromSwaggerDefinitions( 71 | swagger.definitions, 72 | swagger 73 | ); 74 | 75 | return { 76 | ...data 77 | }; 78 | } 79 | 80 | function normalizeResponseDefinitions(swagger: any): any { 81 | // ensure that the optional swagger.responses and swagger.definitions fields are present 82 | swagger.responses = swagger.responses || {}; 83 | swagger.definitions = swagger.definitions || {}; 84 | 85 | // inject swagger.response defs into swagger.definitions 86 | // prefixing them with "Response_" on name clashes with existing definitions 87 | Object.entries(swagger.responses).forEach(([name, def]) => { 88 | if (!def.schema || def.schema.$ref) { 89 | return; 90 | } 91 | 92 | const defName = (swagger.definitions[name] ? "Response_" : "") + name; 93 | swagger.definitions[defName] = def.schema; 94 | def.schema = { $ref: `#/definitions/${defName}` }; 95 | }); 96 | 97 | // inject inline response definitions into swagger.definitions 98 | // the corresponding def name will be constructed like "Response_${opName}_${responseCode}" 99 | // in order to avoid name clashes 100 | getHttpMethodTuplesFromSwaggerPathsObject(swagger.paths).forEach( 101 | ([path, httpVerb, op]) => { 102 | const responses = op.responses; 103 | 104 | Object.entries(responses).forEach(([resCode, resDef]) => { 105 | const schema = resDef.schema; 106 | if (schema && !schema.$ref) { 107 | const methodName = makeMethodName(path, httpVerb, op); 108 | const defName = `Response_${methodName}_${resCode}`; 109 | swagger.definitions[defName] = schema; 110 | resDef.schema = { $ref: `#/definitions/${defName}` }; 111 | } 112 | }); 113 | } 114 | ); 115 | 116 | // remove one level of indirection (refs pointing to swagger.responses) 117 | // from the endpoint.responses defs by redirecting them directly to the 118 | // corresponding ref into swagger.definitions 119 | getHttpMethodTuplesFromSwaggerPathsObject(swagger.paths).forEach( 120 | ([_path, _httpVerb, op]) => { 121 | const responses = op.responses; 122 | 123 | Object.keys(responses).forEach(r => { 124 | const ref = responses[r].$ref; 125 | if (ref) { 126 | const def = get(swagger, ref.substring(2).split("/")); // remove leading "#/" 127 | (responses[r] as any) = def; 128 | } 129 | }); 130 | } 131 | ); 132 | 133 | // swagger.responses is not used/required anymore 134 | delete swagger.responses; 135 | 136 | return swagger; 137 | } 138 | 139 | function setIsLatestVersion( 140 | latestVersions: Method[] 141 | ): (method: Method) => Method { 142 | return method => 143 | latestVersions.indexOf(method) > -1 144 | ? { 145 | ...method, 146 | isLatestVersion: true 147 | } 148 | : method; 149 | } 150 | 151 | const makeMethodsFromPaths = ( 152 | data: ViewData, 153 | opts: CodeGenOptions, 154 | swagger: Swagger 155 | ): Method[] => 156 | getHttpMethodTuplesFromSwaggerPathsObject(swagger.paths) 157 | .filter( 158 | method => 159 | (opts.includeDeprecated && isAuthorizedMethod(method)) || 160 | isAuthorizedAndNotDeprecated(method) 161 | ) 162 | .map(([path, httpVerb, op, globalParams]) => { 163 | // TODO: Start of untested security stuff that needs fixing 164 | const secureTypes = []; 165 | 166 | if ( 167 | swagger.securityDefinitions !== undefined || 168 | op.security !== undefined 169 | ) { 170 | const mergedSecurity = merge([], swagger.security, op.security).map( 171 | security => Object.keys(security) 172 | ); 173 | if (swagger.securityDefinitions) { 174 | for (const sk in swagger.securityDefinitions) { 175 | if (mergedSecurity.join(",").indexOf(sk) !== -1) { 176 | secureTypes.push(swagger.securityDefinitions[sk].type); 177 | } 178 | } 179 | } 180 | } 181 | // End of untested 182 | 183 | const method: Method = makeMethod( 184 | path, 185 | opts, 186 | swagger, 187 | httpVerb, 188 | op, 189 | secureTypes, 190 | globalParams 191 | ); 192 | 193 | // TODO: It seems the if statements below are pretty weird... 194 | // This runs in a for loop which is run for every "method" 195 | // in every "api" but we modify the parameter passed in to the 196 | // function, therefore changing the global state by setting it to 197 | // the last api + method combination? 198 | // No test covers this scenario at the moment. 199 | if (method.isSecure && method.isSecureToken) { 200 | data.isSecureToken = method.isSecureToken; 201 | } 202 | 203 | if (method.isSecure && method.isSecureApiKey) { 204 | data.isSecureApiKey = method.isSecureApiKey; 205 | } 206 | 207 | if (method.isSecure && method.isSecureBasic) { 208 | data.isSecureBasic = method.isSecureBasic; 209 | } 210 | // End of weird statements 211 | 212 | return method; 213 | }); 214 | -------------------------------------------------------------------------------- /src/options/options.test.ts: -------------------------------------------------------------------------------- 1 | import { makeOptions, validateOptions } from "./options"; 2 | import * as Mustache from "mustache"; 3 | import { Swagger } from "../swagger/Swagger"; 4 | 5 | const defaultOptions = { 6 | isES6: false, 7 | moduleName: "", 8 | includeDeprecated: false, 9 | imports: [], 10 | className: "", 11 | template: {}, 12 | mustache: Mustache, 13 | beautify: true, 14 | beautifyOptions: {} 15 | }; 16 | 17 | describe("makeOptions", () => { 18 | it("returns the default options when no options are passed", () => { 19 | const partialOptions = { 20 | swagger: {} as Swagger 21 | }; 22 | 23 | expect(makeOptions(partialOptions)).toEqual({ 24 | ...defaultOptions, 25 | swagger: {} 26 | }); 27 | }); 28 | 29 | it("merges in the options that are passed with higher priority", () => { 30 | const partialOptions = { 31 | swagger: {} as Swagger, 32 | className: "GeneratedDataLayer" 33 | }; 34 | 35 | const options = makeOptions(partialOptions); 36 | 37 | expect(options.className).toBe("GeneratedDataLayer"); 38 | }); 39 | }); 40 | 41 | describe("validateOptions", () => { 42 | it("with valid options", () => { 43 | const partialOptions = { 44 | swagger: {} as Swagger, 45 | template: { 46 | class: "class-template", 47 | method: "method-template" 48 | } 49 | }; 50 | 51 | const options = makeOptions(partialOptions); 52 | 53 | expect(() => validateOptions(options)); 54 | }); 55 | 56 | it("throws when class template is not provided", () => { 57 | const partialOptions = { 58 | swagger: {} as Swagger, 59 | template: { 60 | class: "class-template", 61 | method: undefined 62 | } 63 | }; 64 | 65 | const options = makeOptions(partialOptions); 66 | 67 | expect(() => validateOptions(options)).toThrow( 68 | 'Unprovided custom template. Please use the following template: template: { class: "...", method: "...", request: "..." }' 69 | ); 70 | }); 71 | 72 | it("throws when method template is not provided", () => { 73 | const partialOptions = { 74 | swagger: {} as Swagger, 75 | template: { 76 | class: undefined, 77 | method: "method-template" 78 | } 79 | }; 80 | 81 | const options = makeOptions(partialOptions); 82 | 83 | expect(() => validateOptions(options)).toThrow( 84 | 'Unprovided custom template. Please use the following template: template: { class: "...", method: "...", request: "..." }' 85 | ); 86 | }); 87 | }); 88 | -------------------------------------------------------------------------------- /src/options/options.ts: -------------------------------------------------------------------------------- 1 | import * as Mustache from "mustache"; 2 | import { isObject, isString } from "lodash"; 3 | import { Swagger } from "../swagger/Swagger"; 4 | 5 | export interface Template { 6 | readonly class: string; 7 | readonly method: string; 8 | readonly type: string; 9 | } 10 | 11 | interface Options { 12 | readonly isES6: boolean; 13 | readonly moduleName: string; 14 | readonly includeDeprecated: boolean; 15 | readonly imports: ReadonlyArray; 16 | readonly className: string; 17 | readonly template: Partial