full
This commit is contained in:
34
utils/postStatusSave.js
Normal file
34
utils/postStatusSave.js
Normal file
@@ -0,0 +1,34 @@
|
||||
const STATUS_FALLBACKS = {
|
||||
temp_accept: ['temp_accept', 'accept', 'pending'],
|
||||
}
|
||||
|
||||
/**
|
||||
* Save post; fall back to older status enum values if server schema is outdated.
|
||||
*/
|
||||
async function savePostWithModerationStatus(Model, payload) {
|
||||
const preferredStatus = payload.status || 'pending'
|
||||
const candidates = STATUS_FALLBACKS[preferredStatus] ?? [preferredStatus]
|
||||
|
||||
let lastError = null
|
||||
for (let i = 0; i < candidates.length; i += 1) {
|
||||
const status = candidates[i]
|
||||
const doc = new Model({ ...payload, status })
|
||||
try {
|
||||
await doc.save()
|
||||
return doc
|
||||
} catch (err) {
|
||||
lastError = err
|
||||
const isLast = i === candidates.length - 1
|
||||
if (err?.name === 'ValidationError' && !isLast) {
|
||||
continue
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError ?? new Error('Failed to save post')
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
savePostWithModerationStatus,
|
||||
}
|
||||
Reference in New Issue
Block a user