Build your TypeScript v2 application with Express decorators ! Support ES5 and ES6.
- Define class as Controller,
- Define class as Service (IoC),
- Define class as Middleware and MiddlewareError,
- Define class as Converter (POJ to Model and Model to POJ),
- Define root path for an entire controller and versioning your Rest API,
- Define as sub-route path for a method,
- Define routes on GET, POST, PUT, DELETE and HEAD verbs,
- Define middlewares on routes,
- Define required parameters,
- Inject data from query string, path parameters, entire body, cookies, session or header,
- Inject Request, Response, Next object from Express request,
- Templating (View),
- Testing.
You can get the latest release using npm:
$ npm install --save ts-express-decorators express@4 @types/expressImportant! TsExpressDecorators requires Node >= 4, Express >= 4, TypeScript >= 2.0 and the
experimentalDecorators,emitDecoratorMetadata,typesandlibcompilation options in yourtsconfig.jsonfile.
{
"compilerOptions": {
"target": "es5",
"lib": ["es6", "dom"],
"types": ["reflect-metadata"],
"module": "commonjs",
"moduleResolution": "node",
"experimentalDecorators":true,
"emitDecoratorMetadata": true,
"sourceMap": true,
"declaration": false
},
"exclude": [
"node_modules"
]
}The @types/express modules dependency has move to devDependencies. So you can have a compilation error with TypeScript.
To resolve it, just run npm install --save @types/express.
If we used the InjectorService. Make you sure we have this in your code:
InjectorService.invoke(target)has changed toInjectorService.invoke<T>(target): T.InjectorService.get(target)has changed toInjectorService.get<T>(target): T.
TsExpressDecorators provide a ServerLoader class to configure your
express quickly. Just create a server.ts in your root project, declare
a new Server class that extends ServerLoader.
import * as Express from "express";
import {ServerLoader, ServerSettings} from "ts-express-decorators";
import Path = require("path");
@ServerSettings({
rootDir: Path.resolve(__dirname)
})
export class Server extends ServerLoader {
/**
* This method let you configure the middleware required by your application to works.
* @returns {Server}
*/
public $onMountingMiddlewares(): void|Promise<any> {
const morgan = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
compress = require('compression'),
methodOverride = require('method-override');
this
.use(morgan('dev'))
.use(ServerLoader.AcceptMime("application/json"))
.use(cookieParser())
.use(compress({}))
.use(methodOverride())
.use(bodyParser.json())
.use(bodyParser.urlencoded({
extended: true
}));
return null;
}
public $onReady(){
console.log('Server started...');
}
public $onServerInitError(err){
console.error(err);
}
static Initialize = (): Promise<any> => new Server().start();
}
Server.Initialize();By default ServerLoader load controllers in
${rootDir}/controllersand mount it to/restendpoint.
To customize the server settings see Configure server with decorator
Create a new calendarCtrl.ts in your controllers directory configured
previously with ServerLoader.mount(). All controllers declared with @Controller
decorators is considered as an Express router. An Express router require a path
(here, the path is /calendars) to expose an url on your server.
More precisely, it is a part of path, and entire exposed url depend on
the Server configuration (see ServerLoader.setEndpoint()) and the controllers
dependencies. In this case, we haven't a dependencies and the root endpoint is set to /rest.
So the controller's url will be http://host/rest/calendars.
import {Controller, Get} from "ts-express-decorators";
import * as Express from "express";
interface ICalendar{
id: string;
name: string;
}
@Controller("/calendars")
export class CalendarCtrl {
/**
* Example of classic call. Use `@Get` for routing a request to your method.
* In this case, this route "/calendars/:id" are mounted on the "rest/" path.
*
* By default, the response is sent with status 200 and is serialized in JSON.
*
* @param request
* @param response
* @returns {{id: any, name: string}}
*/
@Get("/:id")
public get(request: Express.Request, response: Express.Response): ICalendar {
return <ICalendar> {id: request.params.id, name: "test"};
}
@Get("")
@ResponseView("calendars/index") // Render "calendars/index" file using Express.Response.render internal
public get(request: Express.Request, response: Express.Response): Array<ICalendar> {
return [<ICalendar> {id: '1', name: "test"}];
}
@Authenticated()
@BodyParams() @Required("calendar.name") // Throw Bad Request (400) if the request.body.calendar.name isn't provided
@Post("/")
public post(
@BodyParams("calendar") calendar: ICalendar
): Promise<ICalendar> {
return new Promise((resolve: Function, reject: Function) => {
calendar.id = 1;
resolve(calendar);
});
}
@Authenticated()
@Delete("/")
public post(
@BodyParams("calendar.id") @Required() id: string
): Promise<ICalendar> {
return new Promise((resolve: Function, reject: Function) => {
calendar.id = id;
resolve(calendar);
});
}
}To test your method, just run your server.ts and send a http request on /rest/calendars/1.
Note : Decorators
@Getsupport dynamic pathParams (see/:id) andRegExplike Express API.
Welcome to the TsExpressDecorators project wiki!
- Installation
- Quick start
- Examples
- Controllers
- Services
- Middlewares
- ServerLoader
- Templating
- Upload files with Multer
- Throw HTTP exceptions
- Testing
- API references
- Add
@Inject()decorator #42, - Add
@Middleware()decorator #40, - Add
@ContentType()decorator #34, - Add
@Redirect()decorator #33, - Add
@Location()decorator #32, - Add
@UseBefore()decorator #19, - Add
@UseAfter()decorator #19, - Add alias
@HeaderParams()decorator #30, - Extends
@Header()decorator. Now @Header can be used on method #30, - Add
@MultipartFile()decorator #31, - Refactoring
InjectorService. You can add a no class based service (factory) #36, InjectorServicecan be use inServerLoader.$onMountingMiddleware()#39.- Add
@AcceptMime()decorator, - Add
@Status()decorator, - Add
@Deprecated()decorator, - Add
@ServerSettings()decorator to configure ServerLoader, - Add some services : ControllerService, ExpressApplication, MiddlewareService and ServerSettingsService
- Add
boostrap()function to test your server application with Mocha and SuperTest. - Improve testing module.
- Add Symbol serialization/deserialization support.
- Fix Array deserialization when input data isn't an array.
- Support of Typescript 2.2.x.
ServerLoader.onError()is deprecated. Use your own middleware instead of.ServerLoader.getExpressAppis deprecated. Use ServerLoader.expressApp instead of.ServerLoader.AcceptMime()is deprecated. Use your own middleware instead of.
You can encounter typescript compilation issues:
InjectorService.invoke(target)has changed toInjectorService.invoke<T>(target): T.InjectorService.get(target)has changed toInjectorService.get<T>(target): T.@types/expressisn't installed as dependencies now. Just makenpm install --save @types/express.
- Add
@Session()decorator #11, - Add
@ResponseView()decorator #9, #16, #22, - Add model deserialization and add decorator
@JsonProperty#3, - Add two proxy methods :
ServerLoader.set()andServerLoader.engine()#18, - Add
yarnsupport #21, - Pass bind interface to http server #27,
- Prevent sending data if header is already sent #28,
- Add ServerLoader.mount(). This method can mount controller to one or more endpoints #13.
- Remove Bluebird and use native Promise. Breaking change are possible if you use v1.1.0 of ts-express-decorators. Just, replace Bluebird reference in your
Server.tsor install Bluebird and @types/bluebird dependencies. - Improve
package.jsonconfiguration. Now, IDE like webstorm can auto discovered the exposed decorators. - Implement Lifecycle hooks.
- Change testing module. See documentation (https://github.com/Romakita/ts-express-decorators/wiki/Testing).
The MIT License (MIT)
Copyright (c) 2016 Romain Lenzotti
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.