Files
homebrewery-oidc/server/storage/contract/brews.contract.js
T
dev-bot BotandClaude Sonnet 5.5 a55c403527 feat(storage): Repository-Schicht für Brews/Notifications, PostgreSQL-18-Backend (Kysely) und Contract-Suite
HB_DB_DRIVER=mongo|postgres, versionierte Migrationen beim Start, Mongo-Backend ruft unverändert die Upstream-Modelle.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 10:16:55 +00:00

295 lines
14 KiB
JavaScript

// Gemeinsame Contract-Suite für BrewRepository und NotificationRepository (ADR 0002 §5).
// Aufruf: runBrewRepositoryContract(async ()=>({ brews, cleanup }))
const sample = (over = {})=>({
title : 'Mein Brew',
text : '# Hallo\n\nText mit Ümläut und 🎲',
description : 'Beschreibung',
tags : ['fun'],
authors : ['alice'],
renderer : 'V3',
published : true,
...over
});
export const runBrewRepositoryContract = (createBrews)=>{
let brews;
let cleanup;
beforeAll(async ()=>{ ({ brews, cleanup } = await createBrews()); });
afterAll(async ()=>{ await cleanup?.(); });
describe('create / find', ()=>{
test('create vergibt id, editId, shareId und liefert entpackten Text', async ()=>{
const b = await brews.create(sample());
expect(b.id).toEqual(expect.any(String));
expect(b.editId).toHaveLength(12);
expect(b.shareId).toHaveLength(12);
expect(b.text).toBe(sample().text);
expect(b.textBin).toBeUndefined();
expect(b._id).toBeUndefined();
expect(b).toMatchObject({ title: 'Mein Brew', authors: ['alice'], published: true, views: 0, version: 1, lang: 'en' });
expect(b.constructor).toBe(Object);
});
test('findByEditId / findByShareId / findByEditOrShareId', async ()=>{
const b = await brews.create(sample({ title: 'Finde mich' }));
expect((await brews.findByEditId(b.editId)).title).toBe('Finde mich');
expect((await brews.findByShareId(b.shareId)).text).toBe(sample().text);
expect((await brews.findByEditOrShareId(b.editId)).id).toBe(b.id);
expect((await brews.findByEditOrShareId(b.shareId)).id).toBe(b.id);
// Vertauschte IDs finden nichts
expect(await brews.findByEditId(b.shareId)).toBeNull();
expect(await brews.findByShareId(b.editId)).toBeNull();
});
test('unbekannte ID liefert null', async ()=>{
expect(await brews.findByEditId('gibtsnicht12')).toBeNull();
expect(await brews.findByShareId('gibtsnicht12')).toBeNull();
expect(await brews.findByEditOrShareId('gibtsnicht12')).toBeNull();
});
test('fields beschränkt das Ergebnis', async ()=>{
const b = await brews.create(sample());
const r = await brews.findByShareId(b.shareId, { fields: ['title', 'authors'] });
expect(r).toMatchObject({ title: 'Mein Brew', authors: ['alice'] });
expect(r.description).toBeUndefined();
});
test('shareId und editId sind eindeutig', async ()=>{
const b = await brews.create(sample());
await expect(brews.create(sample({ shareId: b.shareId }))).rejects.toBeDefined();
await expect(brews.create(sample({ editId: b.editId }))).rejects.toBeDefined();
});
test('vorgegebene Ids werden übernommen; Stub (text undefined) bleibt ohne Text', async ()=>{
const b = await brews.create(sample({ shareId: 'fixshare0001', editId: 'fixedit00001', text: undefined, googleId: 'g-1' }));
expect(b).toMatchObject({ shareId: 'fixshare0001', editId: 'fixedit00001', googleId: 'g-1' });
const r = await brews.findByShareId('fixshare0001');
expect(r.googleId).toBe('g-1');
expect(r.text ?? '').toBe('');
});
test('Tags als String werden zum Array', async ()=>{
const b = await brews.create(sample({ tags: 'einzel' }));
expect(b.tags).toEqual(['einzel']);
});
});
describe('update / delete', ()=>{
test('update überschreibt Felder und behält Ids', async ()=>{
const b = await brews.create(sample());
const u = await brews.update({ ...b, title: 'Neu', text: 'neuer Text', version: 2, tags: ['x'], authors: ['alice', 'bob'] });
expect(u).toMatchObject({ id: b.id, editId: b.editId, shareId: b.shareId, title: 'Neu', text: 'neuer Text', version: 2, tags: ['x'], authors: ['alice', 'bob'] });
const r = await brews.findByEditId(b.editId);
expect(r).toMatchObject({ title: 'Neu', text: 'neuer Text', version: 2, authors: ['alice', 'bob'] });
});
test('update entfernt googleId, wenn undefined', async ()=>{
const b = await brews.create(sample({ googleId: 'g-2' }));
await brews.update({ ...b, googleId: undefined });
expect((await brews.findByShareId(b.shareId)).googleId).toBeUndefined();
});
test('update mit unbekannter id liefert null', async ()=>{
const b = await brews.create(sample());
await brews.deleteById(b.id);
expect(await brews.update({ ...b, title: 'weg' })).toBeNull();
});
test('deleteById / deleteByEditId', async ()=>{
const a = await brews.create(sample());
const b = await brews.create(sample());
expect(await brews.deleteById(a.id)).toBe(true);
expect(await brews.deleteById(a.id)).toBe(false);
expect(await brews.findByShareId(a.shareId)).toBeNull();
expect(await brews.deleteByEditId(b.editId)).toBe(true);
expect(await brews.findByShareId(b.shareId)).toBeNull();
});
});
describe('Listen und Zähler', ()=>{
const author = `autor_${Math.random().toString(36).slice(2, 8)}`;
beforeAll(async ()=>{
await brews.create(sample({ title: 'pub', authors: [author], published: true }));
await brews.create(sample({ title: 'priv', authors: [author], published: false }));
await brews.create(sample({ title: 'theme', authors: [author, 'zweiter'], published: false, tags: ['meta:theme'] }));
await brews.create(sample({ title: 'google', authors: [author], published: true, googleId: 'g-3', text: undefined }));
});
test('listByAuthor: nur veröffentlichte, mit includeUnpublished alle', async ()=>{
expect((await brews.listByAuthor(author)).map((b)=>b.title).sort()).toEqual(['google', 'pub']);
expect((await brews.listByAuthor(author, { includeUnpublished: true })).map((b)=>b.title).sort()).toEqual(['google', 'priv', 'pub', 'theme']);
});
test('listByAuthor: tagsAny und fields', async ()=>{
const r = await brews.listByAuthor(author, { includeUnpublished: true, tagsAny: ['meta:theme', 'meta:Theme'], fields: ['title', 'shareId'] });
expect(r).toHaveLength(1);
expect(r[0]).toMatchObject({ title: 'theme', shareId: expect.any(String) });
expect(r[0].description).toBeUndefined();
});
test('listByAuthor ohne Treffer: leeres Array', async ()=>{
expect(await brews.listByAuthor('niemand_xyz', { includeUnpublished: true })).toEqual([]);
});
test('countByAuthor zählt nur Brews ohne Google-Ablage', async ()=>{
expect(await brews.countByAuthor(author, { storage: 'homebrewery' })).toBe(3);
});
test('existsAuthor', async ()=>{
expect(await brews.existsAuthor(author)).toBe(true);
expect(await brews.existsAuthor('niemand_xyz')).toBe(false);
});
test('renameAuthor ändert nur authors[] und lässt andere Namen stehen', async ()=>{
const old = `alt_${Math.random().toString(36).slice(2, 8)}`;
const b = await brews.create(sample({ authors: ['x1', old, 'x2'] }));
const other = await brews.create(sample({ authors: ['x1'] }));
await brews.renameAuthor(old, 'neu_name');
expect((await brews.findByShareId(b.shareId)).authors).toEqual(['x1', 'neu_name', 'x2']);
expect((await brews.findByShareId(other.shareId)).authors).toEqual(['x1']);
expect(await brews.existsAuthor(old)).toBe(false);
});
});
describe('Views', ()=>{
test('incrementViews zählt hoch und setzt lastViewed', async ()=>{
const b = await brews.create(sample());
const before = new Date(b.lastViewed);
await new Promise((r)=>setTimeout(r, 20));
const r1 = await brews.incrementViews(b.shareId);
const r2 = await brews.incrementViews(b.shareId);
expect(r1.views).toBe(1);
expect(r2.views).toBe(2);
expect(new Date(r2.lastViewed).getTime()).toBeGreaterThan(before.getTime());
expect((await brews.findByShareId(b.shareId)).views).toBe(2);
});
});
describe('Vault-Suche', ()=>{
const tag = `vt${Math.random().toString(36).slice(2, 8)}`;
const author = `va_${tag}`;
beforeAll(async ()=>{
await brews.create(sample({ title: `${tag} Alpha Drache`, authors: [author], renderer: 'V3' }));
await brews.create(sample({ title: `${tag} Beta Zwerg`, authors: [author], renderer: 'legacy' }));
await brews.create(sample({ title: `${tag} Gamma Elf`, authors: [author], renderer: 'V3' }));
await brews.create(sample({ title: `${tag} Delta geheim`, authors: [author], renderer: 'V3', published: false }));
});
test('nach Autor, nur veröffentlicht, mit Gesamtzahl', async ()=>{
const r = await brews.searchPublished({ author, sort: 'title', dir: 'asc', skip: 0, limit: 10, withTotal: true });
expect(r.total).toBe(3);
expect(r.brews.map((b)=>b.title)).toEqual([`${tag} Alpha Drache`, `${tag} Beta Zwerg`, `${tag} Gamma Elf`]);
expect(r.brews[0].editId).toBeUndefined();
expect(r.brews[0].text).toBeUndefined();
});
test('Sortierung absteigend und Paging', async ()=>{
const p1 = await brews.searchPublished({ author, sort: 'title', dir: 'desc', skip: 0, limit: 2 });
const p2 = await brews.searchPublished({ author, sort: 'title', dir: 'desc', skip: 2, limit: 2 });
expect(p1.brews.map((b)=>b.title)).toEqual([`${tag} Gamma Elf`, `${tag} Beta Zwerg`]);
expect(p2.brews.map((b)=>b.title)).toEqual([`${tag} Alpha Drache`]);
expect(p1.total).toBeUndefined();
});
test('Renderer-Filter', async ()=>{
const legacy = await brews.searchPublished({ author, renderer: 'legacy', limit: 10, withTotal: true });
expect(legacy.brews.map((b)=>b.title)).toEqual([`${tag} Beta Zwerg`]);
expect(legacy.total).toBe(1);
const v3 = await brews.searchPublished({ author, renderer: 'V3', limit: 10, withTotal: true });
expect(v3.total).toBe(2);
});
test('Volltext auf dem Titel (einzelnes Wort, nur veröffentlichte)', async ()=>{
const all = await brews.searchPublished({ title: tag, limit: 10, withTotal: true });
expect(all.total).toBe(3);
expect(all.brews.map((b)=>b.title).sort()).toEqual([`${tag} Alpha Drache`, `${tag} Beta Zwerg`, `${tag} Gamma Elf`]);
const one = await brews.searchPublished({ title: 'Zwerg', author, limit: 10, withTotal: true });
expect(one.brews.map((b)=>b.title)).toEqual([`${tag} Beta Zwerg`]);
expect(one.total).toBe(1);
});
test('nur Gesamtzahl (limit 0) und unbekanntes Sortierfeld fällt auf Titel zurück', async ()=>{
const r = await brews.searchPublished({ author, limit: 0, withTotal: true });
expect(r).toEqual({ brews: [], total: 3 });
const s = await brews.searchPublished({ author, sort: '$where; DROP', limit: 10 });
expect(s.brews).toHaveLength(3);
});
});
describe('Admin: Zähler und Sperren', ()=>{
test('countAll / countPublished', async ()=>{
const all = await brews.countAll();
const pub = await brews.countPublished();
await brews.create(sample({ published: false }));
await brews.create(sample({ published: true }));
expect(await brews.countAll()).toBe(all + 2);
expect(await brews.countPublished()).toBe(pub + 1);
});
test('Sperre setzen, überschreiben, Review anfordern, entfernen', async ()=>{
const b = await brews.create(sample({ title: 'Gesperrt' }));
const lockedBefore = await brews.countLocked();
const lock = { code: 999, editMessage: 'edit', shareMessage: 'share', applied: new Date() };
expect((await brews.setLock('nichtda12345', lock)).result).toBe('not-found');
expect((await brews.setLock(b.shareId, lock)).result).toBe('locked');
expect(await brews.countLocked()).toBe(lockedBefore + 1);
expect((await brews.setLock(b.shareId, lock)).result).toBe('already-locked');
expect((await brews.setLock(b.shareId, { ...lock, code: 1 }, { overwrite: true })).result).toBe('locked');
expect((await brews.findByShareId(b.shareId)).lock).toMatchObject({ code: 1, editMessage: 'edit' });
const listed = (await brews.listLocked()).find((l)=>l.shareId === b.shareId);
expect(listed).toMatchObject({ title: 'Gesperrt', editId: b.editId, lock: { code: 1 } });
expect((await brews.requestReview('nichtda12345')).result).toBe('not-found');
expect((await brews.requestReview(b.shareId)).result).toBe('requested');
expect((await brews.requestReview(b.shareId)).result).toBe('already-requested');
expect((await brews.listReviewRequests()).map((r)=>r.shareId)).toContain(b.shareId);
expect((await brews.removeReviewRequest(b.shareId)).result).toBe('removed');
expect((await brews.removeReviewRequest(b.shareId)).result).toBe('not-found');
expect((await brews.listReviewRequests()).map((r)=>r.shareId)).not.toContain(b.shareId);
expect((await brews.findByShareId(b.shareId)).lock).toMatchObject({ code: 1 });
expect((await brews.removeLock(b.shareId)).result).toBe('unlocked');
expect((await brews.removeLock(b.shareId)).result).toBe('not-locked');
expect((await brews.removeLock('nichtda12345')).result).toBe('not-found');
expect((await brews.findByShareId(b.shareId)).lock).toBeUndefined();
expect(await brews.countLocked()).toBe(lockedBefore);
});
});
};
export const runNotificationRepositoryContract = (createNotifications)=>{
let notifications;
let cleanup;
beforeAll(async ()=>{ ({ notifications, cleanup } = await createNotifications()); });
afterAll(async ()=>{ await cleanup?.(); });
test('create, list, deleteByDismissKey', async ()=>{
const n = await notifications.create({ dismissKey: 'k1', title: 'Titel', text: 'Text' });
expect(n).toMatchObject({ dismissKey: 'k1', title: 'Titel', text: 'Text' });
expect(n.id).toEqual(expect.any(String));
expect((await notifications.list()).map((x)=>x.dismissKey)).toContain('k1');
expect((await notifications.deleteByDismissKey('k1')).dismissKey).toBe('k1');
expect((await notifications.list()).map((x)=>x.dismissKey)).not.toContain('k1');
});
test('Fehlerfälle: ohne Key, doppelter Key, unbekannter Key', async ()=>{
await expect(notifications.create({ title: 'x' })).rejects.toMatchObject({ message: 'Dismiss key is required!' });
await notifications.create({ dismissKey: 'dup' });
await expect(notifications.create({ dismissKey: 'dup' })).rejects.toHaveProperty('message');
await expect(notifications.deleteByDismissKey('gibtsnicht')).rejects.toMatchObject({ message: 'Notification not found' });
await expect(notifications.deleteByDismissKey('')).rejects.toMatchObject({ message: 'Dismiss key is required!' });
});
test('Standardwerte für Titel, Text und Zeiten', async ()=>{
const n = await notifications.create({ dismissKey: 'defaults' });
expect(n).toMatchObject({ title: '', text: '' });
expect(new Date(n.startAt).getTime()).not.toBeNaN();
expect(new Date(n.stopAt).getTime()).not.toBeNaN();
});
};