Swagger schema to typescript

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

An auto typescript/javascript code generator from swagger.

License

hosseinmd/swagger-typescript

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

readme.md

NPM

⭐ ⭐ ⭐ If you would like to contribute, please refer to To do list and a list of open tasks. ⭐ ⭐ ⭐

Swagger-Typescript: Generate ts/js code from swagger/openApi JSON

Support OpenApi v3, swagger v2 and postman collection

An auto typescript/javascript/kotlin code generator from APIs doc. Each endpoint will be created as a function, full type base. Supported

  • Generating a function for every apis
  • Generating all types, interfaces and enums which used in apis
  • React hooks.
  • SignalR hub.
  • Generating mock data.

For Example: Get method of ‘/Account’ path will be this code in services.ts

import  getAccount > from "./services"; const response = await getAccount( id: 1234 >);

$ yarn add swagger-typescript prettier -D && yarn add axios

Before running, add your config to swagger.config.json

< "url": "http://example.com/api/swagger.json", "dir": "./services", "prefix": "/api" >
const baseConfig: AxiosRequestConfig =  baseURL: "", // //other static configs >;

Now you can use APIs, So for advanced config read below.

< "$schema": "https://raw.githubusercontent.com/hosseinmd/swagger-typescript/master/schema/v6.json", "url": "http://example.com/api/swagger.json", "dir": "./services", "prettierPath": ".prettierrc", "language": "typescript" >

The config.ts file automatically will be created after first run. You could change this file for customization. Don’t change other files, if you want another config create Issue or PR.

  • getAxiosInstance getAxiosInstance used for create an instance of axios request you can customize that for what you needed
  • baseConfig baseConfig used for get static configs and headers. if you need some dynamic configs like add authentication to headers use requestConfig.headers.authorization into of axiosInstance.interceptors.request.use function.
const  generate > = require("swagger-typescript"); generate(config); // or generate(); // will be use ./swagger.config.json

In some situation teams have parallel backend development which cause conflict when updating swagger for solving this we have partially update, you can update your service just for a few tags and keep other old services codes.

For Doing this you need to add this to your swagger.config.json

This code will keep previous JSON for updating partially.

Run $ yarn swag-ts with your base backend, for example develop branch

Others need to pull this changes

Now you can update Tag1 and Tag2 $ yarn swag-ts Tag1 Tag2 .

if you have multiple gateway in your project you could handle it by add array of config in swagger.config.json

[ < "$schema": "https://raw.githubusercontent.com/hosseinmd/swagger-typescript/master/schema/v6.json", "url": "http://example1.com/api/swagger.json", "dir": "./service1", "prettierPath": ".prettierrc", "language": "typescript" >, < "$schema": "https://raw.githubusercontent.com/hosseinmd/swagger-typescript/master/schema/v6.json", "url": "http://example2.com/api/swagger.json", "dir": "./service2", "prettierPath": ".prettierrc", "language": "typescript" > ]

if you are managing project by multiple branch like gitflow, you need to update swagger based on you working branch or parent branch (for example your parent is develop if you create a branch from develop).

< "url": [ < "branch": "master", "url": "http:/example.com/api/swagger.json" >, < "branch": "develop", "url": "http://stage.example.com/api/swagger.json" > ] >

to generate swagger for develop run yarn swag-ts —branch=develop or your branch name should be develop or develop/something

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Generate TypeScript types from Swagger OpenAPI specs

jonaskello/swagger-to-ts

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

🚀 Convert OpenAPI 2.0 and OpenAPI 3.0 schemas to TypeScript interfaces using Node.js.

💅 The output is prettified with Prettier (and can be customized!).

👉 Works for both local and remote resources (filesystem and HTTP).

🗄️ Reading specs from file system

npx @manifoldco/swagger-to-ts schema.yaml --output schema.ts # 🤞 Loading spec from tests/v2/specs/stripe.yaml… # 🚀 schema.yaml -> schema.ts [250ms]

☁️ Reading specs from remote resource

npx @manifoldco/swagger-to-ts https://petstore.swagger.io/v2/swagger.json --output petstore.ts # 🤞 Loading spec from https://petstore.swagger.io/v2/swagger.json… # 🚀 https://petstore.swagger.io/v2/swagger.json -> petstore.ts [650ms]

Thanks to @psmyrdek for this feature!

Generating multiple schemas

In your package.json , for each schema you’d like to transform add one generate:specs:[name] npm-script. Then combine them all into one generate:specs script, like so:

"scripts": < "generate:specs": "npm run generate:specs:one && npm run generate:specs:two && npm run generate:specs:three", "generate:specs:one": "npx @manifoldco/swagger-to-ts one.yaml -o one.ts", "generate:specs:two": "npx @manifoldco/swagger-to-ts two.yaml -o two.ts", "generate:specs:three": "npx @manifoldco/swagger-to-ts three.yaml -o three.ts" >

You can even specify unique options per-spec, if needed. To generate them all together, run:

Rinse and repeat for more specs.

For anything more complicated, or for generating specs dynamically, you can also use the Node API.

Option Alias Default Description
—output [location] -o (stdout) Where should the output file be saved?
—prettier-config [location] (optional) Path to your custom Prettier configuration for output
npm i --save-dev @manifoldco/swagger-to-ts
const  readFileSync > = require("fs"); const swaggerToTS = require("@manifoldco/swagger-to-ts"); const input = JSON.parse(readFileSync("spec.json", "utf8")); // Input can be any JS object (OpenAPI format) const output = swaggerToTS(input); // Outputs TypeScript defs as a string (to be parsed, or written to a file)

The Node API is a bit more flexible: it will only take a JS object as input (OpenAPI format), and return a string of TS definitions. This lets you pull from any source (a Swagger server, local files, etc.), and similarly lets you parse, post-process, and save the output anywhere.

If your specs are in YAML, you’ll have to convert them to JS objects using a library such as js-yaml. If you’re batching large folders of specs, glob may also come in handy.

In order to allow more control over how properties are parsed, and to specifically handle x-something -properties, the propertyMapper option may be specified as the optional 2nd parameter.

This is a function that, if specified, is called for each property and allows you to change how swagger-to-ts handles parsing of Swagger files.

An example on how to use the x-nullable property to control if a property is optional:

const getNullable = (d:  [key: string]: any >): boolean =>  const nullable = d["x-nullable"]; if (typeof nullable === "boolean")  return nullable; > return true; >; const output = swaggerToTS(swagger,  propertyMapper: (swaggerDefinition, property): Property => ( . property, optional: getNullable(swaggerDefinition), >), >);

Thanks to @atlefren for this feature!

Some options were removed in swagger-to-ts v2 that will break apps using v1, but it does so in exchange for more control, more stability, and more resilient types.

-import < OpenAPI2 >from './generated'; +import < definitions >from './generated'; -type MyType = OpenAPI2.MyType; +type MyType = definitions['MyType'];

In order to explain the change, let’s go through an example with the following Swagger definition (partial):

swagger: 2.0 definitions: user: type: object properties: role: type: object properties: access: enum: - admin - user user_role: type: object role: type: string team: type: object properties: users: type: array items: $ref: user

This is how v1 would have generated those types:

declare namespace OpenAPI2  export interface User  role?: UserRole; > export interface UserRole  access?: "admin" | "user"; > export interface UserRole  role?: string; > export interface Team  users?: User[]; > >

Uh oh. It tried to be intelligent, and keep interfaces shallow by transforming user.role into UserRole. However, we also have another user_role entry that has a conflicting UserRole interface. This is not what we want.

v1 of this project made certain assumptions about your schema that don’t always hold true. This is how v2 generates types from that same schema:

export interface definitions  user:  role?:  access?: "admin" | "user"; >; >; user_role:  role?: string; >; team:  users?: definitions["user"][]; >; >

This matches your schema more accurately, and doesn’t try to be clever by keeping things shallow. It’s also more predictable, with the generated types matching your schema naming. In your code here’s what would change:

-UserRole +definitions['user']['role'];

While this is a change, it’s more predictable. Now you don’t have to guess what user_role was renamed to; you simply chain your type from the Swagger definition you‘re used to.

swagger-to-ts v1 would attempt to resolve and flatten $ref s. This was bad because it would break on circular references (which both Swagger and TypeScript allow), and resolution also slowed it down.

In v2, your $ref s are preserved as-declared, and TypeScript does all the work. Now the responsibility is on your schema to handle collisions rather than swagger-to-ts, which is a better approach in general.

The —wrapper CLI flag was removed because it was awkward having to manage part of your TypeScript definition in a CLI flag. In v2, simply compose the wrapper yourself however you’d like in TypeScript:

import  components as Schema1 > from './generated/schema-1.ts'; import  components as Schema2 > from './generated/schema-2.ts'; declare namespace OpenAPI3  export Schema1; export Schema2; >

The —camelcase flag was removed because it would mangle object names incorrectly or break trying to sanitize them (for example, you couldn’t run camelcase on a schema with my.obj and my-obj —they both would transfom to the same thing causing unexpected results).

OpenAPI allows for far more flexibility in naming schema objects than JavaScript, so that should be carried over from your schema. In v2, the naming of generated types maps 1:1 with your schema name.

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!

About

Generate TypeScript types from Swagger OpenAPI specs

Источник

Читайте также:  Redirect from header php
Оцените статью