/** * A small in-memory stand-in for the Prisma client, enough for the servers / jobs tests: where * filters (equals, in, notIn, not, lt/lte/gt/gte, OR, AND, nested relation-free), include of the * relations listed in RELATIONS, orderBy, take, create / update / upsert / delete / count and * $transaction. Not a database: no constraints beyond what the code under test checks itself. */ const crypto = require('crypto'); // model → relation → [target model, kind, localKey, foreignKey] const RELATIONS = { job: { server: ['server', 'one', 'serverId', 'id'], deployment: ['deployment', 'one', 'deploymentId', 'id'] }, deployment: { server: ['server', 'one', 'serverId', 'id'], customer: ['customer', 'one', 'customerId', 'id'], install: ['install', 'one', 'installId', 'id'], jobs: ['job', 'many', 'id', 'deploymentId'], exports: ['export', 'many', 'id', 'deploymentId'] }, server: { alerts: ['serverAlert', 'many', 'id', 'serverId'], deployments: ['deployment', 'many', 'id', 'serverId'], ports: ['port', 'many', 'id', 'serverId'] }, licence: { install: ['install', 'oneBack', 'id', 'licenceId'] }, install: { deployment: ['deployment', 'oneBack', 'id', 'installId'] }, port: { server: ['server', 'one', 'serverId', 'id'] }, export: { deployment: ['deployment', 'one', 'deploymentId', 'id'] }, }; const KEYS = { port: 'port', setting: 'key' }; const cmp = (a, b) => (a instanceof Date ? a.getTime() : a) - (b instanceof Date ? b.getTime() : b); function matches(row, where = {}) { for (const [k, cond] of Object.entries(where || {})) { if (k === 'OR') { if (!cond.some(c => matches(row, c))) return false; continue; } if (k === 'AND') { if (!cond.every(c => matches(row, c))) return false; continue; } const v = row[k]; if (cond === null) { if (v != null) return false; continue; } if (cond instanceof Date || typeof cond !== 'object') { if (cond instanceof Date ? !(v instanceof Date && v.getTime() === cond.getTime()) : v !== cond) return false; continue; } if ('in' in cond && !cond.in.includes(v)) return false; if ('notIn' in cond && cond.notIn.includes(v)) return false; if ('not' in cond && (cond.not === null ? v == null : v === cond.not)) return false; if ('lt' in cond && !(v != null && cmp(v, cond.lt) < 0)) return false; if ('lte' in cond && !(v != null && cmp(v, cond.lte) <= 0)) return false; if ('gt' in cond && !(v != null && cmp(v, cond.gt) > 0)) return false; if ('gte' in cond && !(v != null && cmp(v, cond.gte) >= 0)) return false; if ('equals' in cond && v !== cond.equals) return false; } return true; } function createFakeDb() { const tables = {}; const t = name => (tables[name] ||= []); const keyOf = name => KEYS[name] || 'id'; function include(name, row, inc) { if (!inc || !row) return row; const out = { ...row }; for (const [rel, spec] of Object.entries(inc)) { if (!spec) continue; const [target, kind, local, foreign] = RELATIONS[name]?.[rel] || []; // A plain field in a `select` (rows are returned whole), or an unknown relation. if (!target) { if (spec === true && rel in row) continue; throw new Error(`fakeDb: no relation ${name}.${rel}`); } const opts = spec === true ? {} : spec; if (kind === 'one') { const r = t(target).find(x => x[foreign] === row[local]) || null; out[rel] = r ? include(target, r, opts.include) : null; } else if (kind === 'oneBack') { const r = t(target).find(x => x[foreign] === row[local]) || null; out[rel] = r ? include(target, r, opts.include) : null; } else { let list = t(target).filter(x => x[foreign] === row[local] && matches(x, opts.where)); list = sort(list, opts.orderBy); if (opts.take) list = list.slice(0, opts.take); out[rel] = list.map(x => include(target, x, opts.include)); } } return out; } function sort(list, orderBy) { if (!orderBy) return list; const orders = Array.isArray(orderBy) ? orderBy : [orderBy]; return [...list].sort((a, b) => { for (const o of orders) { const [k, dir] = Object.entries(o)[0]; const c = a[k] == null ? -1 : b[k] == null ? 1 : typeof a[k] === 'string' ? a[k].localeCompare(b[k]) : cmp(a[k], b[k]); if (c) return dir === 'desc' ? -c : c; } return 0; }); } const defaults = { job: { status: 'queued', scheduled: false, emergency: false, createdAt: () => new Date() }, deployment: { status: 'installing', product: 'events', createdAt: () => new Date() }, server: { mode: 'church', joinedAt: () => new Date() }, serverAlert: { createdAt: () => new Date(), resolvedAt: null }, export: { bytes: 0, extended: false, deletedAt: null, createdAt: () => new Date() }, notice: { createdAt: () => new Date(), updatedAt: () => new Date() }, licence: { status: 'active', product: 'events' }, }; function model(name) { const key = keyOf(name); const withDefaults = data => { const row = { ...data }; for (const [k, v] of Object.entries(defaults[name] || {})) if (row[k] === undefined) row[k] = typeof v === 'function' ? v() : v; if (key === 'id' && !row.id) row.id = crypto.randomUUID(); return row; }; return { findUnique: async ({ where, include: inc, select }) => include(name, t(name).find(r => matches(r, where)) || null, inc || select), findFirst: async ({ where, include: inc, orderBy } = {}) => include(name, sort(t(name).filter(r => matches(r, where)), orderBy)[0] || null, inc), findMany: async ({ where, include: inc, orderBy, take, select } = {}) => { let list = sort(t(name).filter(r => matches(r, where)), orderBy); if (take) list = list.slice(0, take); return list.map(r => include(name, r, inc || select)); }, count: async ({ where } = {}) => t(name).filter(r => matches(r, where)).length, create: async ({ data }) => { const row = withDefaults(data); t(name).push(row); return { ...row }; }, update: async ({ where, data }) => { const row = t(name).find(r => matches(r, where)); if (!row) throw Object.assign(new Error(`fakeDb: ${name} not found`), { code: 'P2025' }); Object.assign(row, Object.fromEntries(Object.entries(data).filter(([, v]) => v !== undefined))); return { ...row }; }, updateMany: async ({ where, data }) => { const rows = t(name).filter(r => matches(r, where)); for (const r of rows) Object.assign(r, data); return { count: rows.length }; }, upsert: async ({ where, update, create }) => { const row = t(name).find(r => matches(r, where)); if (row) { Object.assign(row, update); return { ...row }; } const created = withDefaults(create); t(name).push(created); return { ...created }; }, delete: async ({ where }) => { const i = t(name).findIndex(r => matches(r, where)); const [r] = tables[name].splice(i, 1); return r; }, deleteMany: async ({ where } = {}) => { const before = t(name).length; tables[name] = t(name).filter(r => !matches(r, where)); return { count: before - tables[name].length }; }, groupBy: async () => [], }; } const db = new Proxy({ tables }, { get(target, prop) { if (prop === 'tables') return tables; if (prop === '$transaction') return async fn => (typeof fn === 'function' ? fn(db) : Promise.all(fn)); if (prop === '$executeRaw' || prop === '$executeRawUnsafe') return async () => 0; if (typeof prop !== 'string' || prop.startsWith('_') || prop === 'then') return undefined; return (target[prop] ||= model(prop)); }, }); return db; } module.exports = { createFakeDb, matches };