Publish my events: the Website's simple events as crosscode.event/1 (GET /api/feed/v1/events, updatedSince, removals in deleted for 90 days) and a signed event.changed to linked siblings. Show events from: each sibling's feed every 15 minutes and at once on its signed event.changed; read-only copies of only that sibling's events, one bad event skipped, the last good copy kept. Admin: Linked products. church.changed from Accounts refreshes the profile at once. Plan: the video hero, more blocks and more pages move to website@1.1.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
189 lines
11 KiB
TypeScript
189 lines
11 KiB
TypeScript
/**
|
|
* An in-memory stand-in for the Prisma client (from Accounts' tests/support/memoryDb.ts): every
|
|
* model the Website uses, with the schema's defaults and unique fields, generic `where` matching
|
|
* (equality, in / notIn, gt / gte / lt / lte, not, contains, AND / OR), `include` of the relations
|
|
* below and `aggregate` sums. Enough to run the whole app in tests.
|
|
*/
|
|
import crypto from 'node:crypto';
|
|
|
|
type Row = Record<string, unknown>;
|
|
|
|
const DEFAULTS: Record<string, () => Row> = {
|
|
ministry: () => ({ summary: null, body: null, imageId: null, position: 0, archivedAt: null, updatedBy: null }),
|
|
leader: () => ({ role: null, bio: null, photoId: null, position: 0, archivedAt: null, updatedBy: null }),
|
|
messageSeries: () => ({ summary: null, imageId: null }),
|
|
page: () => ({ seoTitle: null, description: null, navLabel: null, inNav: true, position: 0, imageId: null, archivedAt: null, updatedBy: null }),
|
|
section: () => ({ variant: null, position: 0, hidden: false, updatedBy: null }),
|
|
message: () => ({ externalId: null, thumbnailUrl: null, speaker: null, passage: null, notes: null, seriesId: null, hidden: false, publishedAt: null, updatedBy: null }),
|
|
simpleEvent: () => ({ endsAt: null, allDay: false, timezone: 'Africa/Johannesburg', location: null, description: null, imageId: null, link: null, cancelled: false, publishedAt: null, updatedBy: null }),
|
|
mediaAsset: () => ({ width: null, height: null, alt: '', sizes: null, uploadedBy: null }),
|
|
siteVersion: () => ({ note: null }),
|
|
websiteUser: () => ({ ministryId: null, lastSignInAt: null }),
|
|
session: () => ({ sid: null, mfa: false, idToken: null, lastSeenAt: new Date() }),
|
|
productLink: () => ({ connectedById: null, lastSyncError: null, showEvents: true, lastSyncAt: null, lastGoodAt: null }),
|
|
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
|
|
};
|
|
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', feedRemoval: 'eventId' };
|
|
const UNIQUE: Record<string, string[]> = { session: ['tokenHash'], siteVersion: ['number'], page: ['slug'], message: ['slug', 'externalId'], previewLink: ['tokenHash'] };
|
|
const HAS_UPDATED_AT = new Set(['siteDesign', 'page', 'section', 'ministry', 'leader', 'message', 'simpleEvent', 'appSetting', 'productLink']);
|
|
/** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */
|
|
const RELATIONS: Record<string, Record<string, { model: string; many: boolean; key: string }>> = {
|
|
page: { sections: { model: 'section', many: true, key: 'pageId' } },
|
|
message: { series: { model: 'messageSeries', many: false, key: 'seriesId' } },
|
|
};
|
|
|
|
const v = (x: unknown) => (x instanceof Date ? x.getTime() : x);
|
|
|
|
function matchValue(actual: unknown, cond: unknown): boolean {
|
|
if (cond !== null && typeof cond === 'object' && !(cond instanceof Date) && !Array.isArray(cond)) {
|
|
const c = cond as Record<string, unknown>;
|
|
const insensitive = c.mode === 'insensitive';
|
|
return Object.entries(c).every(([op, x]) => {
|
|
switch (op) {
|
|
case 'mode': return true;
|
|
case 'equals': return v(actual) === v(x);
|
|
case 'in': return (x as unknown[]).map(v).includes(v(actual));
|
|
case 'notIn': return !(x as unknown[]).map(v).includes(v(actual));
|
|
case 'gt': return actual != null && (v(actual) as number) > (v(x) as number);
|
|
case 'gte': return actual != null && (v(actual) as number) >= (v(x) as number);
|
|
case 'lt': return actual != null && (v(actual) as number) < (v(x) as number);
|
|
case 'lte': return actual != null && (v(actual) as number) <= (v(x) as number);
|
|
case 'not': return x === null ? actual != null : !matchValue(actual, x);
|
|
case 'contains': return typeof actual === 'string' && (insensitive ? actual.toLowerCase().includes(String(x).toLowerCase()) : actual.includes(String(x)));
|
|
default: throw new Error(`memoryDb: no operator ${op}`);
|
|
}
|
|
});
|
|
}
|
|
return v(actual) === v(cond);
|
|
}
|
|
|
|
export function matches(row: Row, where: Row = {}): boolean {
|
|
return Object.entries(where ?? {}).every(([k, cond]) => {
|
|
if (k === 'AND') return (cond as Row[]).every((w) => matches(row, w));
|
|
if (k === 'OR') return (cond as Row[]).some((w) => matches(row, w));
|
|
if (k === 'NOT') return !matches(row, cond as Row);
|
|
return matchValue(row[k], cond);
|
|
});
|
|
}
|
|
|
|
const clone = <T>(x: T): T => structuredClone(x);
|
|
const pick = (row: Row, select?: Row) => (select ? Object.fromEntries(Object.keys(select).filter((k) => select[k]).map((k) => [k, row[k]])) : row);
|
|
|
|
function order(rows: Row[], orderBy?: Row | Row[]) {
|
|
const list = Array.isArray(orderBy) ? orderBy : orderBy ? [orderBy] : [];
|
|
return [...rows].sort((a, b) => {
|
|
for (const o of list) {
|
|
const [k, dir] = Object.entries(o)[0]!;
|
|
const x = v(a[k]) as number;
|
|
const y = v(b[k]) as number;
|
|
const d = x < y ? -1 : x > y ? 1 : 0;
|
|
if (d) return dir === 'desc' ? -d : d;
|
|
}
|
|
return 0;
|
|
});
|
|
}
|
|
|
|
function prismaError(code: string, message: string) {
|
|
return Object.assign(new Error(message), { code });
|
|
}
|
|
|
|
function model(name: string, tables: Map<string, Map<unknown, Row>>) {
|
|
const key = KEYS[name] ?? 'id';
|
|
const table = () => {
|
|
if (!tables.has(name)) tables.set(name, new Map());
|
|
return tables.get(name)!;
|
|
};
|
|
const findWhere = (where: Row) => {
|
|
if (where && key in where && typeof where[key] !== 'object') return table().get(where[key]) ?? null;
|
|
for (const u of UNIQUE[name] ?? []) if (where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null;
|
|
return [...table().values()].find((r) => matches(r, where)) ?? null;
|
|
};
|
|
const checkUnique = (row: Row, except?: unknown) => {
|
|
for (const u of UNIQUE[name] ?? []) {
|
|
if (row[u] == null) continue;
|
|
if ([...table().values()].some((r) => r[key] !== except && r[u] === row[u])) throw prismaError('P2002', `Unique constraint failed on ${name}.${u}`);
|
|
}
|
|
};
|
|
const api = {
|
|
findUnique: async ({ where, select }: { where: Row; select?: Row }) => { const r = findWhere(where); return r ? pick(clone(r), select) : null; },
|
|
findUniqueOrThrow: async (args: { where: Row; select?: Row }) => { const r = await api.findUnique(args); if (!r) throw prismaError('P2025', `${name} not found`); return r; },
|
|
findFirst: async ({ where, orderBy, select }: { where?: Row; orderBy?: Row | Row[]; select?: Row } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? pick(clone(r), select) : null; },
|
|
findMany: async ({ where, orderBy, take, skip, select, include }: { where?: Row; orderBy?: Row | Row[]; take?: number; skip?: number; select?: Row; include?: Row } = {}) =>
|
|
order([...table().values()].filter((x) => matches(x, where)), orderBy).slice(skip ?? 0, (skip ?? 0) + (take ?? Infinity)).map((r) => withIncludes(pick(clone(r), select), include)),
|
|
aggregate: async ({ where, _sum }: { where?: Row; _sum: Row }) => {
|
|
const rows = [...table().values()].filter((x) => matches(x, where));
|
|
return { _sum: Object.fromEntries(Object.keys(_sum).map((k) => [k, rows.length ? rows.reduce((t, r) => t + Number(r[k] ?? 0), 0) : null])) };
|
|
},
|
|
count: async ({ where }: { where?: Row } = {}) => [...table().values()].filter((x) => matches(x, where)).length,
|
|
create: async ({ data }: { data: Row }) => {
|
|
const now = new Date();
|
|
const row: Row = { ...(DEFAULTS[name]?.() ?? {}), ...(key === 'id' ? { id: crypto.randomUUID() } : {}), createdAt: now, ...(HAS_UPDATED_AT.has(name) ? { updatedAt: now } : {}), ...clone(data) };
|
|
if (table().has(row[key])) throw prismaError('P2002', `Unique constraint failed on ${name}.${key}`);
|
|
checkUnique(row);
|
|
table().set(row[key], row);
|
|
return clone(row);
|
|
},
|
|
update: async ({ where, data }: { where: Row; data: Row }) => {
|
|
const r = findWhere(where);
|
|
if (!r) throw prismaError('P2025', `Record to update not found (${name})`);
|
|
const next = { ...r, ...clone(data), ...(HAS_UPDATED_AT.has(name) ? { updatedAt: new Date() } : {}) };
|
|
checkUnique(next, r[key]);
|
|
table().set(r[key], next);
|
|
return clone(next);
|
|
},
|
|
updateMany: async ({ where, data }: { where?: Row; data: Row }) => {
|
|
let count = 0;
|
|
for (const [k, r] of table()) if (matches(r, where)) { table().set(k, { ...r, ...clone(data) }); count++; }
|
|
return { count };
|
|
},
|
|
upsert: async ({ where, create, update }: { where: Row; create: Row; update: Row }) => {
|
|
const r = findWhere(where);
|
|
return r ? api.update({ where, data: update }) : api.create({ data: create });
|
|
},
|
|
delete: async ({ where }: { where: Row }) => {
|
|
const r = findWhere(where);
|
|
if (!r) throw prismaError('P2025', `Record to delete does not exist (${name})`);
|
|
table().delete(r[key]);
|
|
cascade(name, r[key]);
|
|
return clone(r);
|
|
},
|
|
deleteMany: async ({ where }: { where?: Row } = {}) => {
|
|
let count = 0;
|
|
for (const [k, r] of [...table()]) if (matches(r, where)) { table().delete(k); cascade(name, k); count++; }
|
|
return { count };
|
|
},
|
|
};
|
|
const cascade = (from: string, id: unknown) => {
|
|
if (from === 'page') for (const [k, r] of tables.get('section') ?? []) if (r.pageId === id) tables.get('section')!.delete(k);
|
|
if (from === 'productLink') for (const [k, r] of tables.get('importedEvent') ?? []) if (r.linkId === id) tables.get('importedEvent')!.delete(k);
|
|
};
|
|
const withIncludes = (row: Row, include?: Row) => {
|
|
for (const [rel, on] of Object.entries(include ?? {})) {
|
|
const spec = RELATIONS[name]?.[rel];
|
|
if (!on || !spec) continue;
|
|
const other = [...(tables.get(spec.model)?.values() ?? [])];
|
|
const nested = typeof on === 'object' ? (on as { orderBy?: Row | Row[] }).orderBy : undefined;
|
|
row[rel] = spec.many ? order(other.filter((o) => o[spec.key] === row.id), nested).map(clone) : clone(other.find((o) => o.id === row[spec.key]) ?? null);
|
|
}
|
|
return row;
|
|
};
|
|
return api;
|
|
}
|
|
|
|
export type MemoryDb = Record<string, ReturnType<typeof model>> & { tables: Map<string, Map<unknown, Row>>; $queryRaw: () => Promise<unknown[]>; $disconnect: () => Promise<void> };
|
|
|
|
export function memoryDb(): MemoryDb {
|
|
const tables = new Map<string, Map<unknown, Row>>();
|
|
const models = new Map<string, ReturnType<typeof model>>();
|
|
return new Proxy({} as MemoryDb, {
|
|
get(_t, prop: string) {
|
|
if (prop === 'tables') return tables;
|
|
if (prop === '$queryRaw' || prop === '$queryRawUnsafe') return async () => [{ ok: 1 }];
|
|
if (prop === '$disconnect') return async () => {};
|
|
if (prop === 'then') return undefined;
|
|
if (!models.has(prop)) models.set(prop, model(prop, tables));
|
|
return models.get(prop);
|
|
},
|
|
});
|
|
}
|