mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-20 04:31:13 -05:00
feat: Implement strict type enforcement
This commit is contained in:
@@ -21,6 +21,11 @@ export default tseslint.config(
|
||||
...reactHooks.configs.recommended.rules,
|
||||
"react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
|
||||
"@typescript-eslint/no-unused-vars": "off",
|
||||
"@typescript-eslint/no-explicit-any": "error",
|
||||
"@typescript-eslint/no-unsafe-assignment": "warn",
|
||||
"@typescript-eslint/no-unsafe-member-access": "warn",
|
||||
"@typescript-eslint/no-unsafe-call": "warn",
|
||||
"@typescript-eslint/no-unsafe-return": "warn",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -157,7 +157,7 @@ export function DesignerForm({ onSubmit, onCancel, initialData }: DesignerFormPr
|
||||
<Label>Entity Type *</Label>
|
||||
<RadioGroup
|
||||
value={watch('person_type')}
|
||||
onValueChange={(value) => setValue('person_type', value as any)}
|
||||
onValueChange={(value) => setValue('person_type', value as 'company' | 'individual' | 'firm' | 'organization')}
|
||||
className="grid grid-cols-2 md:grid-cols-4 gap-4"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
|
||||
@@ -160,7 +160,7 @@ export function ManufacturerForm({ onSubmit, onCancel, initialData }: Manufactur
|
||||
<Label>Entity Type *</Label>
|
||||
<RadioGroup
|
||||
value={watch('person_type')}
|
||||
onValueChange={(value) => setValue('person_type', value as any)}
|
||||
onValueChange={(value) => setValue('person_type', value as 'company' | 'individual' | 'firm' | 'organization')}
|
||||
className="grid grid-cols-2 md:grid-cols-4 gap-4"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
|
||||
@@ -157,7 +157,7 @@ export function OperatorForm({ onSubmit, onCancel, initialData }: OperatorFormPr
|
||||
<Label>Entity Type *</Label>
|
||||
<RadioGroup
|
||||
value={watch('person_type')}
|
||||
onValueChange={(value) => setValue('person_type', value as any)}
|
||||
onValueChange={(value) => setValue('person_type', value as 'company' | 'individual' | 'firm' | 'organization')}
|
||||
className="grid grid-cols-2 md:grid-cols-4 gap-4"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
|
||||
@@ -142,7 +142,7 @@ export function ParkForm({ onSubmit, onCancel, initialData, isEditing = false }:
|
||||
status: initialData?.status || 'Operating',
|
||||
opening_date: initialData?.opening_date || '',
|
||||
closing_date: initialData?.closing_date || '',
|
||||
location_id: (initialData as any)?.location_id || undefined,
|
||||
location_id: initialData?.location_id || undefined,
|
||||
website_url: initialData?.website_url || '',
|
||||
phone: initialData?.phone || '',
|
||||
email: initialData?.email || '',
|
||||
|
||||
@@ -157,7 +157,7 @@ export function PropertyOwnerForm({ onSubmit, onCancel, initialData }: PropertyO
|
||||
<Label>Entity Type *</Label>
|
||||
<RadioGroup
|
||||
value={watch('person_type')}
|
||||
onValueChange={(value) => setValue('person_type', value as any)}
|
||||
onValueChange={(value) => setValue('person_type', value as 'company' | 'individual' | 'firm' | 'organization')}
|
||||
className="grid grid-cols-2 md:grid-cols-4 gap-4"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
|
||||
@@ -229,8 +229,8 @@ export function RideForm({ onSubmit, onCancel, initialData, isEditing = false }:
|
||||
_tempNewRideModel: tempNewRideModel
|
||||
};
|
||||
|
||||
// Pass clean data to parent
|
||||
await onSubmit(metricData as any);
|
||||
// Pass clean data to parent with extended fields
|
||||
await onSubmit(metricData);
|
||||
|
||||
toast({
|
||||
title: isEditing ? "Ride Updated" : "Submission Sent",
|
||||
|
||||
@@ -39,7 +39,7 @@ type RideModelFormData = z.infer<typeof rideModelSchema>;
|
||||
interface RideModelFormProps {
|
||||
manufacturerName: string;
|
||||
manufacturerId?: string;
|
||||
onSubmit: (data: RideModelFormData) => void;
|
||||
onSubmit: (data: RideModelFormData & { _technical_specifications?: unknown[] }) => void;
|
||||
onCancel: () => void;
|
||||
initialData?: Partial<RideModelFormData & {
|
||||
id?: string;
|
||||
@@ -87,11 +87,11 @@ export function RideModelForm({
|
||||
|
||||
|
||||
const handleFormSubmit = (data: RideModelFormData) => {
|
||||
// Include relational technical specs
|
||||
// Include relational technical specs with extended type
|
||||
onSubmit({
|
||||
...data,
|
||||
_technical_specifications: technicalSpecs
|
||||
} as any);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -8,28 +8,41 @@ import { supabase } from '@/integrations/supabase/client';
|
||||
|
||||
const currentYear = new Date().getFullYear();
|
||||
|
||||
// Park Schema
|
||||
// ============================================
|
||||
// SHARED IMAGE UPLOAD SCHEMA
|
||||
// ============================================
|
||||
|
||||
const imageAssignmentSchema = z.object({
|
||||
uploaded: z.array(z.any()),
|
||||
banner_assignment: z.number().int().min(0).nullable().optional(),
|
||||
card_assignment: z.number().int().min(0).nullable().optional()
|
||||
}).optional().default({ uploaded: [], banner_assignment: null, card_assignment: null });
|
||||
|
||||
// ============================================
|
||||
// PARK SCHEMA
|
||||
// ============================================
|
||||
|
||||
export const parkValidationSchema = z.object({
|
||||
name: z.string().min(1, 'Park name is required').max(200, 'Name must be less than 200 characters'),
|
||||
slug: z.string().min(1, 'Slug is required').regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
|
||||
description: z.string().max(2000, 'Description must be less than 2000 characters').optional(),
|
||||
name: z.string().trim().min(1, 'Park name is required').max(200, 'Name must be less than 200 characters'),
|
||||
slug: z.string().trim().min(1, 'Slug is required').regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
|
||||
description: z.string().trim().max(2000, 'Description must be less than 2000 characters').optional().or(z.literal('')),
|
||||
park_type: z.string().min(1, 'Park type is required'),
|
||||
status: z.string().min(1, 'Status is required'),
|
||||
opening_date: z.string().optional().refine((val) => {
|
||||
opening_date: z.string().optional().or(z.literal('')).refine((val) => {
|
||||
if (!val) return true;
|
||||
const date = new Date(val);
|
||||
return date <= new Date();
|
||||
}, 'Opening date cannot be in the future'),
|
||||
opening_date_precision: z.enum(['day', 'month', 'year']).optional(),
|
||||
closing_date: z.string().optional(),
|
||||
closing_date: z.string().optional().or(z.literal('')),
|
||||
closing_date_precision: z.enum(['day', 'month', 'year']).optional(),
|
||||
location_id: z.string().uuid().optional().nullable(),
|
||||
website_url: z.string().optional().refine((val) => {
|
||||
website_url: z.string().trim().optional().or(z.literal('')).refine((val) => {
|
||||
if (!val || val === '') return true;
|
||||
return z.string().url().safeParse(val).success;
|
||||
}, 'Invalid URL format'),
|
||||
phone: z.string().max(50, 'Phone must be less than 50 characters').optional(),
|
||||
email: z.string().optional().refine((val) => {
|
||||
phone: z.string().trim().max(50, 'Phone must be less than 50 characters').optional().or(z.literal('')),
|
||||
email: z.string().trim().optional().or(z.literal('')).refine((val) => {
|
||||
if (!val || val === '') return true;
|
||||
return z.string().email().safeParse(val).success;
|
||||
}, 'Invalid email format'),
|
||||
@@ -39,11 +52,7 @@ export const parkValidationSchema = z.object({
|
||||
banner_image_url: z.string().optional(),
|
||||
card_image_id: z.string().optional(),
|
||||
card_image_url: z.string().optional(),
|
||||
images: z.object({
|
||||
uploaded: z.array(z.any()),
|
||||
banner_assignment: z.number().nullable().optional(),
|
||||
card_assignment: z.number().nullable().optional(),
|
||||
}).optional(),
|
||||
images: imageAssignmentSchema,
|
||||
}).refine((data) => {
|
||||
if (data.closing_date && data.opening_date) {
|
||||
return new Date(data.closing_date) >= new Date(data.opening_date);
|
||||
@@ -54,62 +63,93 @@ export const parkValidationSchema = z.object({
|
||||
path: ['closing_date'],
|
||||
});
|
||||
|
||||
// Ride Schema
|
||||
// ============================================
|
||||
// RIDE SCHEMA
|
||||
// ============================================
|
||||
|
||||
export const rideValidationSchema = z.object({
|
||||
name: z.string().min(1, 'Ride name is required').max(200, 'Name must be less than 200 characters'),
|
||||
slug: z.string().min(1, 'Slug is required').regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
|
||||
description: z.string().max(2000, 'Description must be less than 2000 characters').optional(),
|
||||
name: z.string().trim().min(1, 'Ride name is required').max(200, 'Name must be less than 200 characters'),
|
||||
slug: z.string().trim().min(1, 'Slug is required').regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
|
||||
description: z.string().trim().max(2000, 'Description must be less than 2000 characters').optional().or(z.literal('')),
|
||||
category: z.string().min(1, 'Category is required'),
|
||||
ride_sub_type: z.string().max(100, 'Sub type must be less than 100 characters').optional(),
|
||||
ride_sub_type: z.string().trim().max(100, 'Sub type must be less than 100 characters').optional().or(z.literal('')),
|
||||
status: z.string().min(1, 'Status is required'),
|
||||
park_id: z.string().uuid().optional().nullable(),
|
||||
designer_id: z.string().uuid().optional().nullable(),
|
||||
opening_date: z.string().optional(),
|
||||
opening_date: z.string().optional().or(z.literal('')),
|
||||
opening_date_precision: z.enum(['day', 'month', 'year']).optional(),
|
||||
closing_date: z.string().optional(),
|
||||
closing_date: z.string().optional().or(z.literal('')),
|
||||
closing_date_precision: z.enum(['day', 'month', 'year']).optional(),
|
||||
height_requirement: z.number().min(0, 'Height requirement must be positive').max(300, 'Height requirement must be less than 300cm').optional(),
|
||||
age_requirement: z.number().min(0, 'Age requirement must be positive').max(100, 'Age requirement must be less than 100').optional(),
|
||||
capacity_per_hour: z.number().min(0, 'Capacity must be positive').optional(),
|
||||
duration_seconds: z.number().min(0, 'Duration must be positive').optional(),
|
||||
max_speed_kmh: z.number().min(0, 'Speed must be positive').max(300, 'Speed must be less than 300 km/h').optional(),
|
||||
max_height_meters: z.number().min(0, 'Height must be positive').max(200, 'Height must be less than 200 meters').optional(),
|
||||
length_meters: z.number().min(0, 'Length must be positive').optional(),
|
||||
inversions: z.number().min(0, 'Inversions must be positive').optional(),
|
||||
height_requirement: z.preprocess(
|
||||
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
||||
z.number().int().min(0, 'Height requirement must be positive').max(300, 'Height requirement must be less than 300cm').optional()
|
||||
),
|
||||
age_requirement: z.preprocess(
|
||||
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
||||
z.number().int().min(0, 'Age requirement must be positive').max(100, 'Age requirement must be less than 100').optional()
|
||||
),
|
||||
capacity_per_hour: z.preprocess(
|
||||
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
||||
z.number().int().min(1, 'Capacity must be positive').max(99999, 'Capacity must be less than 100,000').optional()
|
||||
),
|
||||
duration_seconds: z.preprocess(
|
||||
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
||||
z.number().int().min(1, 'Duration must be positive').max(86400, 'Duration must be less than 24 hours').optional()
|
||||
),
|
||||
max_speed_kmh: z.preprocess(
|
||||
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
||||
z.number().min(0, 'Speed must be positive').max(500, 'Speed must be less than 500 km/h').optional()
|
||||
),
|
||||
max_height_meters: z.preprocess(
|
||||
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
||||
z.number().min(0, 'Height must be positive').max(200, 'Height must be less than 200 meters').optional()
|
||||
),
|
||||
length_meters: z.preprocess(
|
||||
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
||||
z.number().min(0, 'Length must be positive').max(10000, 'Length must be less than 10km').optional()
|
||||
),
|
||||
inversions: z.preprocess(
|
||||
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
||||
z.number().int().min(0, 'Inversions must be positive').max(20, 'Inversions must be less than 20').optional()
|
||||
),
|
||||
drop_height_meters: z.preprocess(
|
||||
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
||||
z.number().min(0, 'Drop height must be positive').max(200, 'Drop height must be less than 200 meters').optional()
|
||||
),
|
||||
max_g_force: z.preprocess(
|
||||
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
||||
z.number().min(-10, 'G-force must be greater than -10').max(10, 'G-force must be less than 10').optional()
|
||||
),
|
||||
manufacturer_id: z.string().uuid().optional().nullable(),
|
||||
ride_model_id: z.string().uuid().optional().nullable(),
|
||||
coaster_type: z.string().optional(),
|
||||
seating_type: z.string().optional(),
|
||||
intensity_level: z.string().optional(),
|
||||
drop_height_meters: z.number().min(0, 'Drop height must be positive').max(200, 'Drop height must be less than 200 meters').optional(),
|
||||
max_g_force: z.number().optional(),
|
||||
banner_image_id: z.string().optional(),
|
||||
banner_image_url: z.string().optional(),
|
||||
card_image_id: z.string().optional(),
|
||||
card_image_url: z.string().optional(),
|
||||
images: z.object({
|
||||
uploaded: z.array(z.any()),
|
||||
banner_assignment: z.number().nullable().optional(),
|
||||
card_assignment: z.number().nullable().optional(),
|
||||
}).optional(),
|
||||
images: imageAssignmentSchema,
|
||||
});
|
||||
|
||||
// Company Schema (Manufacturer, Designer, Operator, Property Owner)
|
||||
// ============================================
|
||||
// COMPANY SCHEMA (Manufacturer, Designer, Operator, Property Owner)
|
||||
// ============================================
|
||||
|
||||
export const companyValidationSchema = z.object({
|
||||
name: z.string().trim().min(1, 'Company name is required').max(200, 'Name must be less than 200 characters'),
|
||||
slug: z.string().trim().min(1, 'Slug is required').regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
|
||||
company_type: z.enum(['manufacturer', 'designer', 'operator', 'property_owner']),
|
||||
description: z.string().max(2000, 'Description must be less than 2000 characters').optional(),
|
||||
description: z.string().trim().max(2000, 'Description must be less than 2000 characters').optional().or(z.literal('')),
|
||||
person_type: z.enum(['company', 'individual', 'firm', 'organization']),
|
||||
// Support both founded_date (preferred) and founded_year (legacy)
|
||||
founded_date: z.string().optional(),
|
||||
founded_date: z.string().optional().or(z.literal('')),
|
||||
founded_date_precision: z.enum(['day', 'month', 'year']).optional(),
|
||||
founded_year: z.preprocess(
|
||||
(val) => val === '' || val === null || val === undefined ? undefined : val,
|
||||
z.coerce.number().int().min(1800).max(currentYear).optional()
|
||||
).optional().nullable(),
|
||||
headquarters_location: z.string().max(200, 'Location must be less than 200 characters').optional(),
|
||||
website_url: z.string().optional().refine((val) => {
|
||||
(val) => val === '' || val === null || val === undefined ? undefined : Number(val),
|
||||
z.number().int().min(1800, 'Founded year must be after 1800').max(currentYear, `Founded year cannot be after ${currentYear}`).optional()
|
||||
),
|
||||
headquarters_location: z.string().trim().max(200, 'Location must be less than 200 characters').optional().or(z.literal('')),
|
||||
website_url: z.string().trim().optional().or(z.literal('')).refine((val) => {
|
||||
if (!val || val === '') return true;
|
||||
return z.string().url().safeParse(val).success;
|
||||
}, 'Invalid URL format'),
|
||||
@@ -117,37 +157,42 @@ export const companyValidationSchema = z.object({
|
||||
banner_image_url: z.string().optional(),
|
||||
card_image_id: z.string().optional(),
|
||||
card_image_url: z.string().optional(),
|
||||
images: z.object({
|
||||
uploaded: z.array(z.any()),
|
||||
banner_assignment: z.number().nullable().optional(),
|
||||
card_assignment: z.number().nullable().optional(),
|
||||
}).optional(),
|
||||
images: imageAssignmentSchema,
|
||||
});
|
||||
|
||||
// Ride Model Schema
|
||||
// ============================================
|
||||
// RIDE MODEL SCHEMA
|
||||
// ============================================
|
||||
|
||||
export const rideModelValidationSchema = z.object({
|
||||
name: z.string().min(1, 'Model name is required').max(200, 'Name must be less than 200 characters'),
|
||||
slug: z.string().min(1, 'Slug is required').regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
|
||||
name: z.string().trim().min(1, 'Model name is required').max(200, 'Name must be less than 200 characters'),
|
||||
slug: z.string().trim().min(1, 'Slug is required').regex(/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens'),
|
||||
category: z.string().min(1, 'Category is required'),
|
||||
ride_type: z.string().min(1, 'Ride type is required').max(100, 'Ride type must be less than 100 characters'),
|
||||
description: z.string().max(2000, 'Description must be less than 2000 characters').optional(),
|
||||
ride_type: z.string().trim().min(1, 'Ride type is required').max(100, 'Ride type must be less than 100 characters'),
|
||||
description: z.string().trim().max(2000, 'Description must be less than 2000 characters').optional().or(z.literal('')),
|
||||
manufacturer_id: z.string().uuid('Invalid manufacturer ID').optional(),
|
||||
});
|
||||
|
||||
// Photo Schema
|
||||
// ============================================
|
||||
// PHOTO SCHEMA
|
||||
// ============================================
|
||||
|
||||
export const photoValidationSchema = z.object({
|
||||
cloudflare_image_id: z.string().min(1, 'Image ID is required'),
|
||||
cloudflare_image_url: z.string().url('Invalid image URL'),
|
||||
entity_type: z.string().min(1, 'Entity type is required'),
|
||||
entity_id: z.string().uuid('Invalid entity ID'),
|
||||
caption: z.string().max(500, 'Caption must be less than 500 characters').optional(),
|
||||
photographer_credit: z.string().max(200, 'Credit must be less than 200 characters').optional(),
|
||||
caption: z.string().trim().max(500, 'Caption must be less than 500 characters').optional().or(z.literal('')),
|
||||
photographer_credit: z.string().trim().max(200, 'Credit must be less than 200 characters').optional().or(z.literal('')),
|
||||
});
|
||||
|
||||
// Milestone/Timeline Event Schema
|
||||
// ============================================
|
||||
// MILESTONE/TIMELINE EVENT SCHEMA
|
||||
// ============================================
|
||||
|
||||
export const milestoneValidationSchema = z.object({
|
||||
title: z.string().min(1, 'Event title is required').max(200, 'Title must be less than 200 characters'),
|
||||
description: z.string().max(2000, 'Description must be less than 2000 characters').optional(),
|
||||
title: z.string().trim().min(1, 'Event title is required').max(200, 'Title must be less than 200 characters'),
|
||||
description: z.string().trim().max(2000, 'Description must be less than 2000 characters').optional().or(z.literal('')),
|
||||
event_type: z.string().min(1, 'Event type is required'),
|
||||
event_date: z.string().min(1, 'Event date is required'),
|
||||
event_date_precision: z.enum(['day', 'month', 'year']).optional(),
|
||||
@@ -207,7 +252,7 @@ export interface ValidationResult {
|
||||
*/
|
||||
export async function validateEntityData(
|
||||
entityType: keyof typeof entitySchemas,
|
||||
data: any
|
||||
data: unknown
|
||||
): Promise<ValidationResult> {
|
||||
const schema = entitySchemas[entityType];
|
||||
|
||||
@@ -240,7 +285,8 @@ export async function validateEntityData(
|
||||
}
|
||||
|
||||
// Add warnings for optional but recommended fields
|
||||
if (data.description && data.description.length < 50) {
|
||||
const validData = data as Record<string, unknown>;
|
||||
if (validData.description && typeof validData.description === 'string' && validData.description.length < 50) {
|
||||
warnings.push({
|
||||
field: 'description',
|
||||
message: 'Description is short. Recommended: 50+ characters',
|
||||
@@ -249,7 +295,7 @@ export async function validateEntityData(
|
||||
}
|
||||
|
||||
if (entityType === 'park' || entityType === 'ride') {
|
||||
if (!data.description || data.description.trim() === '') {
|
||||
if (!validData.description || (typeof validData.description === 'string' && validData.description.trim() === '')) {
|
||||
warnings.push({
|
||||
field: 'description',
|
||||
message: 'No description provided. Adding a description improves content quality',
|
||||
@@ -259,8 +305,12 @@ export async function validateEntityData(
|
||||
}
|
||||
|
||||
// Check slug uniqueness (async)
|
||||
if (data.slug) {
|
||||
const isSlugUnique = await checkSlugUniqueness(entityType, data.slug, data.id);
|
||||
if (validData.slug && typeof validData.slug === 'string') {
|
||||
const isSlugUnique = await checkSlugUniqueness(
|
||||
entityType,
|
||||
validData.slug,
|
||||
typeof validData.id === 'string' ? validData.id : undefined
|
||||
);
|
||||
if (!isSlugUnique) {
|
||||
blockingErrors.push({
|
||||
field: 'slug',
|
||||
@@ -313,7 +363,7 @@ async function checkSlugUniqueness(
|
||||
}
|
||||
|
||||
// If excludeId provided and matches, it's the same entity (editing)
|
||||
if (excludeId && data[0] && (data[0] as any).id === excludeId) {
|
||||
if (excludeId && data[0] && ((data[0] as unknown) as { id: string }).id === excludeId) {
|
||||
console.log(`Slug "${slug}" matches current entity (editing mode)`);
|
||||
return true;
|
||||
}
|
||||
@@ -354,7 +404,7 @@ function getTableNameFromEntityType(entityType: keyof typeof entitySchemas): str
|
||||
* Batch validate multiple items
|
||||
*/
|
||||
export async function validateMultipleItems(
|
||||
items: Array<{ item_type: string; item_data: any; id?: string }>
|
||||
items: Array<{ item_type: string; item_data: unknown; id?: string }>
|
||||
): Promise<Map<string, ValidationResult>> {
|
||||
const results = new Map<string, ValidationResult>();
|
||||
|
||||
@@ -362,9 +412,13 @@ export async function validateMultipleItems(
|
||||
items.map(async (item) => {
|
||||
const result = await validateEntityData(
|
||||
item.item_type as keyof typeof entitySchemas,
|
||||
{ ...item.item_data, id: item.id }
|
||||
{ ...(item.item_data as object), id: item.id }
|
||||
);
|
||||
const validData = item.item_data as Record<string, unknown>;
|
||||
results.set(
|
||||
item.id || (typeof validData.slug === 'string' ? validData.slug : ''),
|
||||
result
|
||||
);
|
||||
results.set(item.id || item.item_data.slug || '', result);
|
||||
})
|
||||
);
|
||||
|
||||
|
||||
240
src/lib/runtimeValidation.ts
Normal file
240
src/lib/runtimeValidation.ts
Normal file
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* Runtime Type Validation
|
||||
*
|
||||
* Validates data from Supabase queries at runtime to ensure type safety.
|
||||
* Uses Zod schemas to parse and validate database responses.
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import type { Park, Ride, Company, RideModel } from '@/types/database';
|
||||
|
||||
// ============================================
|
||||
// RUNTIME SCHEMAS (Mirror Database Types)
|
||||
// ============================================
|
||||
|
||||
export const parkRuntimeSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string(),
|
||||
slug: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
park_type: z.string(),
|
||||
status: z.string(),
|
||||
opening_date: z.string().nullable().optional(),
|
||||
opening_date_precision: z.string().nullable().optional(),
|
||||
closing_date: z.string().nullable().optional(),
|
||||
closing_date_precision: z.string().nullable().optional(),
|
||||
location_id: z.string().uuid().nullable().optional(),
|
||||
operator_id: z.string().uuid().nullable().optional(),
|
||||
property_owner_id: z.string().uuid().nullable().optional(),
|
||||
website_url: z.string().nullable().optional(),
|
||||
phone: z.string().nullable().optional(),
|
||||
email: z.string().nullable().optional(),
|
||||
banner_image_url: z.string().nullable().optional(),
|
||||
banner_image_id: z.string().nullable().optional(),
|
||||
card_image_url: z.string().nullable().optional(),
|
||||
card_image_id: z.string().nullable().optional(),
|
||||
ride_count: z.number().optional(),
|
||||
coaster_count: z.number().optional(),
|
||||
average_rating: z.number().nullable().optional(),
|
||||
review_count: z.number().optional(),
|
||||
view_count_7d: z.number().optional(),
|
||||
view_count_30d: z.number().optional(),
|
||||
view_count_all: z.number().optional(),
|
||||
created_at: z.string().optional(),
|
||||
updated_at: z.string().optional(),
|
||||
}).passthrough(); // Allow additional fields from joins
|
||||
|
||||
export const rideRuntimeSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string(),
|
||||
slug: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
category: z.string(),
|
||||
ride_sub_type: z.string().nullable().optional(),
|
||||
status: z.string(),
|
||||
park_id: z.string().uuid().nullable().optional(),
|
||||
manufacturer_id: z.string().uuid().nullable().optional(),
|
||||
designer_id: z.string().uuid().nullable().optional(),
|
||||
ride_model_id: z.string().uuid().nullable().optional(),
|
||||
opening_date: z.string().nullable().optional(),
|
||||
opening_date_precision: z.string().nullable().optional(),
|
||||
closing_date: z.string().nullable().optional(),
|
||||
closing_date_precision: z.string().nullable().optional(),
|
||||
height_requirement_cm: z.number().nullable().optional(),
|
||||
age_requirement: z.number().nullable().optional(),
|
||||
max_speed_kmh: z.number().nullable().optional(),
|
||||
duration_seconds: z.number().nullable().optional(),
|
||||
capacity_per_hour: z.number().nullable().optional(),
|
||||
gforce_max: z.number().nullable().optional(),
|
||||
inversions_count: z.number().nullable().optional(),
|
||||
length_meters: z.number().nullable().optional(),
|
||||
height_meters: z.number().nullable().optional(),
|
||||
drop_meters: z.number().nullable().optional(),
|
||||
angle_degrees: z.number().nullable().optional(),
|
||||
coaster_type: z.string().nullable().optional(),
|
||||
seating_type: z.string().nullable().optional(),
|
||||
intensity_level: z.string().nullable().optional(),
|
||||
former_names: z.array(z.unknown()).nullable().optional(),
|
||||
banner_image_url: z.string().nullable().optional(),
|
||||
banner_image_id: z.string().nullable().optional(),
|
||||
card_image_url: z.string().nullable().optional(),
|
||||
card_image_id: z.string().nullable().optional(),
|
||||
average_rating: z.number().nullable().optional(),
|
||||
review_count: z.number().optional(),
|
||||
view_count_7d: z.number().optional(),
|
||||
view_count_30d: z.number().optional(),
|
||||
view_count_all: z.number().optional(),
|
||||
created_at: z.string().optional(),
|
||||
updated_at: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const companyRuntimeSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string(),
|
||||
slug: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
company_type: z.string(),
|
||||
person_type: z.string().nullable().optional(),
|
||||
founded_year: z.number().nullable().optional(),
|
||||
founded_date: z.string().nullable().optional(),
|
||||
founded_date_precision: z.string().nullable().optional(),
|
||||
headquarters_location: z.string().nullable().optional(),
|
||||
website_url: z.string().nullable().optional(),
|
||||
logo_url: z.string().nullable().optional(),
|
||||
banner_image_url: z.string().nullable().optional(),
|
||||
banner_image_id: z.string().nullable().optional(),
|
||||
card_image_url: z.string().nullable().optional(),
|
||||
card_image_id: z.string().nullable().optional(),
|
||||
average_rating: z.number().nullable().optional(),
|
||||
review_count: z.number().optional(),
|
||||
view_count_7d: z.number().optional(),
|
||||
view_count_30d: z.number().optional(),
|
||||
view_count_all: z.number().optional(),
|
||||
created_at: z.string().optional(),
|
||||
updated_at: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
export const rideModelRuntimeSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string(),
|
||||
slug: z.string(),
|
||||
manufacturer_id: z.string().uuid().nullable().optional(),
|
||||
category: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
technical_specs: z.array(z.unknown()).nullable().optional(),
|
||||
created_at: z.string().optional(),
|
||||
updated_at: z.string().optional(),
|
||||
}).passthrough();
|
||||
|
||||
// ============================================
|
||||
// VALIDATION HELPERS
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Validate a single park record
|
||||
*/
|
||||
export function validatePark(data: unknown): Park {
|
||||
return parkRuntimeSchema.parse(data) as Park;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an array of park records
|
||||
*/
|
||||
export function validateParks(data: unknown): Park[] {
|
||||
return z.array(parkRuntimeSchema).parse(data) as Park[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely validate parks (returns null on error)
|
||||
*/
|
||||
export function safeValidateParks(data: unknown): Park[] | null {
|
||||
const result = z.array(parkRuntimeSchema).safeParse(data);
|
||||
return result.success ? (result.data as Park[]) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a single ride record
|
||||
*/
|
||||
export function validateRide(data: unknown): Ride {
|
||||
return rideRuntimeSchema.parse(data) as Ride;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an array of ride records
|
||||
*/
|
||||
export function validateRides(data: unknown): Ride[] {
|
||||
return z.array(rideRuntimeSchema).parse(data) as Ride[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely validate rides (returns null on error)
|
||||
*/
|
||||
export function safeValidateRides(data: unknown): Ride[] | null {
|
||||
const result = z.array(rideRuntimeSchema).safeParse(data);
|
||||
return result.success ? (result.data as Ride[]) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a single company record
|
||||
*/
|
||||
export function validateCompany(data: unknown): Company {
|
||||
return companyRuntimeSchema.parse(data) as Company;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an array of company records
|
||||
*/
|
||||
export function validateCompanies(data: unknown): Company[] {
|
||||
return z.array(companyRuntimeSchema).parse(data) as Company[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely validate companies (returns null on error)
|
||||
*/
|
||||
export function safeValidateCompanies(data: unknown): Company[] | null {
|
||||
const result = z.array(companyRuntimeSchema).safeParse(data);
|
||||
return result.success ? (result.data as Company[]) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a single ride model record
|
||||
*/
|
||||
export function validateRideModel(data: unknown): RideModel {
|
||||
return rideModelRuntimeSchema.parse(data) as RideModel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an array of ride model records
|
||||
*/
|
||||
export function validateRideModels(data: unknown): RideModel[] {
|
||||
return z.array(rideModelRuntimeSchema).parse(data) as RideModel[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely validate ride models (returns null on error)
|
||||
*/
|
||||
export function safeValidateRideModels(data: unknown): RideModel[] | null {
|
||||
const result = z.array(rideModelRuntimeSchema).safeParse(data);
|
||||
return result.success ? (result.data as RideModel[]) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic validator for any entity type
|
||||
*/
|
||||
export function validateEntity<T>(
|
||||
data: unknown,
|
||||
schema: z.ZodSchema<T>
|
||||
): T {
|
||||
return schema.parse(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Safe generic validator (returns null on error)
|
||||
*/
|
||||
export function safeValidateEntity<T>(
|
||||
data: unknown,
|
||||
schema: z.ZodSchema<T>
|
||||
): T | null {
|
||||
const result = schema.safeParse(data);
|
||||
return result.success ? result.data : null;
|
||||
}
|
||||
Reference in New Issue
Block a user