Merge pull request #2034 from payloadcms/hotfix/max-versions

fix: max versions incorrectly sorting and removing
This commit is contained in:
James Mikrut
2023-02-07 11:48:00 -05:00
committed by GitHub
4 changed files with 45 additions and 8 deletions

View File

@@ -23,14 +23,12 @@ export const enforceMaxVersions = async ({
if (id) query.parent = id;
const oldestAllowedDoc = await Model.find(query).limit(1).skip(max).sort({ createdAt: -1 });
if (oldestAllowedDoc?.[0]?.createdAt) {
const deleteLessThan = oldestAllowedDoc[0].createdAt;
const oldestAllowedDoc = await Model.find(query).limit(1).skip(max).sort({ updatedAt: -1 });
if (oldestAllowedDoc?.[0]?.updatedAt) {
await Model.deleteMany({
createdAt: {
$lte: deleteLessThan,
updatedAt: {
$lte: oldestAllowedDoc[0].updatedAt,
},
});
}

View File

@@ -100,7 +100,7 @@ export const saveVersion = async ({
if (global && typeof global.versions.max === 'number') max = global.versions.max;
if (max > 0) {
enforceMaxVersions({
await enforceMaxVersions({
id,
payload,
Model: VersionModel,

View File

@@ -9,7 +9,7 @@ const VersionPosts: CollectionConfig = {
},
versions: {
drafts: false,
maxPerDoc: 35,
maxPerDoc: 2,
},
access: {
read: ({ req: { user } }) => {

View File

@@ -318,6 +318,45 @@ describe('Versions', () => {
expect(versions.docs).toHaveLength(3);
});
});
describe('Versions Count', () => {
it('retains correct versions', async () => {
const original = await payload.create({
collection: 'version-posts',
data: {
title: 'A',
description: 'A',
},
});
await payload.update({
collection: 'version-posts',
id: original.id,
data: {
title: 'B',
description: 'B',
},
});
await payload.update({
collection: 'version-posts',
id: original.id,
data: {
title: 'C',
description: 'C',
},
});
const versions = await payload.findVersions({
collection: 'version-posts',
sort: '-updatedAt',
depth: 1,
});
expect(versions.docs[versions.docs.length - 1].version.title).toStrictEqual('B');
expect(versions.docs).toHaveLength(2);
});
});
});
describe('Querying', () => {