-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (59 loc) · 2.3 KB
/
index.js
File metadata and controls
69 lines (59 loc) · 2.3 KB
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
const crypto = require('crypto');
const req = require('request');
const reqPr = require('request-promise');
class RTXClient {
/**
* Initialize RTX Client
* @param {string} baseUrl - <Required> base API URL, Ex. 'https://api.rtxplatform.com'.
* @param {string} apiKey - <Required> RTX apiKey.
* @param {string} secretKey - <Required> RTX secretKey.
*/
constructor(baseUrl, apiKey, secretKey) {
this.baseUrl = baseUrl.replace(/\/+$/, "");
this.apiKey = apiKey;
this.secretKey = secretKey;
}
/**
* Make RTX API call, returns promise if no callBack function is passed.
* @param {string} method - <Required> HTTP method Ex. <'GET' | 'POST' | 'PUT' | 'UPDATE'>.
* @param {string} resourcePath - <Required> Ex. '/pops-api/v1/creatives'.
* @param {object} queryParams - <Optional> Additional URL query parameters.
* @param {object/string} body - <Optional> Request body payload.
* @param {function} callBack - <Optional> Call back function, will return promise if no callBack is passed.
*/
request(method, resourcePath, queryParams=null, body=null, callBack=null){
resourcePath = (resourcePath[0] !== '/') ? '/' + resourcePath : resourcePath
const uri = this.baseUrl + resourcePath;
const timestamp = Math.floor((new Date).getTime()/1000); // current epoch timestamp in seconds
if (body && typeof(body) === 'object')
body = JSON.stringify(body);
const signature = this.sign(method, resourcePath, timestamp, this.apiKey, this.secretKey, body);
queryParams = Object.assign({
timestamp,
api_key: this.apiKey,
signature
}, queryParams)
const options = {
uri,
method,
qs: queryParams,
}
if (body)
options['body'] = body;
const _callBack = (err, res, body) => {
if (!err && body)
body = JSON.parse(body)
callBack(err, res, body)
}
return callBack ? req(options, _callBack) : reqPr(options).then(res => JSON.parse(res));
}
sign(method, resourcePath, timestamp, apiKey, secretKey, body=null) {
let plainText = `${method} ${resourcePath}?api_key=${apiKey}×tamp=${timestamp}`
if (body)
plainText += "&" + body;
const sign = crypto.createHmac('sha256', secretKey);
sign.update(plainText);
return sign.digest('hex');
}
}
module.exports = RTXClient;