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.
-
Install module
npm install simple-ts-express-decorators
yarn add simple-ts-express-decorators
-
Install
reflect-metadata
npm install reflect-metadata
yarn add reflect-metadata
-
Import
reflect-metadata
before using provided decorators -
Enable typescript decorators in your
tsconfig.json
{ "emitDecoratorMetadata": true, "experimentalDecorators": true }
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);
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 |