Private by default (the prayer team only) or shared with members after a coordinator approves it, with the first name or "Anonymous"; fully anonymous requests when the church allows them (off by default). Coordinators approve, redact (the sender told what changed) or remove (with a reason); anyone on the team can escalate to Pastoral care (email and WhatsApp at once, an Owner or Church admin when nobody has the role): it leaves the shared list and the sender sees nothing different. "I prayed" counts without who, "Answered!" updates, private replies from the team, closing after 30 days (7-90) and deletion 12 months later (prayer-requests-tidy). Every list with a sender is access-logged; messages never carry a request's text; nothing in the heartbeat. Export and delete for a member's requests. Shared helpers: parse (http.ts), accessLog (lib/accessLog.ts). Migration 20261203000000_prayer_requests (checked on PostgreSQL 18: applies, no diff). 78 backend tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
200 lines
12 KiB
TypeScript
200 lines
12 KiB
TypeScript
/**
|
|
* An in-memory stand-in for the Prisma client (from the Website's tests/support/memoryDb.ts): every
|
|
* model the App uses, with the schema's defaults and unique fields, generic `where` matching
|
|
* (equality, in / notIn, gt / gte / lt / lte, not, contains, has, AND / OR), `include` of the
|
|
* relations below and `aggregate` sums. Enough to run the whole app in tests. Each module adds its
|
|
* models' defaults here as it arrives.
|
|
*/
|
|
import crypto from 'node:crypto';
|
|
|
|
type Row = Record<string, unknown>;
|
|
|
|
const DEFAULTS: Record<string, () => Row> = {
|
|
member: () => ({ phone: null, whatsappOptedOut: false, roles: [], lastActiveAt: 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 }),
|
|
prayerCommitment: () => ({ reminder: 'hour1', channel: 'email', note: null, bookedById: null, renewalNoticesSent: 0, renewedAt: null }),
|
|
prayedMark: () => ({ memberId: null }),
|
|
prayerCampaign: () => ({ imageUrl: null, goal: null, targetPerSlot: null, createdById: null }),
|
|
testimony: () => ({ campaignId: null, showName: false, status: 'pending', removedReason: null, moderatedById: null, moderatedAt: null }),
|
|
accessLog: () => ({ targetId: null, metadata: null, ip: null }),
|
|
outboxMessage: () => ({ sentAt: null, failedAt: null, error: null, attempts: 0 }),
|
|
prayerRequest: () => ({ visibility: 'team', showName: false, anonymous: false, moderation: 'none', redactedAt: null, redactionNote: null, removedReason: null, moderatedById: null, moderatedAt: null, escalatedAt: null, escalatedById: null, escalationNote: null, closedAt: null }),
|
|
prayerRequestUpdate: () => ({ authorId: null }),
|
|
};
|
|
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce' };
|
|
/** Unique fields: one field, or several together (`@@unique([a, b])`). */
|
|
const UNIQUE: Record<string, (string | string[])[]> = { session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']], requestPrayer: [['requestId', 'memberId']] };
|
|
const HAS_UPDATED_AT = new Set(['member', 'appSetting', 'productLink', 'prayerCommitment', 'prayerCampaign', 'prayerRequest']);
|
|
/** `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 }>> = {
|
|
member: { sessions: { model: 'session', many: true, key: 'memberId' } },
|
|
prayerRequest: { updates: { model: 'prayerRequestUpdate', many: true, key: 'requestId' }, prayers: { model: 'requestPrayer', many: true, key: 'requestId' } },
|
|
prayerCommitment: { skips: { model: 'prayerSkip', many: true, key: 'commitmentId' }, marks: { model: 'prayedMark', many: true, key: 'commitmentId' } },
|
|
};
|
|
|
|
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 'isEmpty': return Array.isArray(actual) && (actual.length === 0) === x;
|
|
case 'has': return Array.isArray(actual) && actual.map(v).includes(v(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);
|
|
});
|
|
}
|
|
|
|
/** Prisma.DbNull / JsonNull (a nullable Json field set to null) are stored as null, as Postgres does. */
|
|
const nulls = (x: unknown) => (x && typeof x === 'object' && /^(Db|Json)Null$/.test(x.constructor?.name ?? '') ? null : x);
|
|
const clone = <T>(x: T): T => structuredClone(x && typeof x === 'object' && !Array.isArray(x) && !(x instanceof Date) ? Object.fromEntries(Object.entries(x).map(([k, y]) => [k, nulls(y)])) as T : 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 (typeof u === 'string' && 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] ?? []) {
|
|
const fields = typeof u === 'string' ? [u] : u;
|
|
if (fields.some((f) => row[f] == null)) continue;
|
|
if ([...table().values()].some((r) => r[key] !== except && fields.every((f) => v(r[f]) === v(row[f])))) throw prismaError('P2002', `Unique constraint failed on ${name}.${fields.join('_')}`);
|
|
}
|
|
};
|
|
const api = {
|
|
findUnique: async ({ where, select, include }: { where: Row; select?: Row; include?: Row }) => { const r = findWhere(where); return r ? withIncludes(pick(clone(r), select), include) : 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, include }: { where?: Row; orderBy?: Row | Row[]; select?: Row; include?: Row } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? withIncludes(pick(clone(r), select), include) : 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) => {
|
|
const drop = (model: string, field: string) => { for (const [k, r] of tables.get(model) ?? []) if (r[field] === id) tables.get(model)!.delete(k); };
|
|
const unset = (model: string, field: string) => { for (const r of tables.get(model)?.values() ?? []) if (r[field] === id) r[field] = null; };
|
|
if (from === 'member') { drop('session', 'memberId'); drop('testimony', 'memberId'); drop('outboxMessage', 'memberId'); drop('prayerRequest', 'memberId'); unset('prayerCommitment', 'memberId'); }
|
|
if (from === 'prayerCommitment') { drop('prayerSkip', 'commitmentId'); drop('prayedMark', 'commitmentId'); }
|
|
if (from === 'prayerCampaign') unset('testimony', 'campaignId');
|
|
if (from === 'prayerRequest') { drop('prayerRequestUpdate', 'requestId'); drop('requestPrayer', 'requestId'); }
|
|
};
|
|
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);
|
|
},
|
|
});
|
|
}
|