node package manager
Stop writing boring code. Discover, share, and reuse within your team. Create a free org »

tsrest

TSRest

Take advantage of the newest TypeScript features like decorators to create REST services while maintaining a nice code style.

This framework is still under development it is not yet recommended for production use.

GETting started

import {Application, GET, route, pathParam} from 'tsrest';
import {Request, Response} from 'express';
 
@route('/hello')
class HelloController {
    @GET
    index() {
        return "Hello from index"
    }
 
    @GET
    @route('/:id')
    one(@pathParam('id') id: String) {
        return `object by id: ${id}`;
    }
 
}
 
class MyApp extends Application {
    constructor() {
        super();
 
        // Index
        // Access the express object directly
        this.express.GET('/', (req: Request, res: Response) => {
            res.send('Hello world');
        });
 
        // Register our resorce
        this.registerController(new HelloController());
    }
 
    public onbeforeApplicationStart() {
    }
 
}
 
let api: MyApp = new MyApp();
api.start();

CLI

TODO: Fill me

API

Application / General

export class Application {
    protected static instance: Application;
    protected express: express.Application;
    protected server: http.Server;
 
    public Host: string = 'localhost';
    public Port: number = 3000;
    public Prefix: string;
 
    // -- Hooks
    onbeforeApplicationStart() {}
    onAfterApplicationStart() {}
 
    /**
     * Registers a Controller class to expose to the rest api
     * @param ControllerClass Class containing the rest methods
     */
    public registerController(ControllerClass: any) {}
 
    /**
     * Start the http server
     */
    public start() {}
}

REST Decorators

Just annotate GET, POST, DELETE or PUT to the function which is supposed to handle the request like so:

@GET
index() {
    return "Hello from index"
}

route-Parameter

@GET
@route('/:id')
public one(@pathParam('id') id: string) {
    return `object by id: ${id}`;
}

Body-Parameter

@POST
public add(@requestBody(String) item: String) {
    // insert item and return a status
}

Both

@PUT
@route('/:id')
public update(@pathParam('id') id: string,
              @requestBody(String) item: String): any {
    // insert item and return a status
}

Middleware

 
 
function testHook(req: any, res: any, next: any) {
  console.log("testHook called!");
 
  next();
}
 
@route('/hello')
class HelloController {
    @GET
    index() {
        return "Hello from index"
    }
 
    @GET
    @route('/:id')
    @before(testHook)
    one(@pathParam('id') id: String) {
        return `object by id: ${id}`;
    }
 
}

Changelog

1.0

  • Added before and after hooks

1.0.1

  • Renamed exprted functions (except rest methods) to lowercase
  • Renamed route to route
  • Renamed Controller to Controller (registerController -> registerController)