All files / lib id-parsing.ts

100% Statements 14/14
100% Branches 10/10
100% Functions 3/3
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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      208x 206x 206x 161x                 194x 194x 153x       5x   4x 4x    
import { ValidationError } from "./errors";
 
export function parseIntId(value: string | undefined): number | null {
	if (!value) return null;
	const parsed = parseInt(value, 10);
	if (Number.isNaN(parsed) || parsed < 1) return null;
	return parsed;
}
 
// Same as parseIntId, but throws 400 on missing/invalid. Use in route handlers
// to drop the parseIntId + null-check + throw triad.
export function parseRequiredId(
	value: string | undefined,
	resource: string,
): number {
	const id = parseIntId(value);
	if (!id) throw new ValidationError(`Invalid ${resource} ID`);
	return id;
}
 
export function isValidUuid(value: string | undefined): boolean {
	if (!value) return false;
	const uuidRegex =
		/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
	return uuidRegex.test(value);
}