promise-express-router
v1.3.0
Published
Express router wrapper. Which can handle promise and correctly make a response using json format.
Downloads
2
Readme
promise-express-router
Promisify express router. Let you return a promise from router handler and it will convert to a json formatted response. The response format is obey to http-api-design,
Document
How to use
Install
npm install promise-express-router
Normal response
- Code
const app = require('express')();
const PromiseRouter = require('promise-express-router');
const promiseRouter = new PromiseRouter();
promiseRouter.getAsync('/test', (req, locals) => {
return Promise.resolve({name: 'lilei'});
});
app.use(promiseRouter.toExpressRouter());
- Response
{
"result": {
"name": "lilei"
},
"ok": true
}
Error response
- Code
const app = require('express')();
const PromiseRouter = require('promise-express-router');
const promiseRouter = new PromiseRouter();
promiseRouter.getAsync('/test', (req, locals) => {
return Promise.reject(new Error('new error'));
});
app.use(promiseRouter.toExpressRouter());
- Response
{
"message": "Error .....",
"ok": false
}
Response fields
ok
If server error happens, it will be false. Or it's true.result
Result data.message
A human readable error message.code
Error code.
Customize response format
You can also customize response format.
promiseRouter = new PromiseRouter({
standard: (obj)=> {
return {
data: obj.result,
status: obj.ok
}
},
error: (obj) => {
return {
error_code: obj.code,
stacktrace: obj.msg,
normal: obj.ok
}
}
});
Example
Compatibility
- Node 4.x
- Node 5.x
License
MIT