forked from sznowicki/uptime-check
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
98 lines (84 loc) · 2.05 KB
/
index.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const request = require('./tasks/request');
/**
* Validates options. Throws Error if something is wrong.
*
* @param {UptimeCheckOptions} opts
* @throws Error
*/
const validateOptions = (opts) => {
const keysRequired = [
'url'
];
const numbers = [
'redirectsLimit',
'timeOut'
];
const strings = [
'keyword',
'url'
];
const objects = [
'headers'
];
keysRequired.forEach(key => {
if (!opts.hasOwnProperty(key)) {
throw new Error(`Missing required option: ${key}`);
}
});
numbers.forEach(key => {
if (typeof opts[key] !== 'number' || parseInt(opts[key]) !== opts[key]) {
throw new Error(`Invalid option: ${key} must be an integer number`);
}
});
strings.forEach(key => {
if (opts[key] && typeof opts[key] !== 'string') {
throw new Error(`Invalid option: ${key} must be a string.`);
}
});
objects.forEach(key => {
if (opts[key] && typeof opts[key] !== 'object') {
throw new Error(`Invalid option: ${key} must be an object.`);
}
});
// Only http and https can be tested.
if (opts.url.startsWith('http') === false) {
throw new Error('Url must be http:// or https://');
}
}
/**
* Merges options with defaults.
* @param {UptimeCheckOptions} opts
* @returns {UptimeCheckOptions}
*/
const mergeDefaults = (opts) => {
const defaults = {
keyword: null,
redirectsLimit: 3,
headers: {
'User-Agent': 'Uptime-check - https://www.npmjs.com/package/uptime-check',
},
timeOut: 10
};
return Object.assign({}, defaults, opts);
}
/**
*
* @param {UptimeCheckOptions} opts
* @returns {Promise<UptimeCheckResult>}
*/
const check = async (opts) => {
/**
*
* @type {UptimeCheckOptions}
*/
const options = mergeDefaults(opts);
validateOptions(options)
const result = await request(options);
const httpCode = result.httpCode;
result.status = (httpCode >= 200 && httpCode < 300);
if (result.status && options.keyword) {
result.status = result.body.indexOf(options.keyword) > -1;
}
return result;
}
module.exports = check;