You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
1009 B
JavaScript

"use strict";
const url = require("url");
const ValidationError = require("@validatem/error");
module.exports = function (protocols) {
if (protocols != null && !Array.isArray(protocols)) {
throw new Error(`Permitted protocol list must be an array`);
}
let protocolSet = (protocols != null)
? new Set(protocols.map((protocol) => protocol.toLowerCase()))
: null;
return function isURL(value) {
let parsed = url.parse(value);
let parsedProtocol = (parsed.protocol != null)
? parsed.protocol.replace(/:$/, "")
: null;
if (parsedProtocol == null) {
return new ValidationError("Must be a valid URL");
} else if (protocolSet != null && !protocolSet.has(parsedProtocol.toLowerCase())) {
let validProtocolList = protocols
.map((protocol) => protocol.toUpperCase())
.join(", ");
return new ValidationError(`Must be a URL with one of the following protocols: ${validProtocolList} - but got ${parsedProtocol.toUpperCase()} instead`);
} else {
return parsed;
}
}
};