@555platform/express-decorators
v0.2.12
Published
555 Platform common Express.js decorators for Typescript
Downloads
60
Readme
express-decorators
Lightweight Typescript decorator library for Express.js to provide shortcuts for common patterns.
Inspired by the following projects:
- https://tsed.io/
- https://github.com/StephenGrider/typescriptcasts/tree/master/server
Installation
You can get the latest release using npm:
$ npm install --save @555platform/express-decorators
Quick Start
You can create web server by extending AppServer
class.
import {
json,
Settings,
AppServer
} from '@555platform/express-decorators';
@Settings({ port: 5001 })
class TestServer extends AppServer {
beforeGlobalRouteInit(): void {
this.use(json());
}
onServerListens(port: number): void {
console.log(`Test server running on port: ${port}`);
}
}
AppServer has couple life cycle methods that can be overwritten to perform custom initializations.
beforeServerInit
This method is automatically called before web server is initialized. It can be used to execute any code that must run before web server starts.
beforeGlobalRouteInit
This method is executed after web server is initialized but before routes are created. It is meant to be customized to set up global route midleware or perform other activities before routes are defined.
onServerListens
This method is called after web server starts.
Create Controller
@Controller('/')
class SimpleRoutes {
@Get('/api')
getApi(req: Request, res: Response, next: NextFunction): void {
res.send('Ok');
}
@Delete('/api')
deleteApi(req: Request, res: Response, next: NextFunction): void {
res.send('Ok');
}
@Post('/api')
postApi(req: Request, res: Response, next: NextFunction): void {
if (!req.body) {
res.status(422).send('Missing body');
}
if (!req.body.testValue) {
res.status(400).send('Missing testValue');
}
res.send('Ok');
}
@Put('/api')
putApi(req: Request, res: Response, next: NextFunction): void {
if (!req.body) {
res.status(422).send('Missing body');
}
if (!req.body.testValue) {
res.status(400).send('Missing testValue');
}
res.send('Ok');
}
@Patch('/api')
patchApi(req: Request, res: Response, next: NextFunction): void {
if (!req.body) {
res.status(422).send('Missing body');
return;
}
if (!req.body.testValue) {
res.status(400).send('Missing testValue');
return;
}
res.send('Ok');
}
@Get('/params/:id')
idApi(req: Request, res: Response, next: NextFunction): void {
if (!req.params.id) {
res.status(422).send('missing param');
}
res.status(200).send({ id: req.params.id });
}
@Post('/multi/id/:id/message/:message')
multiApi(req: Request, res: Response, next: NextFunction): void {
if (!req.params.id || !req.params.message) {
res.status(422).send('missing param');
}
res.status(200).send({ id: req.params.id, message: req.params.message });
}
}
Create WebSocket Server Controller
You can create one or more WebSocket servers as long as they are pointing to different path.
WssBeginConnect and WssEndConnect are functions that will be called by express-decorators at the begining and end of execution of wss.on connection function.
Function deecorated with @Server will receive WebSocket.Server object when the new server is instantiated.
@WebSocketServer('/'), { enableKeepAlive: true }
class SocketGateway {
@Authenticate
authenticationHandler(req: Request, cb: AuthenticationCallback) {
console.log('Authing...');
const queryData = url.parse(req.url, true).query;
if (queryData.access_token === 'somevalue') {
cb(undefined, { id: 'someid' });
return;
}
cb(new Error('Unauthorized'));
}
@WssBeginConnect
beginConnectionHandler() {
console.log('Begin connection');
}
@WssEndConnect
endConnectionHandler() {
console.log('End connection');
}
@WsOnPong
pongHandler(ws: ExtWebSocket) {
return function() {
console.log('Received PONG');
ws.isAlive = true;
};
}
@WsOnMessage
messageHandler(ws: ExtWebSocket) {
return function(msg: string) {
ws.send(msg);
};
}
@WsOnOpen
openHandler(ws: ExtWebSocket) {
return function() {
console.log('connected');
ws.send(Date.now());
};
}
@WsOnClose
closeHandler(ws: ExtWebSocket) {
return function() {};
}
@WsOnError
errorHandler() {
return function(error: Error) {
console.log(`Error: ${error}`);
};
}
@Server
serverHandler(wss: WebSocket.Server) {
console.log('serverHandler');
}
}
Connect to Mongo via Mongoose
You can simply pass Mongo connection information to Settings for AppServer via mongoose property:
@Settings({
port: 5001,
mongoose: {
databaseURI: 'localhost',
databaseName: 'mydb',
dbUser: '',
dbPassword: '',
databaseReplSet: ''
}
})
class TestServer extends AppServer {
beforeGlobalRouteInit(): void {
this.use(json());
}
onServerListens(port: number): void {
console.log(`Test server running on port: ${port}`);
}
onMongooseConnected(): void {
connectSuccess();
}
onMongooseError(error: Error): void {
connectFailed();
}
}