Files
spq-v2/pb_migrations/1740000000028_add_created_updated_fields.js
2026-07-12 10:01:39 -04:00

97 lines
2.7 KiB
JavaScript

/// <reference path="../pb_data/types.d.ts" />
//
// M28 — Add system `created` / `updated` AutodateFields to collections
// that were created without them.
//
// PocketBase v0.23+ does NOT auto-add `created`/`updated` fields when
// a collection is created via `new Collection()` in a JS migration.
// Collections created through the admin UI DO get them.
//
// Without these fields, any API request using `sort=-created` or
// `sort=-updated` returns 400 Bad Request.
//
// Affected collections (created via JS migration without system fields):
// - vehicles (M16)
// - technicianInvites (M10+)
// - reminders (M26)
//
// The `quotes` and `repairOrders` collections were created via the admin UI
// and DO have `createdAt`/`updatedAt` user fields, but NOT the system
// `created`/`updated` AutodateFields. They need them for sort support.
//
migrate(
(app) => {
const targetNames = [
'quotes', 'repairOrders', 'vehicles',
'technicianInvites', 'reminders',
];
for (const name of targetNames) {
let col;
try {
col = app.findCollectionByNameOrId(name);
} catch {
console.warn(`[M28] collection "${name}" not found — skipping`);
continue;
}
if (!col) continue;
const hasCreated = col.fields.find((f) => f.name === 'created');
const hasUpdated = col.fields.find((f) => f.name === 'updated');
if (!hasCreated) {
col.fields.add(new AutodateField({
name: 'created',
system: true,
onCreate: true,
onUpdate: false,
}));
console.log(`[M28] added 'created' field to "${name}"`);
} else {
console.log(`[M28] 'created' already exists on "${name}" — skipping`);
}
if (!hasUpdated) {
col.fields.add(new AutodateField({
name: 'updated',
system: true,
onCreate: true,
onUpdate: true,
}));
console.log(`[M28] added 'updated' field to "${name}"`);
} else {
console.log(`[M28] 'updated' already exists on "${name}" — skipping`);
}
app.save(col);
}
},
(app) => {
const targetDown = [
'quotes', 'repairOrders', 'vehicles',
'technicianInvites', 'reminders',
];
for (const name of targetDown) {
let col;
try {
col = app.findCollectionByNameOrId(name);
} catch {
continue;
}
if (!col) continue;
for (const fieldName of ['created', 'updated']) {
const idx = col.fields.findIndex((f) => f.name === fieldName);
if (idx >= 0) {
col.fields.splice(idx, 1);
console.log(`[M28] removed '${fieldName}' from "${name}"`);
}
}
app.save(col);
}
}
);