-
Notifications
You must be signed in to change notification settings - Fork 14
/
utils.js
85 lines (71 loc) · 1.83 KB
/
utils.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
const rp = require('request-promise');
const crypto = require('crypto');
const moment = require('moment');
const { isDate } = require('lodash');
const createRequest = (verb, url, headers, opts = { data: null, formData: null }) => {
const requestObj = {
headers,
url,
json: true
};
if (opts.data) {
requestObj.body = opts.data;
}
if (opts.formData) {
requestObj.formData = opts.formData;
}
return rp[verb.toLowerCase()](requestObj);
};
const createSignature = (secret = '', verb, path, expires, data = '') => {
const stringData = typeof data === 'string' ? data : JSON.stringify(data);
const signature = crypto
.createHmac('sha256', secret)
.update(verb + path + expires + stringData)
.digest('hex');
return signature;
};
const generateHeaders = (headers, secret, verb, path, expiresAfter, data) => {
const expires = moment().unix() + expiresAfter;
const signature = createSignature(secret, verb, path, expires, data);
const header = {
...headers,
'api-signature': signature,
'api-expires': expires
};
return header;
};
const checkKit = (kit) => {
if (!kit) {
throw new Error(
'Missing Kit ID. ID of the exchange Kit should be initialized in HollaEx constructor'
);
}
return true;
};
const parameterError = (parameter, msg) => {
return new Error(`Parameter ${parameter} error: ${msg}`);
};
const isDatetime = (date, formats = [ moment.ISO_8601 ]) => {
return moment(date, formats, true).isValid();
};
const sanitizeDate = (date) => {
let result = date;
if (isDate(result)) {
result = moment(result).toISOString();
}
return result;
};
const isUrl = (url) => {
const pattern = /^(^|\s)((http(s)?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)$/;
return pattern.test(url);
};
module.exports = {
createRequest,
createSignature,
generateHeaders,
checkKit,
parameterError,
isDatetime,
sanitizeDate,
isUrl
};