dv/frontend/src/adapters/gateways/LocalStorageGateway.ts

35 lines
840 B
TypeScript

import { type IStorageGateway } from '@/application/ports/output/IStorageGateway';
export class LocalStorageGateway implements IStorageGateway {
save<T>(key: string, value: T): void {
window.localStorage.setItem(key, JSON.stringify(value));
}
load<T>(key: string): T | null {
const raw = window.localStorage.getItem(key);
if (raw === null) {
return null;
}
try {
return JSON.parse(raw) as T;
} catch {
return null;
}
}
remove(key: string): void {
window.localStorage.removeItem(key);
}
listKeys(prefix: string): string[] {
const keys: string[] = [];
for (let i = 0; i < window.localStorage.length; i++) {
const key = window.localStorage.key(i);
if (key !== null && key.startsWith(prefix)) {
keys.push(key);
}
}
return keys;
}
}