Skip to content

Commit 690e99f

Browse files
feat: consolidates logic in update and updateByID operations (#9998)
### What? Consolidates logic in update and updateByID. These two operations used a lot of the same core functionality. This is a QOL improvement for future features/fixes on each operation. You will not need to make changes to both operations now. ### Why? Recently we released a feature for `publishSpecificLocale` and that was only implemented on the updateByID operation. I think future enhancements and fixes may suffer the same treatment. ### How? Moves shared logic into a new file with a function called `updateDocument`.
1 parent 04a8083 commit 690e99f

File tree

3 files changed

+428
-529
lines changed

3 files changed

+428
-529
lines changed

packages/payload/src/collections/operations/update.ts

Lines changed: 26 additions & 240 deletions
Original file line numberDiff line numberDiff line change
@@ -13,26 +13,18 @@ import type {
1313
SelectFromCollectionSlug,
1414
} from '../config/types.js'
1515

16-
import { ensureUsernameOrEmail } from '../../auth/ensureUsernameOrEmail.js'
1716
import executeAccess from '../../auth/executeAccess.js'
1817
import { combineQueries } from '../../database/combineQueries.js'
1918
import { validateQueryPaths } from '../../database/queryValidation/validateQueryPaths.js'
2019
import { APIError } from '../../errors/index.js'
21-
import { afterChange } from '../../fields/hooks/afterChange/index.js'
22-
import { afterRead } from '../../fields/hooks/afterRead/index.js'
23-
import { beforeChange } from '../../fields/hooks/beforeChange/index.js'
24-
import { beforeValidate } from '../../fields/hooks/beforeValidate/index.js'
25-
import { deleteAssociatedFiles } from '../../uploads/deleteAssociatedFiles.js'
2620
import { generateFileData } from '../../uploads/generateFileData.js'
2721
import { unlinkTempFiles } from '../../uploads/unlinkTempFiles.js'
28-
import { uploadFiles } from '../../uploads/uploadFiles.js'
29-
import { checkDocumentLockStatus } from '../../utilities/checkDocumentLockStatus.js'
3022
import { commitTransaction } from '../../utilities/commitTransaction.js'
3123
import { initTransaction } from '../../utilities/initTransaction.js'
3224
import { killTransaction } from '../../utilities/killTransaction.js'
3325
import { buildVersionCollectionFields } from '../../versions/buildCollectionFields.js'
3426
import { appendVersionToQueryKey } from '../../versions/drafts/appendVersionToQueryKey.js'
35-
import { saveVersion } from '../../versions/saveVersion.js'
27+
import { updateDocument } from './utilities/update.js'
3628
import { buildAfterOperation } from './utils.js'
3729

3830
export type Arguments<TSlug extends CollectionSlug> = {
@@ -47,6 +39,7 @@ export type Arguments<TSlug extends CollectionSlug> = {
4739
overrideLock?: boolean
4840
overwriteExistingFiles?: boolean
4941
populate?: PopulateType
42+
publishSpecificLocale?: string
5043
req: PayloadRequest
5144
select?: SelectType
5245
showHiddenFields?: boolean
@@ -91,6 +84,7 @@ export const updateOperation = async <
9184
overrideLock,
9285
overwriteExistingFiles = false,
9386
populate,
87+
publishSpecificLocale,
9488
req: {
9589
fallbackLocale,
9690
locale,
@@ -172,7 +166,7 @@ export const updateOperation = async <
172166
// Generate data for all files and sizes
173167
// /////////////////////////////////////
174168

175-
const { data: newFileData, files: filesToUpload } = await generateFileData({
169+
const { data, files: filesToUpload } = await generateFileData({
176170
collection,
177171
config,
178172
data: bulkUpdateData,
@@ -184,251 +178,37 @@ export const updateOperation = async <
184178

185179
const errors = []
186180

187-
const promises = docs.map(async (doc) => {
188-
const { id } = doc
189-
let data = {
190-
...newFileData,
191-
...bulkUpdateData,
192-
}
181+
const promises = docs.map(async (docWithLocales) => {
182+
const { id } = docWithLocales
193183

194184
try {
195-
// /////////////////////////////////////
196-
// Handle potentially locked documents
197-
// /////////////////////////////////////
198-
199-
await checkDocumentLockStatus({
185+
// ///////////////////////////////////////////////
186+
// Update document, runs all document level hooks
187+
// ///////////////////////////////////////////////
188+
const updatedDoc = await updateDocument({
200189
id,
201-
collectionSlug: collectionConfig.slug,
202-
lockErrorMessage: `Document with ID ${id} is currently locked by another user and cannot be updated.`,
203-
overrideLock,
204-
req,
205-
})
206-
207-
const originalDoc = await afterRead({
208-
collection: collectionConfig,
209-
context: req.context,
210-
depth: 0,
211-
doc,
212-
draft: draftArg,
213-
fallbackLocale,
214-
global: null,
215-
locale,
216-
overrideAccess: true,
217-
req,
218-
showHiddenFields: true,
219-
})
220-
221-
await deleteAssociatedFiles({
190+
accessResults: accessResult,
191+
autosave: false,
222192
collectionConfig,
223193
config,
224-
doc,
225-
files: filesToUpload,
226-
overrideDelete: false,
227-
req,
228-
})
229-
230-
if (args.collection.config.auth) {
231-
ensureUsernameOrEmail<TSlug>({
232-
authOptions: args.collection.config.auth,
233-
collectionSlug: args.collection.config.slug,
234-
data: args.data,
235-
operation: 'update',
236-
originalDoc,
237-
req: args.req,
238-
})
239-
}
240-
241-
// /////////////////////////////////////
242-
// beforeValidate - Fields
243-
// /////////////////////////////////////
244-
245-
data = await beforeValidate<DeepPartial<DataFromCollectionSlug<TSlug>>>({
246-
id,
247-
collection: collectionConfig,
248-
context: req.context,
249-
data,
250-
doc: originalDoc,
251-
global: null,
252-
operation: 'update',
253-
overrideAccess,
254-
req,
255-
})
256-
257-
// /////////////////////////////////////
258-
// beforeValidate - Collection
259-
// /////////////////////////////////////
260-
261-
await collectionConfig.hooks.beforeValidate.reduce(async (priorHook, hook) => {
262-
await priorHook
263-
264-
data =
265-
(await hook({
266-
collection: collectionConfig,
267-
context: req.context,
268-
data,
269-
operation: 'update',
270-
originalDoc,
271-
req,
272-
})) || data
273-
}, Promise.resolve())
274-
275-
// /////////////////////////////////////
276-
// Write files to local storage
277-
// /////////////////////////////////////
278-
279-
if (!collectionConfig.upload.disableLocalStorage) {
280-
await uploadFiles(payload, filesToUpload, req)
281-
}
282-
283-
// /////////////////////////////////////
284-
// beforeChange - Collection
285-
// /////////////////////////////////////
286-
287-
await collectionConfig.hooks.beforeChange.reduce(async (priorHook, hook) => {
288-
await priorHook
289-
290-
data =
291-
(await hook({
292-
collection: collectionConfig,
293-
context: req.context,
294-
data,
295-
operation: 'update',
296-
originalDoc,
297-
req,
298-
})) || data
299-
}, Promise.resolve())
300-
301-
// /////////////////////////////////////
302-
// beforeChange - Fields
303-
// /////////////////////////////////////
304-
305-
let result = await beforeChange({
306-
id,
307-
collection: collectionConfig,
308-
context: req.context,
309194
data,
310-
doc: originalDoc,
311-
docWithLocales: doc,
312-
global: null,
313-
operation: 'update',
314-
req,
315-
skipValidation:
316-
shouldSaveDraft &&
317-
collectionConfig.versions.drafts &&
318-
!collectionConfig.versions.drafts.validate &&
319-
data._status !== 'published',
320-
})
321-
322-
// /////////////////////////////////////
323-
// Update
324-
// /////////////////////////////////////
325-
326-
if (!shouldSaveDraft || data._status === 'published') {
327-
result = await req.payload.db.updateOne({
328-
id,
329-
collection: collectionConfig.slug,
330-
data: result,
331-
locale,
332-
req,
333-
select,
334-
})
335-
}
336-
337-
// /////////////////////////////////////
338-
// Create version
339-
// /////////////////////////////////////
340-
341-
if (collectionConfig.versions) {
342-
result = await saveVersion({
343-
id,
344-
collection: collectionConfig,
345-
docWithLocales: result,
346-
payload,
347-
req,
348-
select,
349-
})
350-
}
351-
352-
// /////////////////////////////////////
353-
// afterRead - Fields
354-
// /////////////////////////////////////
355-
356-
result = await afterRead({
357-
collection: collectionConfig,
358-
context: req.context,
359195
depth,
360-
doc: result,
361-
draft: draftArg,
362-
fallbackLocale: null,
363-
global: null,
196+
docWithLocales,
197+
draftArg,
198+
fallbackLocale,
199+
filesToUpload,
364200
locale,
365201
overrideAccess,
202+
overrideLock,
203+
payload,
366204
populate,
205+
publishSpecificLocale,
367206
req,
368207
select,
369208
showHiddenFields,
370209
})
371210

372-
// /////////////////////////////////////
373-
// afterRead - Collection
374-
// /////////////////////////////////////
375-
376-
await collectionConfig.hooks.afterRead.reduce(async (priorHook, hook) => {
377-
await priorHook
378-
379-
result =
380-
(await hook({
381-
collection: collectionConfig,
382-
context: req.context,
383-
doc: result,
384-
req,
385-
})) || result
386-
}, Promise.resolve())
387-
388-
// /////////////////////////////////////
389-
// afterChange - Fields
390-
// /////////////////////////////////////
391-
392-
result = await afterChange({
393-
collection: collectionConfig,
394-
context: req.context,
395-
data,
396-
doc: result,
397-
global: null,
398-
operation: 'update',
399-
previousDoc: originalDoc,
400-
req,
401-
})
402-
403-
// /////////////////////////////////////
404-
// afterChange - Collection
405-
// /////////////////////////////////////
406-
407-
await collectionConfig.hooks.afterChange.reduce(async (priorHook, hook) => {
408-
await priorHook
409-
410-
result =
411-
(await hook({
412-
collection: collectionConfig,
413-
context: req.context,
414-
doc: result,
415-
operation: 'update',
416-
previousDoc: originalDoc,
417-
req,
418-
})) || result
419-
}, Promise.resolve())
420-
421-
await unlinkTempFiles({
422-
collectionConfig,
423-
config,
424-
req,
425-
})
426-
427-
// /////////////////////////////////////
428-
// Return results
429-
// /////////////////////////////////////
430-
431-
return result
211+
return updatedDoc
432212
} catch (error) {
433213
errors.push({
434214
id,
@@ -438,6 +218,12 @@ export const updateOperation = async <
438218
return null
439219
})
440220

221+
await unlinkTempFiles({
222+
collectionConfig,
223+
config,
224+
req,
225+
})
226+
441227
const awaitedDocs = await Promise.all(promises)
442228

443229
let result = {

0 commit comments

Comments
 (0)