javascript - NodeJS 模块导出

标签 javascript node.js httpclient

我有一个简单的 http 客户端模块 (api.js),它返回一个 promise ,如下所示:

 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 的所有其他函数中设置一次?

最佳答案

另一种风格:

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 = '';

关于javascript - NodeJS 模块导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33620638/

相关文章:

javascript - gmaps.js 使用 native Google Maps API v3 函数

javascript - 如何在 Electron.Atom\WebPack 应用程序中使用 FS 模块?

c# - 使用 HttpClient.GetAsync() 时如何确定 404 响应状态

java - HttpConnection 不要关闭

javascript - Apollo 服务器: pass arguments to nested resolvers

java - 从效率角度来看,使用 HttpClient 发布文件的最佳方式

javascript - 通过在 for 循环中解析字符串来委托(delegate)事件

javascript - 获取 HTML 页面上 javascript 函数中的嵌入值

javascript - 未捕获的类型错误 : Object function ()

javascript - 如何将链接 promise 与数组的循环一起使用?