Add mocha server tests for /api/build-requests
[WebKit.git] / Websites / perf.webkit.org / tools / js / remote.js
1 'use strict';
2
3 let assert = require('assert');
4 let http = require('http');
5 let https = require('https');
6
7 let RemoteAPI = new (class RemoteAPI {
8     constructor()
9     {
10         this._server = {
11             scheme: 'http',
12             host: 'localhost',
13         }
14     }
15
16     configure(server)
17     {
18         assert(server.scheme === 'http' || server.scheme === 'https');
19         assert.equal(typeof(server.host), 'string');
20         assert(!server.port || typeof(server.port) == 'number');
21         assert(!server.auth || typeof(server.auth) == 'object');
22         this._server = server;
23     }
24
25     fetchJSON(path, data)
26     {
27         let contentType = null;
28         if (data) {
29             contentType = 'application/json';
30             data = JSON.stringify(data);
31         }
32         return this.sendHttpRequest(path, 'GET', contentType, data).then(function (result) {
33             return JSON.parse(result.responseText);
34         });
35     }
36
37     fetchJSONWithStatus(path, data)
38     {
39         return this.fetchJSON(path, data).then(function (result) {
40             if (result['status'] != 'OK')
41                 return Promise.reject(result);
42             return result;
43         });
44     }
45
46     sendHttpRequest(path, method, contentType, content)
47     {
48         let server = this._server;
49         return new Promise(function (resolve, reject) {
50             let options = {
51                 hostname: server.host,
52                 port: server.port || 80,
53                 auth: server.auth,
54                 method: method,
55                 path: path,
56             };
57
58             let request = (server.scheme == 'http' ? http : https).request(options, function (response) {
59                 let responseText = '';
60                 response.setEncoding('utf8');
61                 response.on('data', function (chunk) { responseText += chunk; });
62                 response.on('end', function () { resolve({statusCode: response.statusCode, responseText: responseText}); });
63             });
64
65             request.on('error', reject);
66
67             if (contentType)
68                 request.setHeader('Content-Type', contentType);
69
70             if (content)
71                 request.write(content);
72
73             request.end();
74         });
75     }
76 })
77
78 if (typeof module != 'undefined')
79     module.exports.RemoteAPI = RemoteAPI;