monvhh / hapijsdemo Goto Github PK
View Code? Open in Web Editor NEWhapiJS实战
hapiJS实战
如果打算用官方demo推荐的方式就不必看了。
由于公司有自己记日志的方式,所以必须自己实现。
首先,hapi.js提供一个EventEmitter的log事件。
server.log
或
request.log
eg.
const handler = function (request, h) {
request.log(['test', 'error'], 'Test event');
return null;
};
server.events.on({ name: 'request', channels: 'app' }, (request, event, tags) => {
if (tags.error) {
console.log(event);
}
});
server.events.on({ name: 'request', channels: 'internal' }, (request, event, tags) => {
console.log(event);
});
channel:app/internal
internel应该是服务内部的日志;
request.log
记录的日志目前使用下来都是app。
在Request lifecycle中绑定事件。
比如,我主要是记录http请求到达和http返回响应
server.ext({
type: 'onPreHandler',
method: function (request, h) {
request.log(['begin', 'api']);
return h.continue;
},
options: {
sandbox: 'plugin'
}
})
server.ext({
type: 'onPreResponse',
method: function (request, h) {
let data = request.response.source;
request.log(['end', 'api'], data);
},
options: {
sandbox: 'plugin'
}
})
server.events.on({
name: 'request',
channels: 'app'
}, (request, event, tags) => {
if (tags.error) {
callback();//调公司通用的记日志方法
return;
}
if (tags.begin) {
callback();//调公司通用的记日志方法
} else if (tags.end) {
callback();//调公司通用的记日志方法
}
});
提供给客户端的响应,有一个固定的结构,懒得每次个接口,调reponse()的时候还要先调一下包装方法,重复劳动。需要抽离出来
server.ext({
type: 'onPreResponse',
method: function (request, h) {
let data = request.response.source;
return h.response({
errCode: 0,
errMsg: '',
data: data
}).code(200);
},
options: {
sandbox: 'plugin'
}
})
我写在plugin里了,因为会影响hapi-swagger.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.