我有一个简单的http客户端模块(api.js),它返回一个承诺,如下所示:
exports.endpoint = '';
exports.GET = function(args){
args.method = 'GET';
args.uri = this.endpoint + args.uri;
return asyncApiCall(args);
};
exports.POST = function(args){
args.method = 'POST';
args.uri = this.endpoint + args.uri;
return asyncApiCall(args);
};
exports.PUT = function(args){
args.method = 'PUT';
args.uri = this.endpoint + args.uri;
return asyncApiCall(args);
};
exports.DELETE= function(args){
args.method = 'DELETE';
args.uri = this.endpoint + args.uri;
return asyncApiCall(args);
};
var asyncApiCall = function(args){
var rp = require('request-promise');
var options = {
method: args.method,
uri: args.uri,
body : args.body,
json: args.json
}
return rp(options);
};
我使用这样的模块:
var api = require('./api.js');
var args = {
uri : '/posts'
}
api.endpoint = 'http://localhost:3000';
api.GET(args)
.then(function(res){
console.log(res);
}, function(err){
console.log(err);
});
现在,我想尽可能地改进模块。有没有办法不重复export.functionName?我在NodeJS中找到了module.exports,但在这种情况下我不确定如何使用它。如何在asyncApiCall函数中设置一次端点变量,而不是所有返回asyncApiCall的其他函数?
答案 0 :(得分:2)
很多人选择将他们的导出方法放在一个新对象上并通过module.exports导出,例如
var myExports = {
get: function () {},
post: function () {}
}
module.exports = myExports;
As for module.exports vs exports
看起来设置一个完整的构造函数可能是合适的,你的方法与它绑在一起,如下所示:
var requests = function (endpoint) {
this.endpoint = endpoint;
}
requests.prototype.GET = function (args) {
args.method = 'GET';
args.uri = this.endpoint + args.uri;
return asyncApiCall(args);
}
// And so on
module.exports = requests;
然后这样称呼它:
var api = require('./api.js');
var endpoint = new api("http://localhost:3000");
endpoint.GET()
答案 1 :(得分:2)
只是另一种风格:
var rp = require('request-promise'); // Put it here so you don't have to require 1 module so many times.
var asyncApiCall = function(args) {
var options = {
method: args.method,
uri: args.uri,
body : args.body,
json: args.json
};
return rp(options);
};
// Let's hack it.
var endpoint = '';
var apis = {};
['GET', 'POST', 'PUT', 'DELETE'].forEach(function(method) {
apis[method] = function(args) {
args.method = method;
args.uri = endpoint + args.uri;
return asyncApiCall(args);
}
});
module.exports = apis;
module.exports.endpoint = '';
答案 2 :(得分:1)
将其包装在一个类中并导出一个新的实例
function Module() {
}
Module.prototype.GET = function () {}
module.export = new Module()
// or
module.export = Module
// to call the constructor for your endpoint variable.