There are several tools available that can help generate an OpenAPI specification from a TypeScript type declaration. Here are a few options:
/**
* @swagger
*
* definitions:
* User:
* type: object
* properties:
* firstName:
* type: string
* lastName:
* type: string
*/
interface User {
firstName: string;
lastName: string;
}
import { OpenAPIV3 } from 'ts-openapi';
interface User {
firstName: string;
lastName: string;
}
const schema: OpenAPIV3.Document = {
openapi: '3.0.0',
info: {
title: 'My API',
version: '1.0.0',
},
paths: {
'/users': {
get: {
summary: 'Get a list of users',
responses: {
'200': {
description: 'OK',
content: {
'application/json': {
schema: {
type: 'array',
items: {
$ref: '#/components/schemas/User',
},
},
},
},
},
},
},
},
},
components: {
schemas: {
User: {
type: 'object',
properties: {
firstName: {
type: 'string',
},
lastName: {
type: 'string',
},
},
},
},
},
};
import { createConnection } from 'typeorm';
import { routingControllersToSpec } from 'routing-controllers-openapi';
import { UserController } from './controllers';
async function getApiSpec() {
const connection = await createConnection();
const routingControllersOptions = {
controllers: [UserController],
};
const spec = routingControllersToSpec(routingControllersOptions, {}, {
components: {
schemas: {
...connection.options.entities.reduce((acc, entity) => {
acc[entity.name] = {
type: 'object',
properties: entity.columns.reduce((innerAcc, column) => {
innerAcc[column.propertyName] = {
type: column.type,
};
return innerAcc;
}, {}),
};
return acc;
}, {}),
},
},
});
await connection.close();
return spec;
}
const apiSpec = await getApiSpec();
These are just a few examples of the tools available for generating OpenAPI schemas from TypeScript types. Choose the one that best fits your needs and preferences.
Asked: 2021-06-04 11:00:00 +0000
Seen: 14 times
Last updated: Dec 23 '22