Hub 2.6.0: paged lists, job status filters, one-product updates, installs found on servers

- Jobs: Succeeded/Cancelled filters, product, type and church search, paged
  on the server; audit log and alerts paged on the server with search;
  every other list paged.
- Updates: one product at a time with its own releases; an Events update
  pins the church's Accounts (or updates it when the release needs it, or
  installs it first); fixes the requirement check comparing an object.
- A status job adds installs found on a server and ties them to their
  registration; unlinked registered sites trigger one (daily); heartbeats
  tie install records too; the install page shows its registration.
13 new tests (209).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 20:09:31 +02:00
co-authored by Claude Opus 5.5
parent ff176681a7
commit de6a14c229
24 changed files with 641 additions and 130 deletions
+23 -7
View File
@@ -3,6 +3,7 @@
const express = require('express');
const rateLimit = require('express-rate-limit');
const prisma = require('../config/db');
const { pageOf, paged, searchTerm } = require('../utils/paging');
const { protect } = require('../middleware/auth');
const { generateLicence, checkReopen } = require('../utils/licences');
const { PRODUCTS, isProduct, PRODUCT_NAMES } = require('../utils/products');
@@ -288,17 +289,32 @@ router.post('/installs/:id/public-key/clear', wrap(async (req, res) => {
// ─── Alerts and history ───────────────────────────────────────────────────────
// Hub 2.6.0: both paged (?page, ?pageSize) with a search (?q), instead of the last 200 / 300.
router.get('/events', wrap(async (req, res) => {
const where = req.query.open === 'true' ? { resolvedAt: null, level: { not: 'info' } } : {};
const events = await prisma.installEvent.findMany({
where, orderBy: { createdAt: 'desc' }, take: 200,
include: { install: { select: { id: true, name: true, url: true } } },
});
res.json(events);
const and = [];
if (req.query.open === 'true') and.push({ resolvedAt: null, level: { not: 'info' } });
const term = searchTerm(req.query.q);
if (term) {
and.push({ OR: [
{ message: { contains: term, mode: 'insensitive' } },
{ level: { contains: term, mode: 'insensitive' } },
{ install: { name: { contains: term, mode: 'insensitive' } } },
{ install: { url: { contains: term, mode: 'insensitive' } } },
] });
}
const out = await paged(prisma.installEvent, { where: and.length ? { AND: and } : {}, orderBy: { createdAt: 'desc' }, include: { install: { select: { id: true, name: true, url: true } } } }, pageOf(req.query));
res.json({ events: out.rows, total: out.total, page: out.page, pageSize: out.pageSize, pages: out.pages });
}));
router.get('/audit', wrap(async (req, res) => {
res.json(await prisma.auditLog.findMany({ orderBy: { createdAt: 'desc' }, take: 300, include: { actor: { select: { name: true } } } }));
const term = searchTerm(req.query.q);
const where = term ? { OR: [
{ action: { contains: term.replace(/s+/g, '_'), mode: 'insensitive' } },
{ target: { contains: term, mode: 'insensitive' } },
{ actor: { name: { contains: term, mode: 'insensitive' } } },
] } : {};
const out = await paged(prisma.auditLog, { where, orderBy: { createdAt: 'desc' }, include: { actor: { select: { name: true } } } }, pageOf(req.query));
res.json({ entries: out.rows, total: out.total, page: out.page, pageSize: out.pageSize, pages: out.pages });
}));
// ─── Releases ─────────────────────────────────────────────────────────────────
+9
View File
@@ -224,6 +224,15 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
prisma.heartbeat.create({ data: { installId: install.id, receivedAt: now, version, health: health || undefined, stats: stats || undefined } }),
prisma.install.update({ where: { id: install.id }, data: { lastHeartbeatAt: now, version, protocolVersion: body.protocolVersion, health: health || undefined, stats: stats || undefined } }),
]);
// Hub 2.6.0: a site the Hub installed is tied to its registration on every heartbeat too, not
// only when it first registers (so a missed one is mended). A site with no install record at
// all has its server asked what's on it (a status job), which adds it. Neither fails the heartbeat.
try {
const tied = await prisma.deployment.updateMany({ where: { licenceId: install.licenceId, installId: null, status: { notIn: ['removed', 'failed'] } }, data: { installId: install.id } });
if (!tied.count) await require('../utils/jobs').lookForUnlinked(install, now);
} catch (e) {
console.warn('[hub] tying the install record to its site failed:', e?.message || e);
}
if (version && install.version && version !== install.version) {
await prisma.installEvent.create({ data: { installId: install.id, type: 'version', level: 'info', message: `Updated from ${install.version} to ${version}`, resolvedAt: now } });
// An update the church asked for is done once the install runs a newer version.
+8 -6
View File
@@ -11,6 +11,7 @@ const { audit } = require('../utils/audit');
const { getSettings, setSettings } = require('../utils/settings');
const servers = require('../utils/servers');
const jobs = require('../utils/jobs');
const { pageOf, paged } = require('../utils/paging');
const router = express.Router();
router.use(protect);
@@ -216,15 +217,16 @@ router.post('/updates', wrap(async (req, res) => {
// ─── Jobs ─────────────────────────────────────────────────────────────────────
// Hub 2.6.0: paged (?page, ?pageSize), with filters for every status (succeeded too), a job type,
// a product, a server, an install, and a search on the church's short name or domain.
router.get('/jobs', wrap(async (req, res) => {
const where = {};
if (req.query.status) where.status = String(req.query.status);
if (req.query.serverId) where.serverId = String(req.query.serverId);
if (req.query.upcoming === 'true') where.status = { in: ['queued', 'scheduled', 'delivered'] };
const list = await prisma.job.findMany({ where, orderBy: [{ notBefore: 'desc' }], take: 200, include: { server: { select: { id: true, name: true } }, deployment: { select: { id: true, shortName: true, domain: true } } } });
res.json({ jobs: list.map(j => ({ ...j, report: undefined, hasReport: !!j.report })) });
const where = await jobs.listWhere(req.query);
const p = pageOf(req.query);
const out = await paged(prisma.job, { where, orderBy: [{ notBefore: 'desc' }, { createdAt: 'desc' }], include: { server: { select: { id: true, name: true } }, deployment: { select: { id: true, shortName: true, domain: true, product: true } } } }, p);
res.json({ jobs: out.rows.map(j => ({ ...j, report: undefined, hasReport: !!j.report })), total: out.total, page: out.page, pageSize: out.pageSize, pages: out.pages });
}));
router.get('/jobs/:id', wrap(async (req, res) => {
const job = await prisma.job.findUnique({ where: { id: req.params.id }, include: { server: { select: { id: true, name: true } }, deployment: { select: { id: true, shortName: true, domain: true } } } });
if (!job) throw bad('Not found.', 404);
+180 -10
View File
@@ -19,7 +19,8 @@ const { sendMail } = require('./mail');
const { getSettings } = require('./settings');
const { PRODUCT_NAMES } = require('./products');
const { generateLicence } = require('./licences');
const { unmetRequirementsFor } = require('./releases');
const { unmetRequirements, unmetRequirementsFor } = require('./releases');
const { searchTerm } = require('./paging');
const { compareVersions } = require('./alerts');
const servers = require('./servers');
const { missingFor, invalidFor } = require('./envTemplates');
@@ -208,6 +209,9 @@ async function afterJob(job, { exportKey }, now) {
case 'check-ports':
if (!ok) await emailJoshua('Central server check: ports not ready', `${job.message || ''}\n\n${JSON.stringify(job.report?.result || {}, null, 2)}`);
break;
case 'status':
if (ok) await linkFromStatus(job, now);
break;
default:
break;
}
@@ -520,6 +524,109 @@ async function requiredFirst({ release, product, siblings, input, domain, server
return { release: accountsRelease, domain: accountsDomain };
}
/**
* Sites on a server the Hub has no install record for (Hub 2.6.0), from a `status` job's report
* (`crosscode status --json`: each church's products with their domain, ports and checkout):
* added as live installs on that server, tied to the site registered at that domain, with their
* ports on the port list. The customer comes from the registered site, or from the church's other
* products here. A product neither tells is left alone (and named in the job's message).
*/
async function linkFromStatus(job, now = new Date()) {
const churches = Array.isArray(job.report?.result?.churches) ? job.report.result.churches : [];
const linked = [];
const unknown = [];
for (const c of churches) {
if (!c || !SHORT_NAME.test(String(c.church || ''))) continue;
for (const p of Array.isArray(c.products) ? c.products : []) {
const product = String(p?.product || '');
if (!PRODUCT_NAMES[product] || !p.domain) continue;
const known = await prisma.deployment.findFirst({ where: { shortName: c.church, product, status: { notIn: ['removed', 'failed'] } } });
if (known) {
if (known.serverId === job.serverId && !known.installId) await tieToRegistration(known);
continue;
}
const domain = String(p.domain).toLowerCase();
const install = await prisma.install.findFirst({ where: { product, releasedAt: null, url: { contains: `//${domain}` } }, include: { deployment: true } });
const sibling = await prisma.deployment.findFirst({ where: { shortName: c.church, serverId: job.serverId, status: { notIn: ['removed', 'failed'] } } });
const customerId = install?.customerId || sibling?.customerId;
const [api, web] = String(p.ports || '').trim().split(/\s+/).map(n => parseInt(n, 10));
if (!customerId || !(web > 0 && api > 0) || install?.deployment) { unknown.push(`${c.church}/${product}`); continue; }
const version = /@(\d+\.\d+\.\d+.*)$/.exec(String(p.ref || ''))?.[1] || install?.version || null;
const d = await prisma.$transaction(async tx => {
const made = await tx.deployment.create({
data: { serverId: job.serverId, customerId, licenceId: install?.licenceId || null, installId: install?.id || null, product, shortName: c.church, domain, webPort: web, apiPort: api, version, timezone: install?.timezone || sibling?.timezone || null, status: 'live', liveAt: now, adminName: install?.adminContact?.name || sibling?.adminName || null, adminEmail: install?.adminContact?.email || sibling?.adminEmail || null },
});
for (const [port, role] of [[web, 'web'], [api, 'api']]) {
await tx.port.upsert({ where: { port }, update: { serverId: job.serverId, deploymentId: made.id, role, releasedAt: null, note: 'found on the server' }, create: { port, serverId: job.serverId, deploymentId: made.id, role, note: 'found on the server' } });
}
return made;
});
linked.push(`${d.shortName} (${PRODUCT_NAMES[product]}, ${domain})`);
}
}
if (linked.length || unknown.length) {
const text = [linked.length ? `Added: ${linked.join(', ')}.` : '', unknown.length ? `Not added (no registered site or other product of the church tells the customer, or no ports): ${unknown.join(', ')}.` : ''].filter(Boolean).join(' ');
await prisma.job.update({ where: { id: job.id }, data: { message: [job.message, text].filter(Boolean).join(' ') } });
if (linked.length) await emailJoshua(`Installs found on a server`, `${text}\n\n${hubUrl()}/jobs/${job.id}`);
}
return { linked, unknown };
}
/** Ties an install record to the site registered with its licence (if it has registered). */
async function tieToRegistration(d) {
if (!d.licenceId) return;
const install = await prisma.install.findFirst({ where: { licenceId: d.licenceId, releasedAt: null }, include: { deployment: true } });
if (install && !install.deployment) await prisma.deployment.update({ where: { id: d.id }, data: { installId: install.id } });
}
/**
* A registered site the Hub has no install record for, of a customer with a product on a server:
* ask that server what's on it (a `status` job, at most one a day per server), so the site is added by
* itself (linkFromStatus). Called after a heartbeat; never fails it.
*/
async function lookForUnlinked(install, now = new Date()) {
try {
if (!install || install.releasedAt) return null;
const own = await prisma.deployment.findFirst({ where: { installId: install.id } });
if (own) return null;
const sibling = await prisma.deployment.findFirst({ where: { customerId: install.customerId, status: { in: ['live', 'waiting_for_proxy'] } }, include: { server: true } });
if (!sibling || sibling.server.removedAt || sibling.server.mode !== 'church') return null;
const recent = await prisma.job.findFirst({ where: { serverId: sibling.serverId, type: 'status', createdAt: { gt: new Date(now.getTime() - 24 * HOUR) } } });
if (recent) return null;
return await makeJob(prisma, { serverId: sibling.serverId, type: 'status', args: { church: sibling.shortName }, notBefore: now });
} catch (e) {
console.warn('[jobs] looking for an unlinked install failed:', e?.message || e);
return null;
}
}
const JOB_STATUSES = ['queued', 'scheduled', 'delivered', 'succeeded', 'failed', 'rolled_back', 'refused', 'missed', 'cancelled', 'timed_out'];
/** The jobs list's filters (Hub 2.6.0, GET /api/admin/jobs). */
async function listWhere(q = {}) {
const and = [];
if (q.upcoming === 'true') and.push({ status: { in: ['queued', 'scheduled', 'delivered'] } });
else if (q.status) {
const list = String(q.status).split(',').filter(s => JOB_STATUSES.includes(s));
if (!list.length) throw fail(400, 'BAD_REQUEST', 'Unknown job status.');
and.push({ status: { in: list } });
}
if (q.type) and.push({ type: String(q.type) });
if (q.serverId) and.push({ serverId: String(q.serverId) });
if (q.deploymentId) and.push({ deploymentId: String(q.deploymentId) });
// By product or church: the matching installs first, then their jobs.
const term = searchTerm(q.q);
if (q.product || term) {
const dWhere = { AND: [
...(q.product ? [{ product: String(q.product) }] : []),
...(term ? [{ OR: [{ shortName: { contains: term, mode: 'insensitive' } }, { domain: { contains: term, mode: 'insensitive' } }] }] : []),
] };
const ids = (await prisma.deployment.findMany({ where: dWhere, select: { id: true } })).map(d => d.id);
and.push({ deploymentId: { in: ids } });
}
return and.length ? { AND: and } : {};
}
/** Proxy done (§7.8): check the public addresses, then Live and the welcome email. */
async function proxyDone(deploymentId, now = new Date(), fetcher = fetch) {
const d = await prisma.deployment.findUnique({ where: { id: deploymentId }, include: { install: true, customer: true } });
@@ -559,7 +666,36 @@ function scheduleWarnings(at, deployment) {
* runs them one at a time from `at` and stops at the first failure. Each church gets one email
* and a banner now, and a reminder an hour before.
*/
async function scheduleUpdate({ deploymentIds, version, at, emergency = false, reason = null, totp = null }, admin, now = new Date()) {
/**
* What an update of a product (not Accounts) does to the church's Accounts (Hub 2.6.0).
* `crosscode deploy` always updates Accounts too, to its latest release unless told a version, so
* the Hub always tells it one:
* - the release needs a newer Accounts: the newest Accounts release (refused if none is new enough)
* - the church has no Accounts and the release needs it: installed first, in the same batch
* - otherwise: the version it runs, so it isn't changed
* Returns { version: 'accounts@x' | null, install: { domain, release } | null, note }.
*/
async function accountsPlan(d, release, accountsRelease) {
if (d.product === 'accounts') return { version: null, install: null, note: null };
const acc = await prisma.deployment.findFirst({ where: { shortName: d.shortName, product: 'accounts', status: { notIn: ['removed', 'failed'] } }, include: { install: true } });
const running = acc ? (acc.install?.version || acc.version || null) : null;
const releases = await prisma.release.findMany({ where: { product: d.product } });
const from = d.install?.version || d.version || null;
const need = unmetRequirements({ releases, from, target: release.version, siblings: running ? [{ product: 'accounts', version: running }] : [] }).find(u => u.product === 'accounts');
if (!need) return { version: running ? `accounts@${running}` : null, install: null, note: null };
if (!accountsRelease || compareVersions(accountsRelease.version, need.version) < 0) {
throw fail(409, 'REQUIREMENT_NOT_MET', `${d.shortName}: ${PRODUCT_NAMES[d.product]} ${release.version} needs Accounts ${need.version}, and there's no Accounts release that new yet.`);
}
if (acc) {
if (acc.status !== 'live') throw fail(409, 'NOT_LIVE', `${d.shortName}: its Accounts isn't live (${acc.status}).`);
return { version: `accounts@${accountsRelease.version}`, install: null, note: `${d.shortName}: Accounts is updated from ${running || 'an unknown version'} to ${accountsRelease.version} first (${PRODUCT_NAMES[d.product]} ${release.version} needs ${need.version}).` };
}
const domain = accountsDomainFor(d.domain);
if (!DOMAIN.test(domain)) throw fail(400, 'BAD_REQUEST', `${d.shortName}: no Accounts domain could be made from ${d.domain}; install Accounts first (New install).`);
return { version: `accounts@${accountsRelease.version}`, install: { domain, release: accountsRelease }, note: `${d.shortName}: Accounts ${accountsRelease.version} is installed first at ${domain} (${PRODUCT_NAMES[d.product]} ${release.version} needs it).` };
}
async function scheduleUpdate({ deploymentIds, product: wanted = null, version, at, emergency = false, reason = null, totp = null }, admin, now = new Date()) {
const when = new Date(at);
if (Number.isNaN(when.getTime())) throw fail(400, 'BAD_REQUEST', 'Pick a time.');
if (emergency) {
@@ -574,15 +710,21 @@ async function scheduleUpdate({ deploymentIds, version, at, emergency = false, r
const deployments = await prisma.deployment.findMany({ where: { id: { in: ids } }, include: { server: true, install: true, customer: true } });
if (deployments.length !== ids.length) throw fail(404, 'NOT_FOUND', 'One of the installs wasn\'t found.');
const products = new Set(deployments.map(d => d.product));
if (products.size !== 1) throw fail(400, 'BAD_REQUEST', 'A batch is for one product.');
if (products.size !== 1) throw fail(400, 'BAD_REQUEST', 'A batch is for one product: choose Cross Events or Accounts installs, not both.');
const product = [...products][0];
const release = await releaseFor(product, version);
// Hub 2.6.0: the page says which product it's updating; a mismatch is refused, never guessed.
if (wanted && wanted !== product) throw fail(400, 'WRONG_PRODUCT', `These installs are ${PRODUCT_NAMES[product]}, not ${PRODUCT_NAMES[wanted] || wanted}.`);
if (version && /@/.test(String(version)) && !String(version).startsWith(`${product}@`)) throw fail(400, 'WRONG_PRODUCT', `${version} isn't a ${PRODUCT_NAMES[product]} release.`);
const release = await releaseFor(product, version ? String(version).replace(/^[a-z]+@/, '') : null);
const accountsRelease = product === 'accounts' ? null : await prisma.release.findMany({ where: { product: 'accounts' } }).then(rs => rs.sort((a, b) => compareVersions(b.version, a.version))[0] || null);
const plans = new Map();
const warnings = [];
for (const d of deployments) {
if (d.status !== 'live') throw fail(409, 'NOT_LIVE', `${d.shortName} isn't live (${d.status}).`);
if (d.server.removedAt) throw fail(409, 'SERVER_REMOVED', `${d.shortName}'s server was removed.`);
if (d.install) {
const unmet = await unmetRequirementsFor(d.install, release);
// Accounts is handled below (kept, updated, or installed first); anything else must be met.
const unmet = (await unmetRequirementsFor(d.install, release.version)).filter(u => u.product !== 'accounts');
if (unmet.length) throw fail(409, 'REQUIREMENT_NOT_MET', `${d.shortName}: ${release.version} needs ${unmet.map(u => `${u.product} ${u.version}`).join(', ')} first.`);
}
const missing = await missingFor(product, release.version, servers.serverConfig(d.server), await servers.installDefaults());
@@ -590,18 +732,46 @@ async function scheduleUpdate({ deploymentIds, version, at, emergency = false, r
const invalid = invalidFor(servers.serverConfig(d.server), await servers.installDefaults());
if (invalid.length) throw fail(409, 'CONFIG_INVALID', `${d.shortName}: fix ${d.server.name}'s configuration first. ${invalid.join(' ')}`);
warnings.push(...scheduleWarnings(when, d));
const plan = await accountsPlan(d, release, accountsRelease);
if (plan.install) await preflight(d.server, 'accounts', plan.install.release.version, now);
if (plan.note) warnings.push(plan.note);
plans.set(d.id, plan);
}
const batchId = deployments.length > 1 ? servers.newId('batch') : null;
const installsFirst = [...plans.values()].filter(p => p.install).length;
const batchId = deployments.length + installsFirst > 1 ? servers.newId('batch') : null;
const name = PRODUCT_NAMES[product];
const jobs = [];
for (const [i, d] of deployments.entries()) {
let order = 0;
for (const d of deployments) {
const plan = plans.get(d.id);
const next = () => ({ batchId, batchOrder: batchId ? order : null, status: !batchId || order++ === 0 ? 'queued' : 'scheduled' });
if (plan.install) {
// The church's Accounts, installed just before its update (a licence, ports, an add-product job).
const acc = await prisma.$transaction(async tx => {
let licence = await tx.licence.findFirst({ where: { customerId: d.customerId, product: 'accounts', status: { not: 'revoked' } }, include: { install: true } });
if (licence?.install && !licence.install.releasedAt) throw fail(409, 'LICENCE_IN_USE', `${d.shortName}: its Accounts licence is already used by ${licence.install.url}. Link that install (Installs → Link existing) instead.`);
if (!licence) licence = (await generateLicence(tx, { customerId: d.customerId, product: 'accounts', now })).licence;
const ports = await servers.allocatePorts(tx, d.serverId, now);
const a = await tx.deployment.create({ data: { serverId: d.serverId, customerId: d.customerId, licenceId: licence.id, product: 'accounts', shortName: d.shortName, domain: plan.install.domain, webPort: ports.web, apiPort: ports.api, timezone: d.timezone, adminName: d.adminName, adminEmail: d.adminEmail, status: 'installing' } });
await tx.port.updateMany({ where: { port: { in: [ports.web, ports.api] } }, data: { deploymentId: a.id } });
const o = next();
const job = await makeJob(tx, {
serverId: d.serverId, type: 'add-product', deploymentId: a.id, createdById: admin?.id || null, notBefore: when, ...o,
args: { church: d.shortName, product: 'accounts', version: `accounts@${plan.install.release.version}`, domain: plan.install.domain, ports },
});
return job;
});
jobs.push(acc);
}
const title = emergency ? `Urgent ${name} update` : `Planned ${name} update`;
const message = `${name} will be updated on ${sast(when)}. The site will be unavailable for a few minutes.${emergency ? ` Why: ${reason}` : ''}`;
const noticeId = await addNotice(d, { title, message, endsAt: new Date(when.getTime() + 2 * HOUR), level: emergency ? 'warning' : 'maintenance' }, now);
// Accounts goes first in the same deploy: told its version, so it's never changed by surprise.
const versions = [...(plan.version && !plan.install ? [plan.version] : []), `${product}@${release.version}`];
jobs.push(await makeJob(prisma, {
serverId: d.serverId, type: 'deploy', deploymentId: d.id, createdById: admin?.id || null, scheduled: true, emergency, reason,
batchId, batchOrder: batchId ? i : null, status: !batchId || i === 0 ? 'queued' : 'scheduled', notBefore: when, noticeId,
args: { church: d.shortName, products: [product], versions: [`${product}@${release.version}`] },
...next(), notBefore: when, noticeId,
args: { church: d.shortName, products: [product], versions },
}));
const notes = release.notes ? `\n\nWhat's new in ${release.version}:\n${release.notes}` : '';
await emailSiteAdmin(d, `${emergency ? 'Urgent: ' : ''}${name} will be updated on ${sast(when)}`, `${message}${notes}`);
@@ -777,6 +947,6 @@ async function seedDemo({ deploymentId, profile, confirm }, admin, now = new Dat
module.exports = {
WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo,
makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch,
newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
linkFromStatus, listWhere, lookForUnlinked, newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow,
fastPanelText, jobReportText, scheduleWarnings, requireTotp, agentOnline, siteAdminEmail,
};
+30
View File
@@ -0,0 +1,30 @@
/**
* Paging for lists that grow without end (Hub 2.6.0): jobs, the audit log, alerts. `?page=` (from
* 1) and `?pageSize=` (default 50, at most 200); the answer has the page's rows plus `total`,
* `page`, `pageSize` and `pages`, so the list never stops at a fixed number of rows.
*/
const DEFAULT_SIZE = 50;
const MAX_SIZE = 200;
function pageOf(query = {}, { defaultSize = DEFAULT_SIZE } = {}) {
const size = Math.min(MAX_SIZE, Math.max(1, parseInt(query.pageSize, 10) || defaultSize));
const page = Math.max(1, parseInt(query.page, 10) || 1);
return { page, pageSize: size, skip: (page - 1) * size, take: size };
}
/** Runs the page's query and the count together. */
async function paged(model, { where, orderBy, include, select }, p) {
const [rows, total] = await Promise.all([
model.findMany({ where, orderBy, include, select, skip: p.skip, take: p.take }),
model.count({ where }),
]);
return { rows, total, page: p.page, pageSize: p.pageSize, pages: Math.max(1, Math.ceil(total / p.pageSize)) };
}
/** A search term for `contains` filters (trimmed, at most 100 characters), or null. */
function searchTerm(q) {
const s = String(q ?? '').trim().slice(0, 100);
return s || null;
}
module.exports = { pageOf, paged, searchTerm, MAX_SIZE };