forked from iliakan/cls-mongoose
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
executable file
·87 lines (79 loc) · 2.67 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
"use strict";
var shimmer = require("shimmer");
module.exports = function patchMPromise(ns, _mongoose) {
//If there are multiple mongoose versions in the dependency tree, then the `require('mongodb')` could contain differnent objects
// This allows users to explicitly pass a `mongoose` object to bind.
var mongoose = _mongoose || require("mongoose");
if (typeof ns.bind !== "function") {
throw new TypeError("must include namespace to patch Mongoose against");
}
if (mongoose.Mongoose.prototype.Promise.prototype.on) {
shimmer.wrap(mongoose.Mongoose.prototype.Promise.prototype, "on", function(
original
) {
return function(event, callback) {
callback = ns.bind(callback);
return original.call(this, event, callback);
};
});
}
shimmer.wrap(mongoose.Mongoose.prototype.Query.prototype, "exec", function(
original
) {
return function(op, callback) {
if (typeof op == "function") op = ns.bind(op);
if (typeof callback == "function") callback = ns.bind(callback);
return original.call(this, op, callback);
};
});
shimmer.wrap(
mongoose.Mongoose.prototype.Query.base,
"_wrapCallback",
function(original) {
return function(method, callback, queryInfo) {
if (typeof callback == "function") callback = ns.bind(callback);
return original.call(this, method, callback, queryInfo);
};
}
);
shimmer.wrap(mongoose.Mongoose.prototype.Model, "$wrapCallback", function(
original
) {
return function(callback) {
if (typeof callback == "function") callback = ns.bind(callback);
return original.call(this, callback);
};
});
shimmer.wrap(
mongoose.Mongoose.prototype.Aggregate.prototype,
"exec",
function(original) {
return function(callback) {
if (typeof callback == "function") callback = ns.bind(callback);
return original.call(this, callback);
};
}
);
for (const func in mongoose.Mongoose.prototype.Collection.prototype) {
if (
mongoose.Mongoose.prototype.Collection.prototype.hasOwnProperty(func) &&
typeof mongoose.Mongoose.prototype.Collection.prototype[func] ===
"function" &&
func[0] !== "$"
) {
shimmer.wrap(
mongoose.Mongoose.prototype.Collection.prototype,
func,
function(original) {
return function() {
const args = Array.from(arguments);
let callback = args[args.length - 1];
if (typeof callback == "function") callback = ns.bind(callback);
const newArgs = [...args.slice(0, -1), callback];
return original.apply(this, newArgs);
};
}
);
}
}
};