0 day streak
javascript / intermediate
Snippet

Runtime Schema Validation for Typed Store Data

While Svelte stores manage reactive state, they do not validate data types at runtime by default. Wrapping store update logic with a schema validation tool like Zod guarantees that invalid data payload shapes throw descriptive runtime errors before mutating application state.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { writable } from 'svelte/store';
import { z } from 'zod';
const UserProfileSchema = z.object({
id: z.number().int().positive(),
email: z.string().email(),
roles: z.array(z.string())
});
export function createValidatedUserStore(initialData) {
const { subscribe, set } = writable(null);
function updateSafely(newData) {
const result = UserProfileSchema.safeParse(newData);
if (!result.success) {
throw new TypeError(`Invalid store data structure: ${result.error.message}`);
}
set(result.data);
}
updateSafely(initialData);
return { subscribe, setSafely: updateSafely };
}
svelte
Breakdown
1
const UserProfileSchema = z.object({
Defines a strict object schema requiring specific data types for primitive fields and array members.
2
const result = UserProfileSchema.safeParse(newData);
Parses incoming candidate data at runtime without throwing unhandled exceptions immediately.
3
if (!result.success) { throw new TypeError(`Invalid store data structure: ${result.error.message}`); }
Guards state integrity by throwing a descriptive error if data parsing fails type or structure validation.
4
return { subscribe, setSafely: updateSafely };
Exposes a custom store interface containing the standard subscribe method alongside safe write controls.