Giter VIP home page Giter VIP logo

typoas's Introduction

Typoas

npm npm npm GitHub npm bundle size

Typoas is an OpenAPI 3.X generator for Typescript. It's inspired by openapi-generator but is written in Typescript for Typescript. The generator uses the Typescript AST to generate code instead on relaying on templates which allows better schemas definitions and other cool stuff.

Main features are:

  • Fully typed and fully customizable
  • References $ref handling (including cyclic refs)
  • Tree Shaking out of the box
  • Support for allOf, oneOf and anyOf schemas.
  • Automatically convert format: 'date-time' to JS Date
  • Handle API Key, HTTP Config and OAuth21 auth security schemes
  • JSDoc for schemas and operations
  • Uses fetch api (can be customized)
  • Non JSON content type support
  • Small bundle size
  • And more...

1: OAuth2 scheme does not handle flows to retrieve an accessToken. You need to provide your own accessToken through the provider.getConfig() function.

The project is split into 3 parts:

Installation

It will generate a single TS file containing all the code specific to the underlying API. This file only has a single dependency on @typoas/runtime. You need to manually add @typoas/runtime to your dependencies. It handles common things like serialization/authentification

Usage

Ues the generator from the CLI

You can generate the TS client from the spec from the command line:

yarn dlx @typoas/cli generate -i my-spec.json -o src/client.ts
npx @typoas/cli generate -i my-spec.json -o src/client.ts

Here is a short list of supported command line options:

    -i, --input [path/url]         Path or URL to the OpenAPI JSON specification (yaml/json format)
    -o, --output [path]            Path where to write the generated TS file
    -e,--generate-enums            Generate enums instead of literal string types where possible
    --js-doc, --no-js-doc          Whether to add JS Doc to the generated code (default: true)
    --wrap-lines-at                Define a maximum width for JS Doc comments, 0 to disable (default: 120)
    --only-types                   Use it to only generate types in #components/schemas/
    --no-fetcher-options           Use it to disable the additional param added to every operations
    --version                      Output the version number
    -h, --help                     Display help for command

    -n, --name                     Deprecated, name isn't used anymore

or you can use it in code:

import cli from '@typoas/cli';

await cli.run(
  [
    'generate',
    '-i',
    'https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.yaml',
    '-o',
    `./src/github.ts`,
  ],
  {
    stdin: process.stdin,
    stdout: process.stdout,
    stderr: process.stderr,
  },
);

Use the generator from the API

The API is still at an alpha stage, so it may break between minors.

It uses typescript API to generate usable code:

import { readFileSync, writeFileSync } from 'fs';
import { createPrinter, NewLineKind, SourceFile } from 'typescript';
import { generateClient, getStringFromSourceFile } from '@typoas/generator';

const specs = JSON.parse(readFileSync('path/to/github-openapi.json', 'utf8'));
const src = generateClient(specs, {
  /* options */
});
const data = getStringFromSourceFile(src);

writeFileSync('./src/client.ts', data, 'utf8');

Use the generated code

Once the file is generated you'll be able to use it like this:

import { ServerConfiguration } from '@typoas/runtime';
import { createContext, pullsList } from './client';

const ctx = createContext();

pullsList(ctx, {
  repo: 'typoas',
  owner: 'embraser01',
})
  .then((list) => console.log('List of PRs', list))
  .catch((err) => console.error('Error while getting PRs', err));

The default fetch implementation is used (included in Node.js >= 18.0.0). You can always override the default fetch implementation in createContext

Examples

You can find examples in the examples folder.

Notes

Here is some notes on some known issues.

External references

External references are not supported. Every $ref must be in the spec. An issue is open here.

Parameters serialization

Typoas has partial support for serialization specified here: https://swagger.io/docs/specification/serialization/

  • It does support array serialization for query.
  • It does NOT support serialization for path parameters with style label or matrix.
  • It does NOT support serialization for query parameters with nested objects. It will be JSON.stringify
  • It does NOT support serialization for headers or cookie parameters.

On query serialization, there can only be one style for a full operation. The first query param will set the style for the whole operation.

Migrating from v1 to v2

In v1, the whole API was generated in a single class. In V2 this was replaced by individual function which allow Tree Shaking. To get a similar result, you can use wrapApi helper:

import { ServerConfiguration, wrapApi } from '@typoas/runtime';
import { createContext, pullsList, issuesList } from './client';

const ctx = createContext();
const ghClient = wrapApi(ctx, {
  pullsList,
  issuesList,
  // ...
});

ghClient
  .pullsList(ctx, {
    repo: 'typoas',
    owner: 'embraser01',
  })
  .then((list) => console.log('List of PRs', list))
  .catch((err) => console.error('Error while getting PRs', err));

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

License

MIT

typoas's People

Contributors

embraser01 avatar friday avatar richardgarnier 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

Watchers

 avatar  avatar  avatar

typoas's Issues

Support timeout option

Client should handle timeout (number in ms) to override default browser timeout behavior.
Doing it with axios is quite easy :

resp = await axiosClient.request({
        url: request.getUrl(),
        method: request.getHttpMethod() as Method,
        headers: request.getHeaders(),
        data: request.getBody(),
        timeout: 3000 // will abort promise if it takes more than 3 sec 
});

I don't know how to do it so far in generated client. I guess a good place would be to put it in RequestContext. The tricky part is to be able to override it in the generated api functions.

incorrect TS generated when param name is like `page[number]`

when a param name (in this case query param) contains square brackets, it ends up generating types like this:

 {
    page[number]?: number;
    page[size]?: number;
    filter[search]?: string;
}

which is invalid TS. they need to be quoted. this style of query param is standard for JSONAPI

CLI running as shell script instead of nodejs

I tried to run the CLI with npx @typoas/cli generate but it looks like it's trying to run the CLI as a shell script.

.npm/bin/cli: line 1: use strict: command not found
.npm/bin/cli: line 2: syntax error near unexpected token `exports,'
.npm/bin/cli: line 2: `Object.defineProperty(exports, "__esModule", { value: true });'

After manually adding a shebang like this it works:

#!/usr/bin/env node

Is this not the expected usage? Or maybe this is a yarn vs npm difference?

Running the cli in Windows results in a crash

I ran the following command : npx @typoas/cli generate -i http://localhost:3232/api-json -o dist/client/client.ts

Then, the bin.js script is executed in the windows script host interpreter instead of NodeJS

image

multipart/form-data Should not be set so the boundry can be set automatically

requestContext.setHeaderParam(
CONTENT_TYPE_HEADER,
'multipart/form-data',
);

Based on my understanding of how browsers handle FormData, we want to make sure that this is NOT set so that the correct header can be added automatically right?

See MDN FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects#sect4

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.