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

ts-api

v3.4.8

Published

Create documented REST API using controllers and interfaces in typescript

Downloads

47

Readme

TS-API

APIs in NodeJS should have a single source of truth for api specs between code and docs, as well as compile time type safety.

Schemas are often duplicated between json schemas for input validation, typescript types, jsdoc comment annotations or swagger-specific wrappers in your app. Routes and response status codes also suffer from similar issues where code can get out of sync with documentation.

TS-API solves this by leveraging the typescript parser to generate:

  • OpenAPI (Swagger) docs
  • Runtime type checks with Json schemas
  • ExpressJS routes to be mounted
  • Optional correctness verification of status code <-> result type mapping

Concepts

Type conversion

TypeScript types are extracted from the source code, such as this example:

export interface User {
    name: string;
    isActive?: boolean;
}

is converted to a json schema:

  "User": {
    "type": "object",
    "properties": {
      "name": {
        "type": "string"
      },
      "isActive": {
        "type": "boolean"
      }
    },
    "required": [
      "name"
    ]
  }

Route Generation

@controller('/user')
export class User extends ControllerBase {

  @get('/')
  async listUsers(): Promise<User[]> {
  ...
  return [{ ...account1 }, ...]
  }

The controller and Rest verbs (get, post, put, etc.) optionally take a route override, otherwise it uses the class or method name by default.

A router tree is build by TS-API from all controllers in the typescript path:

AccountRouter.get('/', async(req,res,next) => { ... }

You can mount this anywhere in your app, use middleware, and treat it like any other ExpressJS router. The controller gives full access to req/res/next in the constructor. There's further customizations support, such as hooks to customize input validation, but by default it returns a 400 status.

OpenAPI (Swagger) docs

OpenAPI 3 output for a sample controller:

Swagger Screenshot

ReDoc is also supported as viewer.

Usage

Install

npm install --save-dev ts-api

First make this package a dependency. This will provide the necessary decorators @controller, @router @get @post, etc. The analyzer will search for those names and generate code that uses them, but these decorators also do things themselves like invoke the runtime type checker.

Create appropriately annotated classes and methods.

The key steps are:

  1. Create a class that extend the base controller
  2. Add a controller decorator to the class
  3. Decorate methods that represend API endpoints
  4. Use typescript interfaces for type declarations in the method arguments/response

See an example controller for a working reference.

Import the router and use in your app

@router('/api')
export default class Router extends RouterBase {
  constructor(app: any) {
    super(app);
    require('./__routes')(this);
  }
}

Run cg after typescript compiling your code

The easiest way to do this is an npm script (or npm install -g):

tsc && cg

The cg CLI tool can take options and specific files:

cg <options> <list of files>

Run your app

You can verify output by using the hosted docs. The route will depend on where you mount the app, such as:

http://localhost:3002/api/docs

License

Apache 2.0