All files / routes/admin taxonomy.validators.ts

100% Statements 14/14
100% Branches 16/16
100% Functions 5/5
100% Lines 13/13

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 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                                46x 5x                 11x             23x 41x   23x 14x                     28x 6x         3x           25x 9x         2x            
// Taxonomy Validation Helpers
import { ValidationError } from "../../lib/errors";
import { MATERIAL_CATEGORIES, BRAND_CATEGORIES } from "../../db/schema";
import {
	type TaxonomyType,
	type StandardTaxonomyType,
	REQUIRED_FIELDS,
	ALL_TAXONOMY_TYPES,
} from "./taxonomy.config";
 
// Re-export TaxonomyType for use in tests
export type { TaxonomyType } from "./taxonomy.config";
 
export function validateTaxonomyType(
	type: string,
): asserts type is TaxonomyType {
	if (!ALL_TAXONOMY_TYPES.includes(type)) {
		throw new ValidationError(
			`Invalid taxonomy type: ${type}. Valid types are: ${ALL_TAXONOMY_TYPES.join(", ")}`,
		);
	}
}
 
export function isStandardTaxonomyType(
	type: TaxonomyType,
): type is StandardTaxonomyType {
	return type !== "roomTypes";
}
 
export function validateRequiredFields(
	type: TaxonomyType,
	data: Record<string, unknown>,
) {
	const required = REQUIRED_FIELDS[type];
	const missing = required.filter((field) => !data[field]);
 
	if (missing.length > 0) {
		throw new ValidationError(
			`Missing required fields for ${type}: ${missing.join(", ")}`,
		);
	}
}
 
// Validate enum values for specific fields
export function validateEnumFields(
	type: TaxonomyType,
	data: Record<string, unknown>,
) {
	if (type === "materialTags" && data.category) {
		if (
			!MATERIAL_CATEGORIES.includes(
				data.category as (typeof MATERIAL_CATEGORIES)[number],
			)
		) {
			throw new ValidationError(
				`Invalid category for materialTags. Must be one of: ${MATERIAL_CATEGORIES.join(", ")}`,
			);
		}
	}
 
	if (type === "brands" && data.category) {
		if (
			!BRAND_CATEGORIES.includes(
				data.category as (typeof BRAND_CATEGORIES)[number],
			)
		) {
			throw new ValidationError(
				`Invalid category for brands. Must be one of: ${BRAND_CATEGORIES.join(", ")}`,
			);
		}
	}
}