-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathgraph.js
113 lines (95 loc) · 2.5 KB
/
graph.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
'use strict';
const crypto = require('crypto');
const logger = require('heroku-logger')
const request = require('request-promise-native');
const workplaceBase = process.env.WORKPLACE_BASE || 'workplace.com';
const baseURL = `https://graph.${workplaceBase}`;
class GraphRequest {
constructor(path) {
this.path = path;
}
post() {
this.method = 'POST';
return this;
}
delete() {
this.method = 'DELETE';
return this;
}
token(token) {
this.accessToken = token;
this.sign = true;
return this;
}
appSecret() {
this.accessToken = process.env.APP_ID + '|' + process.env.APP_SECRET;
this.sign = false;
return this;
}
clientToken() {
this.accessToken = process.env.APP_ID + '|' + process.env.APP_CLIENT_TOKEN;
this.sign = false;
return this;
}
qs(qs) {
this.queryString = qs;
return this;
}
body(body) {
this.contentBody = body;
return this;
}
send() {
const version = process.env.GRAPH_VERSION || 'v3.2';
let options = {
method: this.method || 'GET',
uri: `${baseURL}/${version}/${this.path}`,
qs: Object.assign(this._calcProof(), this.queryString || {}),
json: true,
resolveWithFullResponse: true,
strictSSL: false,
};
if (this.accessToken) {
options.headers = { Authorization: `Bearer ${this.accessToken}` };
}
if ((this.method === 'POST' || this.method === 'DELETE') && this.contentBody) {
options.body = this.contentBody;
}
logger.info('sending request', options);
return request(options)
.then(result => {
logger.info(
'api response',
{
code: result.statusCode,
body: result.caseless.get('content-length') > 1000
? '--truncated--'
: JSON.stringify(result.body),
}
);
return result.body;
})
.catch(result => {
logger.warn('api error', {code: result.statusCode, body: JSON.stringify(result.body)});
throw new Error(result.message);
});
}
_calcProof() {
if (!this.sign) {
return {};
}
const appsecretTime = Math.floor(Date.now() / 1000) - 5;
const appsecretProof = crypto
.createHmac('sha256', process.env.APP_SECRET)
.update(this.accessToken + '|' + appsecretTime)
.digest('hex');
return {
appsecret_proof: appsecretProof,
appsecret_time: appsecretTime
};
}
}
function graph(path) {
return new GraphRequest(path);
}
module.exports = graph;