加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
restful.js 2.23 KB
一键复制 编辑 原始数据 按行查看 历史
yulifu 提交于 2018-05-10 09:48 . change syscode
/**
* @author yu
* @license http://www.apache.org/licenses/LICENSE-2.0
*/
'use strict';
var http = require('http');
var Hook = require('./core/Hook');
var Rest = require('./web/Rest');
var InvalidConfigException = require('./core/InvalidConfigException');
class Restful {
/**
* constructor
*
* @param {Object} config 配置信息
*/
constructor(config) {
if(undefined === config) {
throw new InvalidConfigException('The rest config is required');
}
this.config = config;
this.server = null;
this.rest = new Rest(config);
}
// web
requestListener(req, res) {
try {
this.rest.requestListener(req, res);
} catch(e) {
this.rest.handlerException(res, e);
}
}
// handler
handler(req, res) {
Hook.getInstance().trigger(req, res, () => {
this.requestListener(req, res);
});
}
/**
* get
*/
get(pattern, handler) {
this.rest.addRoute('GET', pattern, handler);
}
/**
* post
*/
post(pattern, handler) {
this.rest.addRoute('POST', pattern, handler);
}
/**
* put
*/
put(pattern, handler) {
this.rest.addRoute('PUT', pattern, handler);
}
/**
* delete
*/
delete(pattern, handler) {
this.rest.addRoute('DELETE', pattern, handler);
}
/**
* patch
*/
patch(pattern, handler) {
this.rest.addRoute('PATCH', pattern, handler);
}
/**
* head
*/
head(pattern, handler) {
this.rest.addRoute('HEAD', pattern, handler);
}
/**
* options
*/
options(pattern, handler) {
this.rest.addRoute('OPTIONS', pattern, handler);
}
/**
* 获取 http server
*
* @return http server
*/
getServer() {
return http.createServer(this.handler.bind(this));
}
/**
* listen
*
* @param {Number} port
* @param {Function} callback
*/
listen(port, callback) {
this.server = this.getServer();
this.server.listen(port, callback);
}
}
module.exports = Restful;
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化