Coder Social home page Coder Social logo

swagger-codegen-ts's Introduction

Build Status

Typesafe OpenAPI generator for TypeScript

Features

  • Generates client code from OpenAPI 3.0, 2.0 (aka Swagger) and AsyncAPI specs
  • Pluggable HTTP clients: can use fetch, Axios or any other library
  • Flexible response types: works with Promises and reactive streams like RxJS
  • Runtime type checks: validates server responses against the spec
  • Written in pure TypeScript using fp-ts and io-ts libraries

Demo code

The examples below refer to the Pet Store OpenAPI 3.0 schema.

After running the codegen, interacting with a REST API may be as simple as this:

import { petController as createPetController } from "./src/generated/petstore.json/paths/PetController";
import { Pet } from "./src/generated/petstore.json/components/schemas/Pet";

// Creating a controller, see the "HTTP Clients" wiki page for more details
const petController = createPetController({ httpClient: fetchHttpClient });

// The returned object is guaranteed to be a valid `Pet`
const createdPet: Promise<Pet> = petController.addPet({
  body: {
    // The parameters are statically typed, IntelliSense works, too
    name: "Spotty",
    photoUrls: [],
  },
});

More usage scenarios are supported - check the usage page for more detail.

Installation

  1. Make sure the peer dependencies are installed, then install the codegen itself:

    yarn add typescript fp-ts io-ts io-ts-types
    yarn add -D @devexperts/swagger-codegen-ts
    
  2. Create a console script that would invoke the generate function, passing the options such as path to the schema file and the output directory. See the Generators page for the API reference, and examples/generate for sample scripts.

  3. In most cases, you might want to include the code generation step into the build and local launch scripts. Example:

    /* package.json */
    
      "scripts": {
    +   "generate:api": "ts-node scripts/generate-api.ts",
    -   "start": "react-scripts start",
    +   "start": "yarn generate:api && react-scripts start",
    -   "build": "react-scripts build"
    +   "build": "yarn generate:api && react-scripts build"
      }

Contributing

Please read the Contributors Guide for more information.

swagger-codegen-ts's People

Contributors

alexeymatveevp avatar alextsk avatar andr3medeiros avatar coolassassin avatar dependabot[bot] avatar dramoturg avatar geksanit avatar ipavelleds avatar kokovtsev avatar lonelind avatar mankdev avatar nedgeva avatar nikolaenkov avatar raveclassic avatar reviewpad[bot] avatar scink avatar sutarmin avatar vkamotin avatar zugaz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swagger-codegen-ts's Issues

Fix generation of entities with the same name in one file

components:
  schemas:
    echo:
      description: echo
      type: string
  messages:
    echo:
      payload:
        $ref: '#/components/schemas/echo'

This piece will result in

import { echo, echoIO } from '../../components/schemas/echo';

export type echo = echo;
export const echoIO = echoIO;

We need to find a way to avoid such conflicts. Possibly using named imports.

Remove all paths from configuration

  • replace pathsToSpec with a list of parsed spec objects

    • supports any spec format, not only json/yaml)
    • support for specs loaded from network or any other source, not only from disk
  • return TFSEntity from generate instead of accepting out parameter

    • supports for any output format, not only writing to disk
  • remove pathToPrettierConfig

    • prettier should be a part of typescript language done in #51
  • remove fileReader

    • "files" are one of many possible sources and should be handled outside of the lib done in #51

Support foreign references in parameters directly

parameters:
  - name: times
    in: query
    schema:
      $ref: './shared.yaml#/components/times'

Current implementation assumes that there will be a separate run of generation for referenced entities in foreign spec. However such generation is only run for local references in local components section.

Support `file` types

OpenAPI 3.0:

  • Requests:
    • single file uploads
    • upload as part of a multipart request
    • file array in a multipart request
  • Responses:
    • single application/octet-stream or text/plain file - done in #129
    • other types such as application/pdf or text/xml
    • embedded files (type: string + format: byte)

ResponseValidationError considered to be unsafe?

After getting some run-time exceptions in one app i took a closer look at ResponseValidationError implementation. Things that wonders me:

  1. why you're setting prototype of ResponseValidationError class to itself via setPrototypeOf? Isn't it's better to use Symbol.hasInstance for hooking instanceof?
  2. ResponseValidationError isn't safe because it's cannot be safely stringifed. Is this intended?

For example following code would produce run-time exceptions:

const failedValidation = pipe(
  fromEither(SomeCoded.decode(someInvalidData)),
  mapLeft<Errors, Error>(ResponseValidationError.create),
);
<RenderRemoteData data={failedValidation} ... />

where RenderRemoteData is something like

interface RenderRemoteDataProps<L, A> {
  data: RemoteData<L, A>;
  failure?: (e: L) => ReactNode;
  ...blah-blah-blah
}

const failureDefault = (e: Error) => (<div>{e.name}: {e.message}</div>);

const Component = <L, A>({
  data,
  failure = flow(toError, /* <-- downcasting ResponseValidationError to Error would cause exception like Uncaught TypeError: Function.prototype.toString requires that 'this' be a Function */ failureDefault),
}: RenderRemoteDataProps<L, A>) => {
  const error = useMemo(() => (e: L) => {
    console.warn('[RemoteDataFailure]', e);
    return failure(e);
  }, [failure]);

  return (
    {isFailure(data) && error(data.error)}
    <Blah />
  );
}

Would like to hear any thoughts on this.

Void response missing if there are response codes with non-void schema

When an operation defines multiple response codes including void responses (no body), the generated code does not handle void responses.

Example:

responses:
  204:
    description: Successful operation
  400:
    description: Request malformed
  404:
    description: Product not found
    schema: { $ref: "#/definitions/InstrumentOperationReject" }
  422:
    description: Product deletion failed
    schema: { $ref: "#/definitions/InstrumentOperationReject" }

Generated code (fragment):

e.httpClient.chain(
	e.httpClient.request({ /* ... */ })
	pipe(
		InstrumentOperationRejectIO.decode(value),	// undefined shall not pass
		either.mapLeft(ResponseValidationError.create),
		// ...
	)
)

test-api.yml.zip
test-api.zip

swagger-codegen-ts doesn't work with latest fp-ts and io-ts

swagger-codegen-ts have the following dependencies in package.json:

 "fp-ts": "^1.10.0",
 "io-ts": "^1.2.1",

Currently, when installed through npm it pulls up following versions:

 "fp-ts": "1.13.0",
 "io-ts": "1.8.1",

The problem is that with these versions of fp-ts and io-ts it doesn't work. It fails to generate code given valid spec file with huge and uninformative log.
As a hotfix, I'll lock minor versions of deps using ~ instead of ^.

To be done:

  • 1. Research and fix problems with newer versions
  • 2. Decide whether we will continue using ~ and upading versions manually or switch back to ^ when problem is resolved.

Update `from: Ref` tracking mechanism

Current implementation ties inner schema structure (paths, definitions, components etc.) to output directories so that we cannot use different names and directory structure.
We should split schema and fs cursors: from: Ref should track position in schema structure (e.g. #/components/schemas/Model and path: string - current file/directory in fs.

CLI wrapper

Do you want to be able to use this instrument as a command line tool?

Controllers are generated with unused variable

After starting generate I receive an error in generated controllers.
The error is
image

generate function is same as test1 in tests

Libs:

"fp-ts": "^2.4.4",
"io-ts": "^2.0.1",
"io-ts-reporters": "^1.0.0",
"io-ts-types": "^0.5.2",
"@devexperts/swagger-codegen-ts": "^2.0.0-alpha.17",
"@devexperts/utils": "^1.0.0-alpha.11",

System: win10

Also, I checked tests here and got the same result.

STR:

  • clone project
  • yarn install
  • yarn test:run

image

Move to Yarn

We have yarn as the de facto standard for our projects, but this one doesn't contain yarn lock file. Is it for purpose or what? @raveclassic @scink

Setup monorepo with lerna

As the codebase grows, new languages and specs are added, to better control tests and builds we need to turn the project to monorepo and split the code into several subpackages:

  • @devexperts/swagger-codegen-ts/core
  • @devexperts/swagger-codegen-ts/spec/swagger-2
  • @devexperts/swagger-codegen-ts/spec/openapi-3
  • @devexperts/swagger-codegen-ts/languageserializer/typescript-swagger-2
  • @devexperts/swagger-codegen-ts/languageserializer/typescript-openapi-3

Suggestions are welcome.

/cc @sutarmin @scink

multifile and crossfile references

there are cases when you have several spec files. it causes need to proceed several files in one go. and there might be references to other files. we need to support such cases

AllOf with recursion

When type, built with allOf, references itself, TS raises following error:

[ts] 'FieldFilterExpressionTreeIO' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer. [7022]

We need to determine if there is such a circular reference and add recursion to the codec in such case.

OpenAPI 3.0 support

  • rename swagger.ts to swagger-2.0.ts see #43
  • add openapi-3.0.ts as additional parser and implement OpenAPI 3.0 spec
  • support parser configuration
  • add typescript language template for OpenAPI 3.0

Support arbitrary strings as names of entities

  • current implementation doesn't process names in any way so that for names like Foo.Bar.Baz we generate interface Foo.Bar.Baz which is invalid TS
  • we need to remove any invalid characters from all names when generating TS

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.