Blame view

code/libs/Interfacer.js 14.4 KB
weiqingting authored
1
var util = require('util');
weiqingting authored
2
var Emitter = require('events');
weiqingting authored
3
var Request = require('request');
weiqingting authored
4
var async = require('async');
weiqingting authored
5 6 7
/*接口*/
var _ = require('lodash');
weiqingting authored
8
var Utils = require('./Utils');
weiqingting authored
9 10

weiqingting authored
11 12 13 14 15 16
var Interfacer = function (config, app) {
    this.config = config;
    this.CONSTS = app.get("Register");
    this.config.domain = this.config.domain || app.get("Register").domain;
    this.apis = {};
    Emitter.call(this);
weiqingting authored
17 18
};
weiqingting authored
19
util.inherits(Interfacer, Emitter);
weiqingting authored
20
weiqingting authored
21 22 23 24 25 26 27 28 29 30 31 32 33
Interfacer.prototype.register = function (mos) {
    var me = this, name = mos.namespace;
    if (!name) {
        console.info(" Interfacer name can not empty");
    }
    for (var key in mos.apis) {
        var name_key = name + "_" + key;
        if (me.isExisted(name_key)) {
            console.info("can not add repeat Interfacer key,please checkout");
        }
        /*需要进行验证判断*/
        me.apis[name_key] = mos.apis[key];
    }
weiqingting authored
34 35
};
weiqingting authored
36 37
Interfacer.prototype.isExisted = function (key) {
    return !!this.apis[key];
weiqingting authored
38
};
weiqingting authored
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
Interfacer.prototype.getInterfacerByNameSpace = function (namespace) {
    var me = this;
    if (!namespace) return {};
    var apis = {}, len = namespace.length;
    for (var key in me.apis) {
        if (key.slice(0, len + 1) === namespace + "_") {
            var name = key.slice(len + 1);
            if (typeof me.apis[key] !== "function") {
                apis[name] = me.apis[key];
            }
        }
    }
    return apis;
}

function __getArgs(str) {
    var arr = str.toString().match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1].split(',');
    return (arr.length == 1 && arr[0] == "")?[]:arr;
}
weiqingting authored
58
weiqingting authored
59 60
function __requestApi(config, apiOpt, req, callback) {
    var me = this;
weiqingting authored
61
    if (typeof apiOpt == "function") {
weiqingting authored
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
        
        var args = __getArgs(apiOpt), o = {};
        if (args.length > 2) {
            args.slice(2).map(function (namespace) {
                namespace = _.trim(namespace);
                o[namespace] = {};
                var apis = me.getInterfacerByNameSpace(namespace);
                for (var action in apis) {
                    o[namespace][action] = (function (api, config, consts) {
                        var intermo = new Interfacer.create(api);
                        return function () {
                            var args = [].slice.call(arguments, 0), params = {};
                            intermo.apiOpt = api;
                            intermo.config = {
                                config: config,
                                consts: consts
                            };
                            
                            if (args.length === 1 && _.isPlainObject(args[0])) {
                                intermo.req.param(args[0]);
                            } else { 
                                api.params = api.params || {};
                                var os = Object.keys(api.params);
                                args.forEach(function (value, i) {
                                    params[os[i]] = value;
                                });
                                intermo.req.param(params);
                            }
                            if (!this.queue) {
                                this.queue = [];
                            }
                            this.queue.push(intermo);
                            this.__proto__ = new queue();
                            return this;
                        };
                    })(apis[action], config, me.CONSTS);
                }
            });
        }
        var fns = [];
        for (var i in o) {
            fns.push(o[i]);
        }
        return apiOpt.apply(0, [req, function (err, result) {
                req._yoheaders = req._yoheaders;
                return callback(null, result);
            }].concat(fns));
    }
    
    var options = __requestOption(req, apiOpt, config, me.CONSTS);
weiqingting authored
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    __sendRequest(options, function (result) {
        return callback(null, result);
    }, function (result) {
        return callback(result, null);
    }, {len:1}, 0, []);
    //Request(options, function (error, response, body) {
    //    var _err_ = new Error();
    //    if (error) {
    //        console.info("Error [request"+options.url+"]:" + options.title);
    //        console.error(error);
    //        return callback(error, null);
    //    }
    //    try {
    //        if (response && response.statusCode === 200) {
    //            var obj = JSON.parse(body)
    //            if (!(typeof obj == "object")) {
    //                _err_.message = "Error[json parse@" + options.title + "--"+options.url+"]:" + body;
    //                console.info(_err_.message);
    //                console.error(_err_);
    //                return callback(_err_, null);
    //            }
    //        } else {
    //            _err_.message = "Error[response state @" + options.title + "--"+options.url+"]:" + response;
    //            console.info(_err_.message);
    //            console.error(_err_);
    //            return callback(_err_, null);
    //        }
            
    //    } catch (err) {
    //        console.info("Error[response to json @" + options.title + "--"+options.url+"]");
    //        console.info(response);
    //        console.error(err);
    //        return callback(err, null);
    //    }
    //    return callback(null, JSON.parse(body));
    //});
weiqingting authored
148 149 150
};

function __requestOption(req, apiOpt, config, consts) {
weiqingting authored
151
    var method = (apiOpt.method || "POST").toLocaleUpperCase(), errs = [];
weiqingting authored
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    var data = {};
    if (apiOpt.params && (_.isArray(apiOpt.params) || _.isPlainObject(apiOpt.params))) {
        if (_.isArray(apiOpt.params)) {
            //兼容 yo之前的模式 后期废弃
            apiOpt.params.forEach(function (param) {
                var name = param.name;
                if (req.param(name)) {
                    if (param.type.toUpperCase() == "NUMBER") {
                        data[name] = Number(req.param(name));
                    } else {
                        data[name] = String(req.param(name));
                    }
                }
            });
        } else
            if (_.isPlainObject(apiOpt.params)) {
weiqingting authored
168
                var fns = [];
weiqingting authored
169 170 171 172 173 174 175 176 177 178 179
                for (var name in apiOpt.params) {
                    if (req.param("@" + name)) {
                        continue;
                    }
                    var param = apiOpt.params[name];
                    if (param.default) {
                        data[name] = param.type(param.default);
                    }
                    if (req.param(name)) {
                        data[name] = param.type(req.param(name));
                    }
weiqingting authored
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
                    if (param.coerce && typeof param.coerce == "function") { 
                        fns.push({ param: param,name:name});
                    }
                }
                fns.forEach(function (fn) {
                    var d = fn.param.coerce.call(data, req);
                    if (d) { 
                        data[fn.name] = param.type(d);
                    }
                });
                //验证
                for (var name in apiOpt.params) {
                    var param = apiOpt.params[name];
                    if (param.required && !data[name]) {
                        errs.push("params "+name + "is required!!!");
                    }
                    if (param.validator&&typeof param.validator=="function") {
                        var isSuc = param.validator.call(data, data[name]);

                        if (isSuc===false) { 
                            errs.push("params " +name + " validator error!!!");
                        }
                    }
weiqingting authored
203 204 205 206
                }
            }
    }
    var options = { method: method };
weiqingting authored
207
    options.errs = errs;
weiqingting authored
208 209 210 211 212
    options.title = apiOpt.title || '';
    options.outobj = apiOpt.outobj || '';
    if (options.method == "GET") {
        apiOpt.query = true;
    }
weiqingting authored
213
weiqingting authored
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    if (/^https{0,1}:\/\//g.test(apiOpt.url)) {
        options.url = apiOpt.url;
    } else {
        options.url = (apiOpt.domain || config.domain) + apiOpt.url;
    }
    if (/\{\{.*\}\}/.test(options.url)) {
        var _qs = {};
        if (apiOpt.query) {
            _qs = data;
        }
        var a = _.merge(consts, _qs);
        options.url=Utils.template(options.url, a);
    }

    if (apiOpt.form) {
        if (typeof apiOpt.form === "string") {
            options.form = Utils.template(apiOpt.form, data);
        } else if (_.isPlainObject(apiOpt.form)) {
            options.form = {};
            for (var i in apiOpt.form) {
                options.form[i] = Utils.template(apiOpt.form[i], data)
            }
        }
        options.headers = {
            'Content-Type' : 'application/x-www-form-urlencoded'
        }
weiqingting authored
240
    } else if (apiOpt.query) {
weiqingting authored
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
        //不做任何事
    } else {
        options.body = JSON.stringify(data);
        options.headers = {
            'Content-Type' : 'application/json'
        }
    }
    if (apiOpt.headers && _.isPlainObject(apiOpt.headers)) {
        options.headers = {};
        for (var name in apiOpt.headers) {
            var param = apiOpt.headers[name];
            if (req.param("@" + name)) {
                if (param.default) {
                    options.headers[name] = param.type(param.default);
                }
                if (req.param("@" + name)) {
                    options.headers[name] = param.type(req.param("@" + name));
                }
            }
        }
weiqingting authored
261
    }
weiqingting authored
262 263 264 265 266
    if (req._yoheaders) {
        options.headers = _.merge(options.headers, req._yoheaders);
    }
    console.log("*************************************");
    console.log("Http", options.url, data, options.headers);
weiqingting authored
267
    console.log("*************************************");
weiqingting authored
268 269
    return options;
}
weiqingting authored
270 271 272 273

/*
* {mos} 接口key 数组 比如[key1,key2] 后面可能要兼容字符串 比如 传key1
*/
weiqingting authored
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
Interfacer.prototype.require = function (mos, req, res, cb) {
    var me = this, funcs = [], names = [], errName = [];
    
    mos.forEach(function (name) {
        
        if (me.apis.hasOwnProperty(name)) {
            names.push(name);
            if (me.config.mock) {
                funcs.push(me.apis[name].output);
            } else {
                funcs.push(function (callback) {
                    __requestApi.call(me, me.config, me.apis[name], req, callback);
                });
            }
        } else {
weiqingting authored
289
            console.error(name+"不存在");
weiqingting authored
290 291 292 293
            errName.push(name);
        }
    });
    
weiqingting authored
294 295
    if (funcs.length != mos.length) {
        var err = new Error();
weiqingting authored
296
        err.message = "某个" + errName.join("->") + " 可能不存在!";
weiqingting authored
297
        cb(err, funcs, names);
weiqingting authored
298 299 300 301 302 303 304 305 306 307 308 309 310
        return;
    }
    if (me.config.mock) {
        cb(null, funcs, names);
        return;
    }
    async.parallel(funcs, function (err, results) {
        if (err) {
            console.info("Async Error");
            console.error(err);
            console.error(results);
            return cb(err, results, names);
        }
weiqingting authored
311
        return cb(null, results, names);
weiqingting authored
312
    });
weiqingting authored
313 314
};
weiqingting authored
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
Interfacer.create = function (apis) {
    return {
        req: {
            __params__: null,
            param: function (value) {
                if (typeof value == "object") {
                    this.__params__ = value;
                } else {
                    return this.__params__[value];
                }
            }
        },
        apiOpt: null,
        config: {},
        
        error: function () { 
            
        }
    }
}
function queue() { }
queue.prototype = {
    done: function (success, fail) {
        var that = this;
        if (typeof success !== 'function') return;
        var len = that.queue.length, watchlen = { len: len };
        var args = new Array(3);
        var wlen=Object.defineProperty({}, 'len', {
            value: len,
            writable: true,
            enumerable: false,
            configurable: true
        });
        for (var i = 0; i < len; i++) {
            (function (queue,args) {
                var options = __requestOption(queue.req, queue.apiOpt, queue.config.config, queue.config.consts);
                __sendRequest(options, success, fail, wlen, i,args);
            })(this.queue[i],args);
        }
        that.queue = null;
        //var options = __requestOption(this.req, this.apiOpt);
        //this.__sendRequest(options, success, fail);
        return this;
    },
    
}
weiqingting authored
361 362 363 364 365 366 367 368 369 370
function __sendRequest(options, success, fail, wlen, i, args) {
    var _err_ = new Error(), obj;
    if (options.errs instanceof Array&&options.errs.length) {
        _err_.message = options.errs.join(',');
        console.info("Error [options" + options.url + "]:" + options.title);
        console.error(_err_);
        wlen.len = 0;
        fail && fail(_err_);
        return;
    }
weiqingting authored
371
    Request(options, function (error, response, body) {
weiqingting authored
372 373 374
        if (!wlen.len) { 
            return;
        }
weiqingting authored
375
        if (error) {
weiqingting authored
376
            console.info("Error [request"+options.url+"]:" + options.title);
weiqingting authored
377
            console.error(error);
weiqingting authored
378
            wlen.len = 0;
weiqingting authored
379 380 381 382
            fail && fail(error);
            return;
        }
        try {
weiqingting authored
383
            if (response && (response.statusCode === 200||response.statusCode === 302)) {
weiqingting authored
384 385 386
                if (!options.outobj) {
                    obj = JSON.parse(body)
                    if (!(typeof obj == "object")) {
weiqingting authored
387
                        _err_.message = "Error[json parse@" + options.title + "--"+options.url+"]:" + body;
weiqingting authored
388
                        console.info(_err_.message);
weiqingting authored
389
                        console.error(_err_);
weiqingting authored
390
                        wlen.len = 0;
weiqingting authored
391 392 393 394 395 396 397
                        fail && fail(_err_);
                        return;
                    }
                } else {
                    obj = options.outobj.toLocaleUpperCase().indexOf("BODY")>-1?body:response;
                }
            } else {
weiqingting authored
398
                _err_.message = "Error[response state @" + options.title + "--"+options.url+"]:" + response.statusCode;
weiqingting authored
399
                console.info(_err_.message);
weiqingting authored
400
                console.error(_err_);
weiqingting authored
401
                wlen.len = 0;
weiqingting authored
402 403 404
                fail && fail(_err_);
                return;
            }
weiqingting authored
405
            
weiqingting authored
406
        } catch (err) {
weiqingting authored
407
            console.info("Error[response to json @" + options.title + "--"+options.url+"]");
weiqingting authored
408 409
            console.info(response);
            console.error(err);
weiqingting authored
410
            wlen.len = 0;
weiqingting authored
411 412 413 414 415 416 417 418 419 420 421 422 423
            fail && fail(err);
            return;
        }
        args[i]=obj;
        wlen.len--;
        if (!wlen.len) { 
            success && success.apply(0, args)
        }
        return;
    });
}

module.exports = Interfacer;