forked from payloadcms/payload
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsyncDocAsSearchIndex.ts
More file actions
284 lines (258 loc) · 7.9 KB
/
syncDocAsSearchIndex.ts
File metadata and controls
284 lines (258 loc) · 7.9 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import type { DocToSync, SyncDocArgs } from '../types.js'
export const syncDocAsSearchIndex = async ({
collection,
doc,
locale,
onSyncError,
operation,
pluginConfig,
req: { payload },
req,
}: SyncDocArgs) => {
const { id, _status: status, title } = doc || {}
const { beforeSync, defaultPriorities, deleteDrafts, searchOverrides, syncDrafts } = pluginConfig
const searchSlug = searchOverrides?.slug || 'search'
// Determine sync locale
const syncLocale = locale || req.locale || undefined
if (typeof pluginConfig.skipSync === 'function') {
try {
const skipSync = await pluginConfig.skipSync({
collectionSlug: collection,
doc,
locale: syncLocale,
req,
})
if (skipSync) {
return doc
}
} catch (err) {
req.payload.logger.error({
err,
msg: 'Search plugin: Error executing skipSync. Proceeding with sync.',
})
}
}
let dataToSave: DocToSync = {
doc: {
relationTo: collection,
value: id,
},
title,
}
const docKeyPrefix = `${collection}:${id}`
const docKey = req.payload.config.localization ? `${docKeyPrefix}:${syncLocale}` : docKeyPrefix
const syncedDocsSet = (req.context?.syncedDocsSet as Set<string>) || new Set<string>()
if (syncedDocsSet.has(docKey)) {
/*
* prevents duplicate syncing of documents in the same request
* this can happen when hooks call `payload.update` within the create lifecycle
* like the nested-docs plugin does
*/
return doc
} else {
syncedDocsSet.add(docKey)
}
req.context.syncedDocsSet = syncedDocsSet
if (typeof beforeSync === 'function') {
let docToSyncWith = doc
if (payload.config?.localization) {
// Check if document is trashed (has deletedAt field)
const isTrashDocument = doc && 'deletedAt' in doc && doc.deletedAt
docToSyncWith = await payload.findByID({
id,
collection,
locale: syncLocale,
req,
// Include trashed documents when the document being synced is trashed
trash: isTrashDocument,
})
}
dataToSave = await beforeSync({
collectionSlug: collection,
originalDoc: docToSyncWith,
payload,
req,
searchDoc: dataToSave,
})
}
let defaultPriority = 0
if (defaultPriorities) {
const { [collection]: priority } = defaultPriorities
if (typeof priority === 'function') {
try {
defaultPriority = await priority(doc)
} catch (err: unknown) {
payload.logger.error(err)
payload.logger.error(
`Error gathering default priority for ${searchSlug} documents related to ${collection}`,
)
}
} else if (priority !== undefined) {
defaultPriority = priority
}
}
const doSync = syncDrafts || (!syncDrafts && status !== 'draft')
try {
if (operation === 'create' && doSync) {
await payload.create({
collection: searchSlug,
data: {
...dataToSave,
priority: defaultPriority,
},
depth: 0,
locale: syncLocale,
req,
})
}
if (operation === 'update') {
try {
// find the correct doc to sync with
const searchDocQuery = await payload.find({
collection: searchSlug,
depth: 0,
locale: syncLocale,
req,
where: {
'doc.relationTo': {
equals: collection,
},
'doc.value': {
equals: id,
},
},
})
const docs: Array<{
id: number | string
priority?: number
}> = searchDocQuery?.docs || []
const [foundDoc, ...duplicativeDocs] = docs
// delete all duplicative search docs (docs that reference the same page)
// to ensure the same, out-of-date result does not appear twice (where only syncing the first found doc)
if (duplicativeDocs.length > 0) {
try {
const duplicativeDocIDs = duplicativeDocs.map(({ id }) => id)
await payload.delete({
collection: searchSlug,
depth: 0,
req,
where: { id: { in: duplicativeDocIDs } },
})
} catch (err: unknown) {
payload.logger.error({
err,
msg: `Error deleting duplicative ${searchSlug} documents.`,
})
}
}
if (foundDoc) {
const { id: searchDocID } = foundDoc
// Check if document is trashed and delete from search
const isTrashDocument = doc && 'deletedAt' in doc && doc.deletedAt
if (isTrashDocument) {
try {
await payload.delete({
id: searchDocID,
collection: searchSlug,
depth: 0,
req,
})
} catch (err: unknown) {
payload.logger.error({
err,
msg: `Error deleting ${searchSlug} document for trashed doc.`,
})
}
} else {
if (doSync) {
// update the doc normally
try {
await payload.update({
id: searchDocID,
collection: searchSlug,
data: {
...dataToSave,
priority: foundDoc.priority || defaultPriority,
},
depth: 0,
locale: syncLocale,
req,
})
} catch (err: unknown) {
payload.logger.error({ err, msg: `Error updating ${searchSlug} document.` })
}
}
if (deleteDrafts && status === 'draft') {
// Check to see if there's a published version of the doc
// We don't want to remove the search doc if there is a published version but a new draft has been created
const {
docs: [docWithPublish],
} = await payload.find({
collection,
depth: 0,
draft: false,
limit: 1,
locale: syncLocale,
pagination: false,
req,
where: {
and: [
{
_status: {
equals: 'published',
},
},
{
id: {
equals: id,
},
},
],
},
})
if (!docWithPublish) {
// do not include draft docs in search results, so delete the record
try {
await payload.delete({
id: searchDocID,
collection: searchSlug,
depth: 0,
req,
})
} catch (err: unknown) {
payload.logger.error({ err, msg: `Error deleting ${searchSlug} document.` })
}
}
}
}
} else if (doSync) {
try {
await payload.create({
collection: searchSlug,
data: {
...dataToSave,
priority: defaultPriority,
},
depth: 0,
locale: syncLocale,
req,
})
} catch (err: unknown) {
payload.logger.error({ err, msg: `Error creating ${searchSlug} document.` })
}
}
} catch (err: unknown) {
payload.logger.error({ err, msg: `Error finding ${searchSlug} document.` })
}
}
} catch (err: unknown) {
payload.logger.error({
err,
msg: `Error syncing ${searchSlug} document related to ${collection} with id: '${id}'.`,
})
if (onSyncError) {
onSyncError()
}
}
return doc
}