如何覆盖Request.js模块中Qs.js模块中的函数?

时间:2014-08-27 13:09:02

标签: javascript node.js rest express override

我需要覆盖位于我帮助的另一个模块中的stringifyArray Qs.js函数。怎么样?

https://github.com/hapijs/qs

https://github.com/mikeal/request/blob/master/request.js

示例:

var request = require('request');


request.qs.stringifyArray = function (arr, prefix) {
var ret = [];
if (!prefix) throw new TypeError('stringify expects an object');
for (var i = 0; i < arr.length; i++) {
    ret.push(this.stringify(arr[i], prefix));
}
return ret.join('&');
};`

1 个答案:

答案 0 :(得分:0)

我的解决方案是覆盖(request.Request.prototype.qs)

var qs = require('qs'),
request = require('request'),
url = require('url');

var stringify;
var toString = Object.prototype.toString;

var isArray = Array.isArray || function (arr) {
return toString.call(arr) === '[object Array]';
};

var objectKeys = Object.keys || function (obj) {
var ret = [];
for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        ret.push(key);
    }
}
return ret;
};

var stringifyString = function (str, prefix) {
if (!prefix) throw new TypeError('stringify expects an object');
return prefix + '=' + encodeURIComponent(str);
};

var stringifyArray = function (arr, prefix) {
var ret = [];
if (!prefix) throw new TypeError('stringify expects an object');
for (var i = 0; i < arr.length; i++) {
    ret.push(stringify(arr[i], prefix));
}
return ret.join('&');
};

function stringifyObject(obj, prefix) {
var ret = [];
var keys = objectKeys(obj);
var key;

for (var i = 0, len = keys.length; i < len; ++i) {

    key = keys[i];

    if ('' === key) {
        continue;
    }

    if (null === obj[key]) {
        ret.push(encodeURIComponent(key) + '=');

    } else {
        ret.push(stringify(obj[key], prefix ? prefix + '[' + encodeURIComponent(key) + ']' :     encodeURIComponent(key)));
    }
}

return ret.join('&');
}

stringify = function (obj, prefix) {
if (isArray(obj)) {
    return stringifyArray(obj, prefix);
} else if ('[object Object]' === toString.call(obj)) {
    return stringifyObject(obj, prefix);
} else if ('string' === typeof obj) {
    return stringifyString(obj, prefix);
} else {
    return prefix + '=' + encodeURIComponent(String(obj));
}
};

并覆盖prototype.qs:

request.Request.prototype.qs = function (q, clobber) {
var base;

if (!clobber && this.uri.query) {
    base = qs.parse(this.uri.query)
}
else {
    base = {}
}

for (var i in q) {
    base[i] = q[i]
}

if (stringify(base) === '') {
    return this
}

this.uri = url.parse(this.uri.href.split('?')[0] + '?' + stringify(base));
this.url = this.uri;
this.path = this.uri.path;

return this;
};