UNPKG

2.52 kBJavaScriptView Raw
1const { map, expand, retryWhen, tap, takeWhile } = require('rxjs/operators');
2
3// const { BASE_URL, DEFAULT_HEADERS } = require('./constants');
4const DEFAULT_TIMEOUT = 10000;
5
6class ChatApi {
7
8 constructor(config, driver = require('./requestDriver')) {
9 if (!config) throw new Error('No config was given.');
10 this.__config = config;
11 this.__driver = driver;
12 }
13
14 __request(url, method, params = {}, body = {}, headers = {}) {
15 return this.__driver.request({
16 baseUrl: this.__config.baseURL,
17 url,
18 headers: { ...this.__config.defaultHeaders, ...headers },
19 method,
20 qs: { ...params, access_token: this.__token },
21 body,
22 json: true,
23 timeout: DEFAULT_TIMEOUT
24 });
25 }
26
27 createSession() {
28 return this.__request('/chat/rest/System/SessionId', 'GET')
29 .toPromise();
30 }
31
32 initializeChasitor(session, chasitor = {}) {
33 const headers = {
34 "X-LIVEAGENT-AFFINITY": session.affinityToken,
35 "X-LIVEAGENT-SESSION-KEY": session.key,
36 "X-LIVEAGENT-SEQUENCE": 1
37 };
38 const body = {
39 ...chasitor,
40 sessionId: session.id
41 };
42 return this.__request('/chat/rest/Chasitor/ChasitorInit', 'POST', {}, body, headers)
43 .toPromise();
44 }
45
46 sendMessage(session, text) {
47 const headers = {
48 "X-LIVEAGENT-AFFINITY": session.affinityToken,
49 "X-LIVEAGENT-SESSION-KEY": session.key
50 };
51 return this.__request('/chat/rest/Chasitor/ChatMessage', 'POST', {}, { text }, headers)
52 .toPromise();
53 }
54
55 __readMessage(cursorId, headers) {
56 return this.__request('/chat/rest/System/Messages', 'GET', { ack: cursorId }, {}, headers);
57 }
58
59 endChat(session){
60 const headers = {
61 "X-LIVEAGENT-AFFINITY": session.affinityToken,
62 "X-LIVEAGENT-SESSION-KEY": session.key
63 };
64 return this.__request('/chat/rest/Chasitor/ChatEnd', 'POST', {}, {ChatEndReason:{reason: 'client closed window'}}, headers)
65 .toPromise();
66 }
67
68 readMessages(session) {
69 let cursorId = 0;
70 const headers = {
71 "X-LIVEAGENT-AFFINITY": session.affinityToken,
72 "X-LIVEAGENT-SESSION-KEY": session.key
73 };
74 return this.__readMessage(cursorId, headers).pipe(
75 expand(response => this.__readMessage(cursorId++, headers)),
76 retryWhen(error$ => error$.pipe(
77 tap(error => console.error(error.code)),
78 takeWhile(error => error.code === "ESOCKETTIMEDOUT" || error.code === "ETIMEDOUT")
79 )),
80 map(data => data && data.messages || [])
81 );
82 }
83}
84
85module.exports = ChatApi;
\No newline at end of file