UNPKG

8.53 kBJavaScriptView Raw
1'use strict';
2
3import { endPoints, parameters } from './endPoints';
4import { GUID } from './redutil';
5
6import * as Globals from './globals';
7
8//require('es6-promise').polyfill();
9if (typeof self !== 'undefined' && !fetch) {
10 //when its in the web.
11 console.log('-- --- using isomorphic-fetch')
12 require('isomorphic-fetch');
13}
14var accessToken = '';
15var getEndpoint = (baseDomain, path) => {
16 var endpoint = baseDomain + path;
17 if (baseDomain.endsWith('/') && path.startsWith('/')) {
18 endpoint = baseDomain + path.substring(1);
19 }
20 else if (!baseDomain.endsWith('/') && !path.startsWith('/')) {
21 endpoint = baseDomain + '/' + path;
22 }
23
24 return endpoint;
25}
26export function createRedService(domain, wsdomain, _forceBase) {
27 var forceBase = false;
28 forceBase = _forceBase;
29 var baseDomain = domain;
30 var wsbaseDomain = wsdomain;
31 var headers = {
32 'Accept': 'application/json',
33 'Content-Type': 'application/json'
34 };
35 var connection,
36 proxy,
37 websocketConnection,
38 receivedMessageHandler,
39 onUnauthorizedHandler;
40 var service = {
41 setDomain: function (domain) {
42 baseDomain = domain;
43 },
44 onReceiveMessage: function (receiveMessageHandler) {
45 receivedMessageHandler = receiveMessageHandler;
46 },
47 onUnauthorized: function (handler) {
48 onUnauthorizedHandler = handler;
49 },
50 setWSDomain: function (domain) {
51 wsbaseDomain = domain;
52 },
53 setUserAccessToken: function (access_token) {
54 accessToken = access_token;
55 service.r.connect();
56 },
57 setBearerAccessToken: function (access_token) {
58 accessToken = access_token;
59 },
60 getAccessToken: function () {
61 return accessToken;
62 },
63 call: function (endpoint, method, body) {
64 console.log(`calling at ${(new Date()).toTimeString()} ${endpoint}`)
65 return fetch(endpoint, {
66 headers: Object.assign({}, headers, {
67 'Authorization': 'Bearer ' + service.getAccessToken()
68 }),
69 method: method,
70 body: body == undefined ? null : JSON.stringify(body)
71 }).then(function (response) {
72
73 //setTimeout(() => null, 0); // workaround for issue-6679
74 if (response.status === 401) {
75
76 throw {
77 unauthorized: true,
78 status: response.status
79 }
80 }
81 else if (response.status >= 400) {
82
83 throw {
84 status: response.status,
85 message: response,
86
87 }
88 }
89
90 return response.json().then(function (json) {
91 console.log(`called at ${(new Date()).toTimeString()} ${endpoint}`)
92 return json;
93 })
94 }).catch(e => {
95 console.log(e);
96 if (e && e.unauthorized && onUnauthorizedHandler) {
97 onUnauthorizedHandler(e);
98 }
99 return Promise.reject(e);
100 });
101 },
102 delete: function (path) {
103 return Globals.getDefaultURL().then(_baseDomain => {
104 var endpoint = getEndpoint(forceBase ? baseDomain || _baseDomain : _baseDomain, path);
105 return service.call(endpoint, 'DELETE');
106 });
107 },
108 put: function (path, body) {
109 return Globals.getDefaultURL().then(_baseDomain => {
110 var endpoint = getEndpoint(forceBase ? baseDomain || _baseDomain : _baseDomain, path);
111 return service.call(endpoint, 'PUT', body);
112 });
113 },
114 post: function (path, body) {
115 return Globals.getDefaultURL().then(_baseDomain => {
116 var endpoint = getEndpoint(forceBase ? baseDomain || _baseDomain : _baseDomain, path);
117 return service.call(endpoint, 'POST', body);
118 });
119 },
120 patch: function (path, body) {
121 return Globals.getDefaultURL().then(_baseDomain => {
122 var endpoint = getEndpoint(forceBase ? baseDomain || _baseDomain : _baseDomain, path);
123 return service.call(endpoint, 'PATCH', body);
124 });
125 },
126 get: function (path) {
127 return Globals.getDefaultURL().then(_baseDomain => {
128 var endpoint = getEndpoint(forceBase ? baseDomain || _baseDomain : _baseDomain, path);
129 return service.call(endpoint, 'GET');
130 });
131 },
132 r: {
133 close: () => {
134 if (websocketConnection && websocketConnection.close) {
135 websocketConnection.close();
136 console.log('Web socket closed');
137 }
138 },
139 connect: function (handler, onopen, onclose, onerror) {
140 receivedMessageHandler = handler || receivedMessageHandler;
141 var promise = Promise.resolve();
142 var oncatch = e => {
143 if (e && e.message && e.message.json) {
144 return e.message.json().then(c => UIA.log(c)).catch(() => { });
145 }
146 UIA.log(e);
147 };
148 function connectToService() {
149 return Globals.getDefaultWS().then(wsbaseDomain => {
150 return new Promise((resolve, fail) => {
151 service.post(endPoints.blindCreds).then((cred) => {
152
153 var ws = new WebSocket(wsbaseDomain + endPoints.socket + '?name=' + cred);
154
155 ws.onopen = () => {
156 // connection opened
157 // ws.send('something');
158 websocketConnection = ws;
159 if (onopen) {
160 onopen();
161 }
162 };
163
164 ws.onmessage = (e) => {
165 // a message was received
166
167 if (receivedMessageHandler) {
168 receivedMessageHandler(e.data);
169 }
170 };
171
172 ws.onerror = (e) => {
173 // setTimeout(function () {
174 // resolve();
175 // promise = promise.then(() => {
176 // connectToService();
177 // });
178 // }, 5000)
179 if (onerror) {
180 onerror(e);
181 }
182 };
183
184 ws.onclose = (e) => {
185 // connection closed
186 if (onclose) {
187 onclose(e);
188 }
189 setTimeout(function () {
190 resolve();
191 promise = promise.then(() => {
192 return connectToService().catch(oncatch);
193 });
194 }, 5000)
195
196 };
197 }).catch(e => {
198 resolve();
199 return Promise.resolve().then(() => {
200 return oncatch(e)
201 }).then(() => {
202 return connectToService().catch(oncatch);
203 });
204 });
205 });
206 });
207 }
208 if (!service.testMode) {
209 promise = promise.then(() => {
210 return connectToService().catch(oncatch);
211 });
212 }
213 }
214 }
215 }
216 return service;
217}
218
219// export default _createService;
\No newline at end of file