-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
61 lines (53 loc) · 1.25 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
/*
* A simple mongoose plugin for getting and setting ip addresses
*/
var ip, ipAddressPlugin;
ip = require("ip");
/*
@param {Schema} schema
@param {Object} options, must include "fields" which is an array of strings
@returns {Schema}
*/
ipAddressPlugin = function(schema, options) {
var addVirtual, f, fields, fn, i, len, makeHiddenKey;
fields = options.fields;
makeHiddenKey = function(f) {
return "_" + f + "_buf";
};
addVirtual = function(schema, f) {
var key;
key = makeHiddenKey(f);
return schema.virtual(f).get(function() {
try {
return ip.toString(this[key]);
} catch (err) {
return null;
}
}).set(function(ipString) {
try {
return this.set(key, ip.toBuffer(ipString));
} catch (err) {
return this.set(key, null);
}
});
};
addIpAddressField = function(field) {
var key, obj;
obj = {};
key = makeHiddenKey(field);
obj[key] = {
type: Buffer,
required: false,
select: false,
index: true
};
schema.add(obj);
return addVirtual(schema, field);
};
for (i = 0, len = fields.length; i < len; i++) {
field = fields[i];
addIpAddressField(field);
}
return schema;
};
module.exports = ipAddressPlugin;