expressts-router

Routing Decorators for Express apps

Usage no npm install needed!

<script type="module">
  import expresstsRouter from 'https://cdn.skypack.dev/expressts-router';
</script>

README

Express TS Router

A simple library which uses powerful Typescript feature - Decorator - to create Routes for express with typescript application

Installation

Using npm/yarn:

$ npm i -s expressts-router
$ yarn add expressts-router

Set these 2 properties in your tsconfig.json

"experimentalDecorators": true
"emitDecoratorMetadata": true

Usage

1. Environment variable
Define a path pattern to your controller files by adding 'X_CONTROLLERS_PATH' environment variable in your .env file.
If no value specified, the default path pattern will be 'dist/controllers/*/.controller.js'
Note The path pattern must lead to the compiled .js files, not the .ts file

2. Create your controller class:
For example, I created a file 'src/controllers/value.controller.ts'
In 'value.controller.ts':

import { Controller } from "expressts-router"

// You can specify the prefix to this controller by passing a string to @Controller decorator
// Ex: By passing '/value' to the @Controller decorator, the prefix to this controller will be '{host}/value'
@Controller('/value')
export class ValueController {

}

Define your request handler in 'value.controller.ts':

import { Request, Response, NextFunction } from "express"
import { 
    Controller,
    Get,
    Post
} from "expressts-router"
import { someMiddleware } from '../middlewares'

@Controller('/value')
export class ValueController {
    // Use @Get decorator to define a GET request handler
    @Get({ path: '' })
    getValues(req: Request, res: Response, next: NextFunction) {
        res.json(['value1', 'value2'])
    }

    // There are other decorators for POST, PUT, PATCH, DELETE methods as well
    @Post({ path: '' })
    createValue(req: Request, res: Response, next: NextFunction) {
        // TODO: Create value
    }

    // You can also use middlewares
    @Get({
        path: '/with-middleware',
        middlewares: [ someMiddleware ]
    })
    getValuesWithMiddlewares(req: Request, res: Response, next: NextFunction) {
        res.json(['value1', 'value2'])
    }
}

In your root file (usually index.ts or app.ts):

  • If you want to use async/await:
import express from 'express'
import { createRoutes } from 'expressts-router'
const app = express()

const startApp = async () => {

    app.use(await createRoutes())

    app.listen(3000, () => {
        console.info(`Server is running on port 3000`)
    })
}
startApp()
  • If you want to use promise:
import express from 'express'
import { createRoutes } from 'expressts-router'
const app = express()

// create routes and return the router
createRoutes().then(router => {
    // use created router
    app.use(router)
})

app.listen(3000, () => {
    console.info(`Server is running on port 3000`)
})
startApp()

That's all!!
Open http://localhost:3000/value on your browser
The response should be

['value1', 'value2']

Exports

createRoutes(router: Router): Router

Create routes and return the router
Parameters:
- router?: Router object created by Router() function from 'express'. If router is undefined, create new Router
Returns:
- router: Router object which has routes defined

Controller(prefix: string)

Define a controller
Parameters:
- prefix: string - the url prefix to access to the controller, default to ''

Get(httpActionOptions: HTTPActionOptions)

Define a GET request handler

Post(httpActionOptions: HTTPActionOptions)

Define a POST request handler

Patch(httpActionOptions: HTTPActionOptions)

Define a PATCH request handler

Put(httpActionOptions: HTTPActionOptions)

Define a PUT request handler

Delete(httpActionOptions: HTTPActionOptions)

Define a DELETE request handler

HTTPActionOptions:

  • path: string
  • middlewares?: RequestHandler[] - an array of Express's request handlers

Change logs

1.1.0: Add new export getControllers