npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

typoa

v1.0.0-alpha.49

Published

Help you generate OpenAPI definitions via Typescript

Downloads

571

Readme

This tools is inspired from tsoa, the purpose is to be able to generate openapi definitions and express routes definitions via Typescript typings.

We're using ts-morph under the hood.

codecov

Why

Tsoa is a great package and it's working fine for simple typescript typings, which I think are principal use cases, it's used by many developers and maintained.

BUT, I've used tsoa in production projects and I've encountered many issues (I was able to fix some of them), but when I've tried to use more complex types (inheritance, deep generics, conditionnal types...) tsoa wasn't able to provide me good openapi definitions, and without even telling me it failed to generate the right schema.

I've spent a lot of time trying to fix those issues, using tricks to have a workaround. But it was never perfect, I've ended with too many duplicated types only because tsoa was not able to resolve correct typings. I wasn't confident when updating my models and I was always checking that the swagger wasn't broken.

And all of this issues are caused by the custom type resolver of tsoa, in this package we're using ts-morph, it allows us to build a resolver more resilient that handle all cases without maintenance on our side.

Features

  • Generate express router via typescript decorators in controllers
  • Generate openapi definition via typescript typings
  • Allowing to export custom types to openapi schema
  • Runtime validation against openapi schema
  • Use jsdoc for additionnal configuration (example, regex...)
  • Handle getters only and readonly properties

How to use

Define your controllers

You only need to add the @Route() decorator at the top of your controller class and @Get(), @Post()... at the top of each method definition, like this:

import { Route, Get } from 'typoa'

@Route()
class MyController {
  @Get()
  public get () {}
}

You can provide the route path in the @Route() decorator or in each verb decorators (eg. @Get...) or both.

You also will need to extends the Controller class if you want to override the default HTTP status (200 if your method return content, 204 if not):

import { Route, Get, Controller } from 'typoa'

@Route('/controller-path')
class MyController extends Controller {
  @Get('/method-path')
  public get () {
    this.setStatus(201)
    return 'Created'
  }
}

To send data to the client you only need to return your data, typoa will use res.json() with it. If you return a stream, typoa will stream it to the client.

Body, Query, Path, Header and Request

To use the parsed (and validated) body from typoa you only need to provide the @Body() decorator:

import { Route, Get, Controller } from 'typoa'

@Route('/controller-path')
class MyController extends Controller {
  @Post('/method-path')
  public post (
    @Body() body: { name: string }
  ) {
    this.setStatus(201)
    return 'Created'
  }
}

This is the same for query parameters (@Query('<name>')), path parameters (@Path('<name>')) and headers (@Header('<name>')).

You also can use the @Request() decorator if you need to access the express request.

Note: You can see more examples in the example/ folder.

Body discrimination

Sometimes you want to validate the body against a specific schema depending on which resource the user try to update...

To handle that, you can provide a discriminator function to the body decorator:

import { Route, Get, Controller, BodyDiscriminatorFunction } from 'typoa'

type TypeA = { name: string }
type TypeB = { name: number }

// The function need to return the name of the type you want to validate against
export const discriminatorFunction: BodyDiscriminatorFunction = async (req) => 'TypeA'

@Route('/controller-path')
class MyController extends Controller {
  @Post('/method-path')
  public post (
    @Body(
      'application/json', // body content-type
      discriminatorFunction // name of the function you want to use
    ) body: TypeA | TypeB
  ) {
    this.setStatus(201)
    return 'Created'
  }
}

Generate

To generate the openapi definition and the router you will need to bind to express, you only need to call the generate method of typoa:

await generate({
  tsconfigFilePath: path.resolve(__dirname, './tsconfig.json'),
  controllers: [path.resolve(__dirname, './*.ts')], // Path of your controllers
  openapi: {
    filePath: '/tmp/openapi.json', // Where do you want to generate your openapi file
    format: 'json', // 'json' | 'yaml'
    service: { // Used in the openapi definitions
      name: 'my-service',
      version: '1.0.0'
    },
    securitySchemes: { // Openapi securitySchemes definitions
      company: {
        type: 'apiKey',
        name: 'x-company-id',
        in: 'header'
      }
    }
  },
  router: {
    filePath: './router.ts', // Where do you want to generate the router file
    securityMiddlewarePath: './security.ts' // Optional, middleware called if you use the @Security() decorator
  }
})