In-browser and node.js implementations of RemoteAPI should share some code
[WebKit.git] / Websites / perf.webkit.org / public / shared / common-remote.js
1 "use strict";
2
3 class CommonRemoteAPI {
4     postJSON(path, data)
5     {
6         return this._asJSON(this.sendHttpRequest(path, 'POST', 'application/json', JSON.stringify(data || {})));
7     }
8
9     postJSONWithStatus(path, data)
10     {
11         return this._checkStatus(this.postJSON(path, data));
12     }
13
14     getJSON(path)
15     {
16         return this._asJSON(this.sendHttpRequest(path, 'GET', null, null));
17     }
18
19     getJSONWithStatus(path)
20     {
21         return this._checkStatus(this.getJSON(path));
22     }
23
24     sendHttpRequest(path, method, contentType, content)
25     {
26         throw 'NotImplemented';
27     }
28
29     _asJSON(promise)
30     {
31         return promise.then((result) => {
32             try {
33                 return JSON.parse(result.responseText);
34             } catch (error) {
35                 console.error(result.responseText);
36                 reject(result.statusCode + ', ' + error);
37             }
38         });
39     }
40
41     _checkStatus(promise)
42     {
43         return promise.then(function (content) {
44             if (content['status'] != 'OK')
45                 throw content['status'];
46             return content;
47         });
48     }
49 }
50
51 if (typeof module != 'undefined')
52     module.exports.CommonRemoteAPI = CommonRemoteAPI;