-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathafterChange.ts
More file actions
109 lines (94 loc) · 3.43 KB
/
afterChange.ts
File metadata and controls
109 lines (94 loc) · 3.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import type { CollectionAfterChangeHook, CollectionConfig, FileData, TypeWithID } from 'payload'
import type { GeneratedAdapter } from '../types.js'
import { getIncomingFiles } from '../utilities/getIncomingFiles.js'
interface Args {
adapter: GeneratedAdapter
collection: CollectionConfig
}
export const getAfterChangeHook =
({ adapter, collection }: Args): CollectionAfterChangeHook<FileData & TypeWithID> =>
async ({ doc, operation, previousDoc, req }) => {
// Skip if this is an internal update to prevent infinite loop
if (req.context?.skipCloudStorage) {
return doc
}
try {
const files = getIncomingFiles({ data: doc, req })
if (files.length > 0) {
// If there is a previous doc, files and the operation is update,
// delete the old files before uploading the new ones.
if (previousDoc && operation === 'update') {
let filesToDelete: string[] = []
if (typeof previousDoc?.filename === 'string') {
filesToDelete.push(previousDoc.filename)
}
if (typeof previousDoc.sizes === 'object') {
filesToDelete = filesToDelete.concat(
Object.values(previousDoc?.sizes || []).map(
(resizedFileData) => resizedFileData?.filename as string,
),
)
}
const deletionPromises = filesToDelete.map(async (filename) => {
if (filename) {
await adapter.handleDelete({ collection, doc: previousDoc, filename, req })
}
})
await Promise.all(deletionPromises)
}
const uploadResults = await Promise.all(
files
.filter((file) => !file.clientUploadContext)
.map((file) =>
adapter.handleUpload({
clientUploadContext: file.clientUploadContext,
collection,
data: doc,
file,
req,
}),
),
)
const uploadMetadata = uploadResults
.filter(
(result): result is Partial<FileData & TypeWithID> =>
result != null && typeof result === 'object',
)
.reduce(
(acc, metadata) => ({ ...acc, ...metadata }),
{} as Partial<FileData & TypeWithID>,
)
if (Object.keys(uploadMetadata).length > 0) {
try {
if (!req.context) {
req.context = {}
}
req.context.skipCloudStorage = true
// Clear to prevent re-processing
req.file = undefined
req.payloadUploadSizes = undefined
await req.payload.update({
id: doc.id,
collection: collection.slug,
data: uploadMetadata,
depth: 0,
req,
})
delete req.context.skipCloudStorage
return { ...doc, ...uploadMetadata }
} catch (updateError: unknown) {
req.payload.logger.warn(
`Failed to persist upload data for collection ${collection.slug} document ${doc.id}: ${String(updateError)}`,
)
}
}
}
} catch (err: unknown) {
req.payload.logger.error(
`There was an error while uploading files corresponding to the collection ${collection.slug} with filename ${doc.filename}:`,
)
req.payload.logger.error({ err })
throw err
}
return doc
}