Skip to content

Latest commit

 

History

History
104 lines (73 loc) · 2.73 KB

README.md

File metadata and controls

104 lines (73 loc) · 2.73 KB

Simple typescript decorators for express

Build Coverage Status

Simple controller and methods typescript decorators for express. Inspired by ts-decorator-routing

Provides pure request and response from express without complicated handlers or transformers.

Installation

  1. Install module

    npm install simple-ts-express-decorators
    yarn add simple-ts-express-decorators
    
  2. Install reflect-metadata

    npm install reflect-metadata
    yarn add reflect-metadata
    
  3. Import reflect-metadata before using provided decorators

  4. Enable typescript decorators in your tsconfig.json

    {
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true
    }

Example of usage

UsersController.ts

import {Controller, Get} from 'simple-ts-express-decorators'; 
import {Request, Response, RequestHandler} from 'express';
import multer, {memoryStorage} from 'multer';

const upload = multer({storage: memoryStorage()});

const logMiddleware: RequestHandler = (req, res, next) => {
  console.log('log');

  next();
};

@Controller('/', logMiddleware)
export class UsersController {

  @Get('/users')
  index(request: Request, response: Response) {
    response.json([
      {id: 1, username: 'example'}
    ]);
  }

  @Post('/users', upload.sindle('avatar')) // example of usage with middleware
  create(request: Request, response: Response) {
    const avatar = request.file;

    // ...save

    response.status(201);
  }
}

index.ts

import "reflect-metadata";
import * as express from 'express';
import {ControllersLoader} from 'simple-ts-express-decorators';
import {UserController} from './UserController'; 

const app = express();

new ControllersLoader({
  controllers: [UserController]
}).load(app);

app.listen(3000);

Configuration options

Option Description
controllers Required. Array of controllers to load or array of glob patterns to load controllers from
container Any container implementation with get() method. For example InversifyJS