97 lines
2.7 KiB
TypeScript
97 lines
2.7 KiB
TypeScript
// Сервис для хранения данных в localStorage
|
|
|
|
import type { Story, GameSession } from "../types";
|
|
|
|
const STORIES_KEY = "resekai_stories";
|
|
const SESSIONS_KEY = "resekai_sessions";
|
|
|
|
// Истории
|
|
export function getStories(): Story[] {
|
|
const data = localStorage.getItem(STORIES_KEY);
|
|
if (!data) return [];
|
|
|
|
const stories = JSON.parse(data);
|
|
return stories.map((s: Story) => ({
|
|
...s,
|
|
createdAt: new Date(s.createdAt),
|
|
updatedAt: new Date(s.updatedAt),
|
|
}));
|
|
}
|
|
|
|
export function getStoryById(id: string): Story | undefined {
|
|
const stories = getStories();
|
|
return stories.find((s) => s.id === id);
|
|
}
|
|
|
|
export function saveStory(story: Story): void {
|
|
const stories = getStories();
|
|
const index = stories.findIndex((s) => s.id === story.id);
|
|
|
|
if (index >= 0) {
|
|
stories[index] = story;
|
|
} else {
|
|
stories.push(story);
|
|
}
|
|
|
|
localStorage.setItem(STORIES_KEY, JSON.stringify(stories));
|
|
}
|
|
|
|
export function deleteStory(id: string): void {
|
|
const stories = getStories().filter((s) => s.id !== id);
|
|
localStorage.setItem(STORIES_KEY, JSON.stringify(stories));
|
|
|
|
// Удаляем связанные сессии
|
|
const sessions = getSessions().filter((s) => s.storyId !== id);
|
|
localStorage.setItem(SESSIONS_KEY, JSON.stringify(sessions));
|
|
}
|
|
|
|
// Игровые сессии
|
|
export function getSessions(): GameSession[] {
|
|
const data = localStorage.getItem(SESSIONS_KEY);
|
|
if (!data) return [];
|
|
|
|
const sessions = JSON.parse(data);
|
|
return sessions.map((s: GameSession) => ({
|
|
...s,
|
|
createdAt: s.createdAt ? new Date(s.createdAt) : new Date(),
|
|
updatedAt: s.updatedAt ? new Date(s.updatedAt) : new Date(),
|
|
messages: s.messages.map((m) => ({
|
|
...m,
|
|
timestamp: new Date(m.timestamp),
|
|
})),
|
|
}));
|
|
}
|
|
|
|
export function getSessionByStoryId(storyId: string): GameSession | undefined {
|
|
const sessions = getSessions();
|
|
return sessions.find((s) => s.storyId === storyId);
|
|
}
|
|
|
|
export function getSessionById(id: string): GameSession | undefined {
|
|
const sessions = getSessions();
|
|
return sessions.find((s) => s.id === id);
|
|
}
|
|
|
|
export function saveSession(session: GameSession): void {
|
|
const sessions = getSessions();
|
|
const index = sessions.findIndex((s) => s.id === session.id);
|
|
|
|
if (index >= 0) {
|
|
sessions[index] = session;
|
|
} else {
|
|
sessions.push(session);
|
|
}
|
|
|
|
localStorage.setItem(SESSIONS_KEY, JSON.stringify(sessions));
|
|
}
|
|
|
|
export function deleteSession(id: string): void {
|
|
const sessions = getSessions().filter((s) => s.id !== id);
|
|
localStorage.setItem(SESSIONS_KEY, JSON.stringify(sessions));
|
|
}
|
|
|
|
// Генерация ID
|
|
export function generateId(): string {
|
|
return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
}
|