@thorsten-wolf-neptune/swagger-typescript-api
v9.2.0
Published
Generate typescript/javascript api from swagger schema
Downloads
27
Maintainers
Readme
Adjustments to main repo
This fork is adding some extra features to allow a split of data definitions (done with) data-contract into multiple files.
The main adjustment is based the introduction of a "schemaStack" in the schema.js
That schema Stack will be passed along onParseSchema hook function. That enables us to see the relation of parent <--> child schema definitions.
API Factory NodeJS client will use this to make schema useages containing a x-sap-ddic-name property (schema elements that refer to a SAP DDIC Definition) outsourced into a central ddic.ts file.
The overall goal is to have a central ddic.ts file that contains all SAP DDIC definitions. Those then can be reused across multiple apis.
Additionally this fork contains an adjustment of the generation for enum values in schema.js
This is adjusted in schema.js and is related to the following issue scenario:
When having "number" enum values but those contain leading zeros the typescript compile will throw an error telling that "Octal literals should not be used". Example:
/**
* Activation type
* @xSAPDdicName AUTHCLASS_
* @xSAPInttype N
*/
export type AUTHCLASS_ = 01 | 02 | 10 | 00;
Our adjustment will fix this and create then the following
We solved it by removing leading zeros as well as if the value only contains zeros then not leav a single zero in place.
Our adjustment will fix this and create then the following:
/**
* Activation type
* @xSAPDdicName AUTHCLASS_
* @xSAPInttype N
*/
export type AUTHCLASS_ = 1 | 2 | 10 | 0;
swagger-typescript-api
Generate api via swagger scheme.
Supports OA 3.0, 2.0, JSON, yaml
Generated api module use Fetch Api or Axios to make requests.
Any questions you can ask here or in our slack(#swagger-typescript-api channel)
👀 Examples
All examples you can find here
📄 Usage
Usage: sta [options]
Usage: swagger-typescript-api [options]
Options:
-v, --version output the current version
-p, --path <path> path/url to swagger scheme
-o, --output <output> output path of typescript api file (default: "./")
-n, --name <name> name of output typescript api file (default: "Api.ts")
-t, --templates <path> path to folder containing templates
-d, --default-as-success use "default" response status code as success response too.
some swagger schemas use "default" response status code
as success response type by default. (default: false)
-r, --responses generate additional information about request responses
also add typings for bad responses (default: false)
--union-enums generate all "enum" types as union types (T1 | T2 | TN) (default: false)
--route-types generate type definitions for API routes (default: false)
--no-client do not generate an API class
--enum-names-as-values use values in 'x-enumNames' as enum values (not only as keys) (default: false)
--js generate js api module with declaration file (default: false)
--extract-request-params extract request params to data contract (default: false)
Also combine path params and query params into one object
--extract-request-body extract request body type to data contract (default: false)
--module-name-index <number> determines which path index should be used for routes separation (default: 0)
(example: GET:/fruites/getFruit -> index:0 -> moduleName -> fruites)
--module-name-first-tag splits routes based on the first tag
--modular generate separated files for http client, data contracts, and routes (default: false)
--disableStrictSSL disabled strict SSL (default: false)
--disableProxy disabled proxy (default: false)
--clean-output clean output folder before generate api. WARNING: May cause data loss (default: false)
--axios generate axios http client (default: false)
--single-http-client Ability to send HttpClient instance to Api constructor (default: false)
--silent Output only errors to console (default: false)
--default-response <type> default type for empty response schema (default: "void")
--type-prefix <string> data contract name prefix (default: "")
--type-suffix <string> data contract name suffix (default: "")
-h, --help display help for command
Also you can use npx
:
npx swagger-typescript-api -p ./swagger.json -o ./src -n myApi.ts
You can use this package from nodejs:
const { generateApi } = require('swagger-typescript-api');
const path = require("path");
const fs = require("fs");
/* NOTE: all fields are optional expect one of `output`, `url`, `spec` */
generateApi({
name: "MySuperbApi.ts",
output: path.resolve(process.cwd(), "./src/__generated__"),
url: 'http://api.com/swagger.json',
input: path.resolve(process.cwd(), './foo/swagger.json'),
spec: {
swagger: "2.0",
info: {
version: "1.0.0",
title: "Swagger Petstore",
},
// ...
},
templates: path.resolve(process.cwd(), './api-templates'),
httpClientType: "axios", // or "fetch"
defaultResponseAsSuccess: false,
generateRouteTypes: false,
generateResponses: true,
toJS: false,
extractRequestParams: false,
extractRequestBody: false,
prettier: {
printWidth: 120,
tabWidth: 2,
trailingComma: "all",
parser: "typescript",
},
defaultResponseType: "void",
singleHttpClient: true,
cleanOutput: false,
enumNamesAsValues: false,
moduleNameFirstTag: false,
generateUnionEnums: false,
extraTemplates: [],
hooks: {
onCreateComponent: (component) => {},
onCreateRequestParams: (rawType) => {},
onCreateRoute: (routeData) => {},
onCreateRouteName: (routeNameInfo, rawRouteInfo) => {},
onFormatRouteName: (routeInfo, templateRouteName) => {},
onFormatTypeName: (typeName, rawTypeName) => {},
onInit: (configuration) => {},
onParseSchema: (originalSchema, parsedSchema) => {},
onPrepareConfig: (currentConfiguration) => {},
}
})
.then(({ files, configuration }) => {
files.forEach(({ content, name }) => {
fs.writeFile(path, content);
});
})
.catch(e => console.error(e))
💎 options
--templates
This option needed for cases when you don't want to use the default swagger-typescript-api
output structure
Templates:
api.eta
- Api class module (locations: /templates/default, /templates/modular)data-contracts.eta
- all types (data contracts) from swagger schema (locations: /templates/base)http-client.eta
- HttpClient class module (locations: /templates/base)procedure-call.eta
- route in Api class (locations: /templates/default, /templates/modular)route-docs.eta
- documentation for route in Api class (locations: /templates/base)route-name.eta
- route name for route in Api class (locations: /templates/base)route-type.eta
- (--route-types
option) (locations: /templates/base)route-types.eta
- (--route-types
option) (locations: /templates/base)
How to use it:
- copy
swagger-typescript-api
templates into your place in project- from /templates/default for single api file
- from /templates/modular for multiple api files (with
--modular
option) - from /templates/base for base templates (templates using both in default and modular)
- add
--templates PATH_TO_YOUR_TEMPLATES
option - modify ETA templates as you like
NOTE:
Eta has special directive to render template in your Eta templates - includeFile(pathToTemplate, payload)
If you want to use some default templates from this tool you can use path prefixes: @base
, @default
, @modular
.@base
- path to base templates@default
- path to single api file templates@modular
- path to multiple api files templates
Examples:
- includeFile("@base/data-contracts.eta", configuration)
- includeFile("@default/api.eta", configuration)
- includeFile("@default/procedure-call.eta", configuration)
- includeFile("@modular/api.eta", configuration)
- includeFile("@modular/procedure-call.eta", configuration)
- includeFile("@base/route-docs.eta", configuration)
- includeFile("@base/route-name.eta", configuration)
- includeFile("@base/route-type.eta", configuration)
- includeFile("@base/route-types.eta", configuration)
--module-name-index
This option should be used in cases when you have api with one global prefix like /api
Example:GET:/api/fruits/getFruits
POST:/api/fruits/addFruits
GET:/api/vegetables/addVegetable
with --module-name-index 0
Api class will have one property api
When we change it to --module-name-index 1
then Api class have two properties fruits
and vegetables
--module-name-first-tag
This option will group your API operations based on their first tag - mirroring how the Swagger UI groups displayed operations
📄 Mass media
- Why Swagger schemes are needed in frontend development ?
- Migration en douceur vers TypeScript (French)
- swagger-typescript-api usage (Japanese)
🛠️ Contribution
❗❗❗ Please use the next
branch :)
If you need to check your changes at schemas in tests
folder before create a PR just run command npm run test-all
Contributors ✨
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
🚀 How it looks
📝 License
Licensed under the MIT License.