@@ -1,47 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { readIdentity, writeIdentity } from './identity';
|
||||
|
||||
function createMockStorage(): Storage {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
getItem: (key: string) => store.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => void store.set(key, value),
|
||||
removeItem: (key: string) => void store.delete(key),
|
||||
clear: () => store.clear(),
|
||||
key: () => null,
|
||||
get length() {
|
||||
return store.size;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('identity storage', () => {
|
||||
it('returns null when nothing is stored', () => {
|
||||
expect(readIdentity(createMockStorage())).toBeNull();
|
||||
});
|
||||
|
||||
it('round-trips a written identity', () => {
|
||||
const storage = createMockStorage();
|
||||
writeIdentity(storage, { name: 'Alice' });
|
||||
expect(readIdentity(storage)).toEqual({ name: 'Alice' });
|
||||
});
|
||||
|
||||
it('ignores malformed JSON', () => {
|
||||
const storage = createMockStorage();
|
||||
storage.setItem('stb:identity', '{not json');
|
||||
expect(readIdentity(storage)).toBeNull();
|
||||
});
|
||||
|
||||
it('ignores an empty stored name', () => {
|
||||
const storage = createMockStorage();
|
||||
storage.setItem('stb:identity', JSON.stringify({ name: ' ' }));
|
||||
expect(readIdentity(storage)).toBeNull();
|
||||
});
|
||||
|
||||
it('overwrites a previously stored identity', () => {
|
||||
const storage = createMockStorage();
|
||||
writeIdentity(storage, { name: 'Alice' });
|
||||
writeIdentity(storage, { name: 'Bob' });
|
||||
expect(readIdentity(storage)).toEqual({ name: 'Bob' });
|
||||
});
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
const STORAGE_KEY = 'stb:identity';
|
||||
|
||||
export interface Identity {
|
||||
name: string;
|
||||
}
|
||||
|
||||
type StorageLike = Pick<Storage, 'getItem' | 'setItem'>;
|
||||
|
||||
export function readIdentity(storage: StorageLike): Identity | null {
|
||||
const raw = storage.getItem(STORAGE_KEY);
|
||||
if (!raw) return null;
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (typeof parsed?.name !== 'string' || !parsed.name.trim()) return null;
|
||||
|
||||
return { name: parsed.name };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeIdentity(storage: StorageLike, identity: Identity): void {
|
||||
storage.setItem(STORAGE_KEY, JSON.stringify(identity));
|
||||
}
|
||||
Reference in New Issue
Block a user