fix: postgres null value breaks orderable hook (#11997)
When postgres is used and orderable is enabled, payload cannot update the docs to set the order correctly. This is because the sort on postgres pushes `null` values to the top causing unique constraints to error when two documents are updated to the same _order value.
This commit is contained in:
@@ -106,24 +106,27 @@ export const addOrderableFieldsAndHook = (
|
||||
collection.hooks.beforeChange = []
|
||||
}
|
||||
|
||||
const orderBeforeChangeHook: BeforeChangeHook = async ({ data, operation, req }) => {
|
||||
// Only set _order on create, not on update (unless explicitly provided)
|
||||
if (operation === 'create') {
|
||||
for (const orderableFieldName of orderableFieldNames) {
|
||||
if (!data[orderableFieldName]) {
|
||||
const lastDoc = await req.payload.find({
|
||||
collection: collection.slug,
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
pagination: false,
|
||||
req,
|
||||
select: { [orderableFieldName]: true },
|
||||
sort: `-${orderableFieldName}`,
|
||||
})
|
||||
const orderBeforeChangeHook: BeforeChangeHook = async ({ data, originalDoc, req }) => {
|
||||
for (const orderableFieldName of orderableFieldNames) {
|
||||
if (!data[orderableFieldName] && !originalDoc?.[orderableFieldName]) {
|
||||
console.log('do not enter')
|
||||
const lastDoc = await req.payload.find({
|
||||
collection: collection.slug,
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
pagination: false,
|
||||
req,
|
||||
select: { [orderableFieldName]: true },
|
||||
sort: `-${orderableFieldName}`,
|
||||
where: {
|
||||
[orderableFieldName]: {
|
||||
exists: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const lastOrderValue = lastDoc.docs[0]?.[orderableFieldName] || null
|
||||
data[orderableFieldName] = generateKeyBetween(lastOrderValue, null)
|
||||
}
|
||||
const lastOrderValue = lastDoc.docs[0]?.[orderableFieldName] || null
|
||||
data[orderableFieldName] = generateKeyBetween(lastOrderValue, null)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,7 +166,7 @@ export const addOrderableEndpoint = (config: SanitizedConfig) => {
|
||||
}
|
||||
if (
|
||||
typeof target !== 'object' ||
|
||||
typeof target.id !== 'string' ||
|
||||
typeof target.id === 'undefined' ||
|
||||
typeof target.key !== 'string'
|
||||
) {
|
||||
return new Response(JSON.stringify({ error: 'target must be an object with id and key' }), {
|
||||
|
||||
Reference in New Issue
Block a user