qapinterface
Version:
Comprehensive API utilities for Node.js applications including authentication, security, request processing, and response handling with zero external dependencies
55 lines (48 loc) • 1.44 kB
JavaScript
/**
* URL Schema Creator
* Single Responsibility: Create URL validation schemas ONLY
*/
const { z } = require('zod');
/**
* Creates a Zod schema for validating URLs against a set of rules.
* @param {object} [options] - Validation options.
* @returns {z.ZodSchema} A Zod schema for URL validation.
*/
function createUrlSchema(options = {}) {
const {
allowedDomains = [],
blockedDomains = [],
requireHttps = true,
} = options;
return z.string().url({ message: 'Invalid URL format' }).superRefine((val, ctx) => {
try {
const url = new URL(val);
if (requireHttps && url.protocol !== 'https:') {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'URL must use the HTTPS protocol.',
});
}
if (allowedDomains.length > 0 && !allowedDomains.includes(url.hostname)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Domain '${url.hostname}' is not in the list of allowed domains.`,
});
}
if (blockedDomains.length > 0 && blockedDomains.includes(url.hostname)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Domain '${url.hostname}' is blocked.`,
});
}
} catch (e) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Failed to parse URL for validation.',
});
}
});
}
module.exports = {
createUrlSchema
};