fix: duplicate list preferences stored (#9185)

The collection list columns are stored as user preferences to the
payload-preferences collection. Normally one user should never have
duplicate documents with the same key. This is controlled by using an
upsert normally. The collection list does not have a good way to call
upsert and was creating preferences documents every time. This change
makes it so that existing preferences are updated rather than created
with each column change.
This commit is contained in:
Dan Ribbens
2024-11-15 14:22:04 -05:00
committed by GitHub
parent ba06ce6338
commit a5cae077cc

View File

@@ -166,6 +166,7 @@ export const buildTableState = async (
collection: 'payload-preferences', collection: 'payload-preferences',
depth: 0, depth: 0,
limit: 1, limit: 1,
pagination: false,
where: { where: {
and: [ and: [
{ {
@@ -186,18 +187,16 @@ export const buildTableState = async (
], ],
}, },
}) })
.then((res) => res.docs[0]?.value as ListPreferences) .then((res) => res.docs[0] ?? { id: null, value: {} })
let newPrefs = preferencesResult let newPrefs = preferencesResult.value
if (!preferencesResult || !dequal(columns, preferencesResult?.columns)) { if (!preferencesResult.id || !dequal(columns, preferencesResult?.columns)) {
const mergedPrefs = { const mergedPrefs = {
...(preferencesResult || {}), ...(preferencesResult || {}),
columns, columns,
} }
const preferencesArgs = {
newPrefs = await payload
.create({
collection: 'payload-preferences', collection: 'payload-preferences',
data: { data: {
key: preferencesKey, key: preferencesKey,
@@ -207,9 +206,20 @@ export const buildTableState = async (
}, },
value: mergedPrefs, value: mergedPrefs,
}, },
depth: 0,
req, req,
}
if (preferencesResult.id) {
newPrefs = await payload
.update({
...preferencesArgs,
id: preferencesResult.id,
}) })
?.then((res) => res.value as ListPreferences) ?.then((res) => res.value as ListPreferences)
} else {
newPrefs = await payload.create(preferencesArgs)?.then((res) => res.value as ListPreferences)
}
} }
const fields = collectionConfig.fields const fields = collectionConfig.fields