README
OpenAPI Typescript Codegen
NodeJS library that generates Typescript clients based on the OpenAPI specification.
Why?
- Frontend ❤️ OpenAPI, but we do not want to use JAVA codegen in our builds.
- Quick, lightweight, robust and framework agnostic.
- Supports generation of Typescript clients.
- Supports generations of fetch and XHR http clients.
- Supports OpenAPI specification v2.0 and v3.0.
- Supports JSON and YAML files for input.
Known issues:
- If you use enums inside your models / definitions then those enums are now inside a namespace with the same name as your model. This is called declaration merging. However, Babel 7 now support compiling of Typescript and right now they do not support namespaces.
Installation
npm install openapi-typescript-codegen --save-dev
Example
package.json
{
"scripts": {
"generate": "openapi --input ./api/openapi.json --output ./dist"
}
}
Command line
npm install openapi-typescript-codegen -g
openapi --input ./api/openapi.json --output ./dist
NodeJS API
const OpenAPI = require('openapi-typescript-codegen');
OpenAPI.generate({
input: './api/openapi.json',
output: './generated'
});
Or by providing the JSON directly:
const OpenAPI = require('openapi-typescript-codegen');
const spec = require('./api/openapi.json');
OpenAPI.generate({
input: spec,
output: './generated'
});
Features
Argument-style vs. Object-style
There's no named parameter in Javascript or Typescript, because of
that, we offer the flag --useOptions
to generate code in two different styles.
Argument-style:
function createUser(name: string, password: string, type?: string, address?: string) {
// ...
}
// Usage
createUser('Jack', '123456', undefined, 'NY US');
Object-style:
function createUser({ name, password, type, address }: {
name: string,
password: string,
type?: string
address?: string
}) {
// ...
}
// Usage
createUser({
name: 'Jack',
password: '123456',
address: 'NY US'
});
Runtime schemas
By default the OpenAPI generator only exports interfaces for your models. These interfaces will help you during
development, but will not be available in javascript during runtime. However, Swagger allows you to define properties
that can be useful during runtime, for instance: maxLength
of a string or a pattern
to match, etc. Let's say
we have the following model:
{
"MyModel": {
"required": [
"key",
"name"
],
"type": "object",
"properties": {
"key": {
"maxLength": 64,
"pattern": "^[a-zA-Z0-9_]*