-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
117 lines (99 loc) · 2.28 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/**
* Module dependencies.
*/
var crypto = require('crypto');
var url = require('url');
var keys = Object.keys;
/**
* Mongoose plugin exposure
*
* @param {MongooseSchema} schema
* @param {Object} options
* @api public
*/
module.exports = function plugin (schema, options) {
options = options || {
property: 'email'
};
schema.methods.gravatar = function (settings) {
settings = settings || {};
merge(settings, options);
return gravatar.call(this, settings);
};
};
/**
* Creates a gravatar url
* from `settings` provided
*
* @param {Object|undefined} settings
* @return {String} gravatar's API image `url`
* @api private
*/
function gravatar (settings) {
var email = settings.email || this[(settings.property || 'email')] || "[email protected]";
var host = (settings.secure ? "secure" : "www") + ".gravatar.com";
var protocol = settings.secure ? "https" : "http";
var pathname = "/avatar/" + md5(email);
var params = clear({
s: settings.size,
d: settings.default,
f: settings.forcedefault,
r: settings.rating
});
return url.format({
protocol: protocol,
host: host,
pathname: pathname,
query: params
});
}
/**
* Creates an MD5 enctryption hash
* with provided `word` parameter
*
* @param {String} word
* @return {String} hashed `word`
* @api private
*/
function md5 (word) {
return crypto.createHash('md5').update(word).digest("hex");
}
/**
* Clears undefined or invalid vars from
* a queryString params object
*
* @param {Object} obj
* @return {Object} reduced object
* @api private
*/
function clear (obj) {
var output = {};
keys(obj).forEach(function (key) {
if (obj[key] != null) {
output[key] = obj[key];
}
});
return output;
}
/**
* Merge missing keys in `settings` object
* from the ones coming from `options` object
* as default values for `gravatar` function.
*
* @param {Object} settings
* @param {Object} options
* @return {Objsect} completed `settings` object
* @api private
*/
function merge (settings, options) {
var defaults = keys(options);
var length = defaults.length;
var i = 0;
for (; i < length; i++) {
var key = defaults[i];
if (settings[key] == null && options[key] != null) {
settings[key] = options[key];
}
}
return settings;
}