-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathresponseCompare.check.js
69 lines (59 loc) · 1.54 KB
/
responseCompare.check.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
'use strict';
const status = require('./status');
const Check = require('./check');
const fetch = require('node-fetch');
const logger = require('@dotcom-reliability-kit/logger');
function allEqual(responses) {
for (let i = 1, l = responses.length; i < l; i++) {
if (responses[i] !== responses[0]) {
return false;
}
}
return true;
}
class ResponseCompareCheck extends Check {
constructor(options) {
super(options);
this.comparison = options.comparison;
this.urls = options.urls;
this.headers = options.headers || {};
this.normalizeResponse = options.normalizeResponse || ((resp) => resp);
}
get checkOutput() {
if (this.status === status.PENDING) {
return 'this test has not yet run';
}
const urls = this.urls.join(' & ');
if (this.comparison === ResponseCompareCheck.comparisons.EQUAL) {
return `${urls} are ${this.status === status.PASSED ? '' : 'not'} equal`;
}
return undefined;
}
async tick() {
try {
const responses = await Promise.all(
this.urls.map((url) =>
fetch(url, { headers: this.headers }).then((r) =>
r.text().then(this.normalizeResponse)
)
)
);
if (this.comparison === ResponseCompareCheck.comparisons.EQUAL) {
this.status = allEqual(responses) ? status.PASSED : status.FAILED;
}
} catch (error) {
logger.error(
{
event: 'RESPONSE_COMPARE_CHECK_ERROR',
message: 'Response was not OK'
},
error
);
this.status = status.FAILED;
}
}
}
ResponseCompareCheck.comparisons = {
EQUAL: 'equal'
};
module.exports = ResponseCompareCheck;