UNPKG

payload

Version:

Node, React, Headless CMS and Application Framework built on Next.js

111 lines (110 loc) 3.54 kB
/** * Finds the latest version and updates it in place if `shouldUpdate` returns true. * Used by both the unpublish and autosave paths in `saveVersion` to avoid creating * a redundant new version. * * Returns the updated version result, or `undefined` if no update was performed. */ export async function updateLatestVersion({ id, collection, global, now, payload, req, shouldUpdate = ()=>true, versionData }) { let docs; const findVersionArgs = { limit: 1, pagination: false, req, sort: '-updatedAt' }; if (collection) { ; ({ docs } = await payload.db.findVersions({ ...findVersionArgs, collection: collection.slug, where: { parent: { equals: id } } })); } else { ; ({ docs } = await payload.db.findGlobalVersions({ ...findVersionArgs, global: global.slug })); } const [latestVersion] = docs; if (!latestVersion || !shouldUpdate(latestVersion)) { return undefined; } const updateVersionArgs = { id: latestVersion.id, req, versionData: { createdAt: new Date(latestVersion.createdAt).toISOString(), latest: true, parent: id, updatedAt: now, version: { ...versionData } } }; let versionUpdateFailed = undefined; try { if (collection) { return await payload.db.updateVersion({ ...updateVersionArgs, collection: collection.slug, req }); } return await payload.db.updateGlobalVersion({ ...updateVersionArgs, global: global.slug, req }); } catch (err) { versionUpdateFailed = true; payload.logger.warn({ err, msg: `Failed to update latest version — checking if a concurrent write already succeeded.` }); } if (versionUpdateFailed) { // If a concurrent request already committed, return its result to avoid a duplicate version. // If updatedAt is unchanged, the update genuinely failed — fall back to createVersion. try { let freshDocs; if (collection) { ; ({ docs: freshDocs } = await payload.db.findVersions({ collection: collection.slug, limit: 1, pagination: false, req, sort: '-updatedAt', where: { parent: { equals: id } } })); } else { ; ({ docs: freshDocs } = await payload.db.findGlobalVersions({ global: global.slug, limit: 1, pagination: false, req, sort: '-updatedAt' })); } const [freshVersion] = freshDocs; if (freshVersion && new Date(freshVersion.updatedAt) > new Date(latestVersion.updatedAt)) { return freshVersion; } } catch { // If the follow-up query also fails, fall through to createVersion } } return undefined; } //# sourceMappingURL=updateLatestVersion.js.map