2020-10-16 08:06:03 +00:00
|
|
|
"use strict";
|
2020-10-02 12:01:51 +00:00
|
|
|
|
2020-10-09 14:42:13 +00:00
|
|
|
// Public modules from npm
|
2020-10-16 08:06:03 +00:00
|
|
|
const ky = require("ky-universal").create({
|
|
|
|
throwHttpErrors: false,
|
2020-10-09 14:42:13 +00:00
|
|
|
});
|
|
|
|
|
2020-10-01 19:13:23 +00:00
|
|
|
// Modules from file
|
2020-10-16 08:06:03 +00:00
|
|
|
const { F95_BASE_URL } = require("./constants/urls.js");
|
2020-10-01 19:13:23 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @protected
|
|
|
|
* Check if the url belongs to the domain of the F95 platform.
|
2020-10-08 21:08:20 +00:00
|
|
|
* @param {String} url URL to check
|
2020-10-01 19:13:23 +00:00
|
|
|
* @returns {Boolean} true if the url belongs to the domain, false otherwise
|
|
|
|
*/
|
2020-10-08 21:09:05 +00:00
|
|
|
module.exports.isF95URL = function (url) {
|
|
|
|
if (url.toString().startsWith(F95_BASE_URL)) return true;
|
|
|
|
else return false;
|
|
|
|
};
|
2020-10-01 19:13:23 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @protected
|
|
|
|
* Checks if the string passed by parameter has a properly formatted and valid path to a URL.
|
|
|
|
* @param {String} url String to check for correctness
|
|
|
|
* @returns {Boolean} true if the string is a valid URL, false otherwise
|
|
|
|
*/
|
2020-10-09 14:45:17 +00:00
|
|
|
module.exports.isStringAValidURL = function (url) {
|
|
|
|
try {
|
2020-10-16 07:45:58 +00:00
|
|
|
new URL(url); // skipcq: JS-0078
|
2020-10-09 14:45:17 +00:00
|
|
|
return true;
|
|
|
|
} catch (err) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
};
|
2020-10-09 14:42:13 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @public
|
|
|
|
* Check if a particular URL is valid and reachable on the web.
|
|
|
|
* @param {String} url URL to check
|
|
|
|
* @param {Boolean} checkRedirect If true, the function will consider redirects a violation and return false
|
|
|
|
* @returns {Promise<Boolean>} true if the URL exists, false otherwise
|
|
|
|
*/
|
2020-10-09 14:45:17 +00:00
|
|
|
module.exports.urlExists = async function (url, checkRedirect) {
|
2020-10-09 14:58:32 +00:00
|
|
|
if (!exports.isStringAValidURL(url)) {
|
2020-10-09 14:45:17 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
const response = await ky.head(url);
|
|
|
|
let valid = response !== undefined && !/4\d\d/.test(response.status);
|
|
|
|
|
|
|
|
if (!valid) return false;
|
|
|
|
|
|
|
|
if (checkRedirect) {
|
|
|
|
if (response.url === url) valid = true;
|
|
|
|
else valid = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return valid;
|
|
|
|
};
|