-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgravatar.js
43 lines (32 loc) · 1.08 KB
/
gravatar.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
/**
* This is a file that is used to generate gravatar image url.
* (c) 2018 | xn-02f Lab
* License: MIT
*/
import md5 from '@xn-02f/md5';
const gravatarUrl = 'https://www.gravatar.com/avatar/';
export default (email, options) => {
let queryString = (options) ? handleOptions(options) : '';
return gravatarUrl + md5Hash(email) + queryString;
}
const md5Hash = email => {
const MD5_REG = /^[0-9a-f]{32}$/;
const UNSPECIFIED = '00000000000000000000000000000000'
// http://en.gravatar.com/site/implement/hash/
email = (typeof email === 'string') ? email.trim().toLowerCase() : UNSPECIFIED;
return email.match(MD5_REG) ? email : md5(email);
}
const handleOptions = obj => {
if (typeof obj === 'object') {
let params = [];
if (Object.keys(obj).length == 0) {
return '';
}
for (const key in obj) {
params.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
return '?' + params.join('&');
} else {
throw Error('\'options\' parameter must be object...');
}
}