使用Node.js抽象请求



传统上,我对所有的JS代码都使用jQuery,但我的任务是用node.JS启动一个简单的API。今天是我使用node的第一天,但我对JS和闭包有足够的了解,可以做得很好。API的任务之一是通过第三方服务进行身份验证,作为一个python爱好者,我想抽象所有的出站请求调用,如下所示:

编辑

var http = require('http');
var init = function(nconf) {
    var methods = {
    /*  
        Helper method to create the request header
    */
    headers: function(params) {
        var content = JSON.stringify(params);
        return {
            'Content-Type': 'application/json',
            'Content-Length': content.length
        }
    },
    /*
        Helper method to create the options object
        which is used in making any type of 
        outbound http request
    */
    options: function(host, path, method, params) {
         return {
            host: host,
            port: 80,
            path: path,
            method: method,
            headers: methods.headers(params)
        }
    },
    /*
        Helper method to abstract the making of
        outbound http requests
    */
    call: function(options, params, success, err) {
        var req = http.request(options, success);
        req.on('error', err);
        req.write(params);
        req.end();
    },
    /*
        Helper method to parse the response
        and return a json object
    */
    parse: function(res, result) {
        var responseString = '';
        res.on('data', function(data) {
            responseString += data;
        });
        res.on('end', function() {
            result = JSON.parse(responseString);
        });
    },
    /*
        API method to return the latest
        release and tag names
    */
    latest: function(req, res, next){
        // // var url = nconf.get('prod:authenticate');
        //authenticate the test user
        msg = methods.authenticate(nconf.get('test:user'), nconf.get("test:password"));
        res.send(msg);
        next();
    },
    /*
        Method used by this API to authenticate users.
        It is used to de-couple this API from the Database
        Schema by calling out to the TTCPAS App and requesting it
        to handle the authentication
    */
    authenticate: function(username, password){
        // create post parameters with API key
        var params = {"username": username, "password": password, "api_key": nconf.get('api_key')};
        //construct options object with params and header
        var options = methods.options(nconf.get('ttcpas:host'), nconf.get('ttcpas:auth_url'), 'POST', params);
        var result;
        var success = function(res) {
            res.setEncoding('utf-8');
            methods.parse(res, result);
        };
        methods.call(options, params, success, function(err){});
        while (typeof(result.statusCode) == 'undefined') {
            //wait 1 second;
            setTimeout(function(){
                console.log("waiting on request at " + nconf.get('ttcpas:host') + nconf.get('ttcpas:auth_url'));
            }, 1000);
        }
        //then down here
        if (result.statusCode == 200) {return result};//success
        if (result.statusCode == 403) {return "forbidden"};//forbidden

    }
}
return methods;
};
module.exports.init = init;

@jfriend00正如我所说,我不知道node.js应该如何设计。我想尽可能多地抽象代码,使代码干净且可重复使用

现在当我这样做的时候http://localhost:9000/latest/

我得到:

{"code":"InternalError","message":"first argument must be a string or Buffer"}

嗯,这部分根本不起作用:

while (typeof(result.statusCode) == 'undefined') {
    //wait 1 second;
    setTimeout(function(){
        console.log("waiting on request at " + nconf.get('ttcpas:host') + nconf.get('ttcpas:auth_url'));
    }, 1000);
}

如果result.statusCode曾经是undefined,那么这将永远在事件队列中堆积setTimeout()调用,直到最终有东西填满或内存耗尽。

因为node.js主要是单线程的,所以不能循环等待更改。因为您永远不会完成while循环,所以没有其他node.js代码可以运行,所以result.statusCode永远不会更改。因此,这里有一个无限循环。

所有nodejs代码都需要是事件驱动的,而不是旋转/等待循环。仅供参考,这类似于基于浏览器的Javascript。

最新更新