refactor player state persist to zod schema
This commit is contained in:
@@ -1,22 +1,48 @@
|
|||||||
|
import { z } from "zod";
|
||||||
import { browser } from "$app/environment";
|
import { browser } from "$app/environment";
|
||||||
import type { Track } from "./types";
|
import type { Track } from "./types";
|
||||||
|
|
||||||
const STORAGE_KEY = "amqtrain:player:v2";
|
const STORAGE_KEY = "amqtrain:player:v2";
|
||||||
|
|
||||||
export type PersistedState = {
|
export const trackSchema: z.ZodType<Track> = z.object({
|
||||||
queue: Track[];
|
id: z.number(),
|
||||||
currentId: number | null;
|
src: z.string(),
|
||||||
volume: number;
|
title: z.string(),
|
||||||
isMuted: boolean;
|
artist: z.string(),
|
||||||
minimized: boolean;
|
album: z.string(),
|
||||||
};
|
animeName: z.string().optional(),
|
||||||
|
type: z.number(),
|
||||||
|
number: z.number(),
|
||||||
|
fileName: z.string().nullable().optional(),
|
||||||
|
dub: z.boolean(),
|
||||||
|
rebroadcast: z.boolean(),
|
||||||
|
globalPercent: z.number(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const persistedStateSchema = z.object({
|
||||||
|
queue: z.array(trackSchema),
|
||||||
|
currentId: z.number().nullable(),
|
||||||
|
volume: z.number(),
|
||||||
|
isMuted: z.boolean(),
|
||||||
|
minimized: z.boolean(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type PersistedState = z.infer<typeof persistedStateSchema>;
|
||||||
|
|
||||||
export function loadState(): PersistedState | null {
|
export function loadState(): PersistedState | null {
|
||||||
if (!browser) return null;
|
if (!browser) return null;
|
||||||
try {
|
try {
|
||||||
const raw = localStorage.getItem(STORAGE_KEY);
|
const raw = localStorage.getItem(STORAGE_KEY);
|
||||||
if (!raw) return null;
|
if (!raw) return null;
|
||||||
return JSON.parse(raw);
|
|
||||||
|
const parsed = JSON.parse(raw);
|
||||||
|
const result = persistedStateSchema.safeParse(parsed);
|
||||||
|
if (result.success) {
|
||||||
|
return result.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.error("Failed to parse player state", result.error);
|
||||||
|
return null;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Failed to load player state", e);
|
console.error("Failed to load player state", e);
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
Reference in New Issue
Block a user