-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathwebex.js
74 lines (63 loc) · 1.6 KB
/
webex.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
let currentSearchNumber = 0;
const webexMsgUrl = 'https://webexapis.com/v1/messages';
const webexSearchUrl = 'https://webexapis.com/v1/people?displayName=';
async function get(url, token) {
if (!token) throw(new Error('No webex token specified'));
const options = {
method: 'GET',
headers: {
Authorization: 'Bearer ' + token,
},
};
try {
const data = await fetch(url, options);
const json = await data.json();
return json.items || [];
}
catch(e) {
console.log('not able to fetch');
return [];
}
}
function sendMessage(token, toPersonEmail, markdown, file) {
const formData = new FormData();
if (file) {
formData.append('files', file);
}
formData.set('markdown', markdown);
formData.set('toPersonEmail', toPersonEmail);
const options = {
headers: {
Authorization: 'Bearer ' + token,
},
method: 'POST',
body: formData,
};
return fetch(webexMsgUrl, options);
}
function mockResult(keyword) {
const img = Math.ceil(Math.random() * 60);
return [
{
displayName: `${keyword} Johnson`,
avatar: `https://i.pravatar.cc/500?img=${img}`,
emails: [`${keyword}@acme.com`],
},
];
}
async function searchPerson(keyword, token, callback) {
if (!keyword) return;
if (!token) {
callback(mockResult(keyword));
return;
}
currentSearchNumber++;
const id = currentSearchNumber; // avoid closure
const url = webexSearchUrl + keyword;
const result = await get(url, token);
// a newer search has been requested, discard this one
if (id < currentSearchNumber) {
return;
}
callback(result);
}