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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914import { describe, beforeAll, beforeEach, afterAll, it, expect } from 'vitest'
import type { Payload } from 'payload'
import path from 'path'
import { wait } from 'payload/shared'
import { fileURLToPath } from 'url'
import type { NextRESTClient } from '../helpers/NextRESTClient.js'
import { devUser } from '../credentials.js'
import { initPayloadInt } from '../helpers/initPayloadInt.js'
import { pagesSlug, postsSlug } from './shared.js'
let payload: Payload
let restClient: NextRESTClient
let token: string
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
describe('@payloadcms/plugin-search', () => {
beforeAll(async () => {
;({ payload, restClient } = await initPayloadInt(dirname))
const data = await restClient
.POST('/users/login', {
body: JSON.stringify({
email: devUser.email,
password: devUser.password,
}),
})
.then((res) => res.json())
token = data.token
})
beforeEach(async () => {
await payload.delete({
collection: 'search',
depth: 0,
where: {
id: {
exists: true,
},
},
})
await Promise.all([
payload.delete({
collection: postsSlug,
depth: 0,
where: {
id: {
exists: true,
},
},
}),
payload.delete({
collection: pagesSlug,
depth: 0,
where: {
id: {
exists: true,
},
},
}),
])
})
afterAll(async () => {
await payload.destroy()
})
it('should add a search collection', async () => {
const search = await payload.find({
collection: 'search',
depth: 0,
limit: 1,
})
expect(search).toBeTruthy()
})
it('should sync published pages to the search collection', async () => {
const pageToSync = await payload.create({
collection: 'pages',
data: {
_status: 'published',
excerpt: 'This is a test page',
title: 'Hello, world!',
},
})
const { docs: results } = await payload.find({
collection: 'search',
depth: 0,
where: {
'doc.value': {
equals: pageToSync.id,
},
},
})
expect(results).toHaveLength(1)
expect(results[0].doc.value).toBe(pageToSync.id)
expect(results[0].title).toBe('Hello, world!')
expect(results[0].excerpt).toBe('This is a test page')
})
it('should not sync drafts pages to the search collection', async () => {
const draftPage = await payload.create({
collection: 'pages',
data: {
_status: 'draft',
excerpt: 'This is a test page',
title: 'Hello, world!',
},
})
// wait for the search document to be potentially created
// we do not await this within the `syncToSearch` hook
await wait(200)
const { docs: results } = await payload.find({
collection: 'search',
depth: 0,
where: {
'doc.value': {
equals: draftPage.id,
},
},
})
expect(results).toHaveLength(0)
})
it('should not delete a search doc if a published item has a new draft but remains published', async () => {
const publishedPage = await payload.create({
collection: 'pages',
data: {
_status: 'published',
title: 'Published title!',
},
})
// wait for the search document to be potentially created
// we do not await this within the `syncToSearch` hook
await wait(200)
const { docs: results } = await payload.find({
collection: 'search',
depth: 0,
where: {
'doc.value': {
equals: publishedPage.id,
},
},
})
expect(results).toHaveLength(1)
// Create a new draft
await payload.update({
collection: 'pages',
id: publishedPage.id,
draft: true,
data: {
_status: 'draft',
title: 'Draft title!',
},
})
// This should remain with the published content
const { docs: updatedResults } = await payload.find({
collection: 'search',
depth: 0,
where: {
'doc.value': {
equals: publishedPage.id,
},
},
})
expect(updatedResults).toHaveLength(1)
await payload.update({
collection: 'pages',
id: publishedPage.id,
data: {
_status: 'draft',
title: 'Drafted again',
},
})
// Should now be deleted given we've unpublished the page
const { docs: deletedResults } = await payload.find({
collection: 'search',
depth: 0,
where: {
'doc.value': {
equals: publishedPage.id,
},
},
})
expect(deletedResults).toHaveLength(0)
})
it('should sync changes made to an existing search document', async () => {
const pageToReceiveUpdates = await payload.create({
collection: 'pages',
data: {
_status: 'published',
excerpt: 'This is a test page',
title: 'Hello, world!',
},
})
const { docs: results } = await payload.find({
collection: 'search',
depth: 0,
where: {
'doc.value': {
equals: pageToReceiveUpdates.id,
},
},
})
expect(results).toHaveLength(1)
expect(results[0].doc.value).toBe(pageToReceiveUpdates.id)
expect(results[0].title).toBe('Hello, world!')
expect(results[0].excerpt).toBe('This is a test page')
await payload.update({
id: pageToReceiveUpdates.id,
collection: 'pages',
data: {
excerpt: 'This is a test page (updated)',
title: 'Hello, world! (updated)',
},
})
// wait for the search document to be potentially updated
// we do not await this within the `syncToSearch` hook
await wait(200)
// Do not add `limit` to this query, this way we can test if multiple documents were created
const { docs: updatedResults } = await payload.find({
collection: 'search',
depth: 0,
where: {
'doc.value': {
equals: pageToReceiveUpdates.id,
},
},
})
expect(updatedResults).toHaveLength(1)
expect(updatedResults[0].doc.value).toBe(pageToReceiveUpdates.id)
expect(updatedResults[0].title).toBe('Hello, world! (updated)')
expect(updatedResults[0].excerpt).toBe('This is a test page (updated)')
})
it('should clear the search document when the original document is deleted', async () => {
const page = await payload.create({
collection: 'pages',
data: {
_status: 'published',
excerpt: 'This is a test page',
title: 'Hello, world!',
},
})
// wait for the search document to be created
// we do not await this within the `syncToSearch` hook
await wait(200)
const { docs: results } = await payload.find({
collection: 'search',
depth: 0,
where: {
'doc.value': {
equals: page.id,
},
},
})
expect(results).toHaveLength(1)
expect(results[0].doc.value).toBe(page.id)
await payload.delete({
id: page.id,
collection: 'pages',
})
// wait for the search document to be potentially deleted
// we do not await this within the `syncToSearch` hook
await wait(200)
const { docs: deletedResults } = await payload.find({
collection: 'search',
depth: 0,
where: {
id: {
equals: results[0].id,
},
},
})
expect(deletedResults).toHaveLength(0)
})
it('should clear the proper search document when having the same doc.value but different doc.relationTo', async () => {
const custom_id_1 = await payload.create({
collection: 'custom-ids-1',
data: { id: 'custom_id' },
})
await payload.create({
collection: 'custom-ids-2',
data: { id: 'custom_id' },
})
await wait(200)
const {
docs: [docBefore],
} = await payload.find({
collection: 'search',
where: { 'doc.value': { equals: 'custom_id' } },
limit: 1,
sort: 'createdAt',
})
expect(docBefore.doc.relationTo).toBe('custom-ids-1')
await payload.delete({ collection: 'custom-ids-1', id: custom_id_1.id })
await wait(200)
const {
docs: [docAfter],
} = await payload.find({
collection: 'search',
where: { 'doc.value': { equals: 'custom_id' } },
limit: 1,
sort: 'createdAt',
})
expect(docAfter.doc.relationTo).toBe('custom-ids-2')
})
it('should sync localized data', async () => {
const createdDoc = await payload.create({
collection: 'posts',
data: {
_status: 'published',
title: 'test title',
slug: 'es',
},
locale: 'es',
})
await payload.update({
collection: 'posts',
id: createdDoc.id,
data: {
_status: 'published',
title: 'test title',
slug: 'en',
},
locale: 'en',
})
const syncedSearchData = await payload.find({
collection: 'search',
locale: 'es',
where: {
and: [
{
'doc.value': {
equals: createdDoc.id,
},
},
],
},
})
expect(syncedSearchData.docs[0].slug).toEqual('es')
})
it('should respond with 401 when invalid permissions on user before reindex', async () => {
const testCreds = {
email: 'test@payloadcms.com',
password: 'test',
}
await payload.create({
collection: 'users',
data: testCreds,
})
const testUserRes = await restClient.POST(`/users/login`, {
body: JSON.stringify(testCreds),
})
const testUser = await testUserRes.json()
const endpointRes = await restClient.POST(`/search/reindex`, {
body: JSON.stringify({
collections: [postsSlug],
}),
headers: {
Authorization: `JWT ${testUser.token}`,
},
})
expect(endpointRes.status).toEqual(401)
})
it('should respond with 400 when invalid collection args passed to reindex', async () => {
const endpointNoArgsRes = await restClient.POST(`/search/reindex`, {
body: JSON.stringify({}),
headers: {
Authorization: `JWT ${token}`,
},
})
const endpointEmptyArrRes = await restClient.POST(`/search/reindex`, {
body: JSON.stringify({
collections: [],
}),
headers: {
Authorization: `JWT ${token}`,
},
})
const endpointInvalidArrRes = await restClient.POST(`/search/reindex`, {
body: JSON.stringify({
collections: ['users'],
}),
headers: {
Authorization: `JWT ${token}`,
},
})
expect(endpointNoArgsRes.status).toBe(400)
expect(endpointEmptyArrRes.status).toBe(400)
expect(endpointInvalidArrRes.status).toBe(400)
})
it('should delete existing search indexes before reindexing', async () => {
await payload.create({
collection: postsSlug,
data: {
title: 'post_1',
_status: 'published',
},
})
await wait(200)
await payload.create({
collection: postsSlug,
data: {
title: 'post_2',
_status: 'published',
},
})
const { docs } = await payload.find({ collection: 'search' })
await wait(200)
const endpointRes = await restClient.POST('/search/reindex', {
body: JSON.stringify({
collections: [postsSlug],
}),
})
expect(endpointRes.status).toBe(200)
await wait(200)
const { docs: results } = await payload.find({
collection: 'search',
depth: 0,
where: {
id: {
in: docs.map((doc) => doc.id),
},
},
})
// Should have no docs with these ID
// after reindex since it deletes indexes and recreates them
expect(results).toHaveLength(0)
})
it('should reindex whole collections', async () => {
await Promise.all([
payload.create({
collection: pagesSlug,
data: {
title: 'Test page title',
_status: 'published',
},
}),
payload.create({
collection: postsSlug,
data: {
title: 'Test page title',
_status: 'published',
},
}),
])
await wait(200)
const { totalDocs: totalBeforeReindex } = await payload.count({
collection: 'search',
})
const endpointRes = await restClient.POST(`/search/reindex`, {
body: JSON.stringify({
collections: [postsSlug, pagesSlug],
}),
headers: {
Authorization: `JWT ${token}`,
},
})
expect(endpointRes.status).toBe(200)
const { totalDocs: totalAfterReindex } = await payload.count({
collection: 'search',
})
expect(totalAfterReindex).toBe(totalBeforeReindex)
})
it('should exclude drafts from reindexing by default', async () => {
await Promise.all([
payload.create({
collection: pagesSlug,
data: {
title: 'Test page published',
_status: 'published',
},
}),
payload.create({
collection: pagesSlug,
data: {
title: 'Test page draft',
_status: 'draft',
},
}),
])
await wait(200)
const { totalDocs: totalBeforeReindex } = await payload.count({
collection: 'search',
})
expect(totalBeforeReindex).toBe(1)
const endpointRes = await restClient.POST(`/search/reindex`, {
body: JSON.stringify({
collections: [pagesSlug],
}),
headers: {
Authorization: `JWT ${token}`,
},
})
expect(endpointRes.status).toBe(200)
const { totalDocs: totalAfterReindex } = await payload.count({
collection: 'search',
})
expect(totalAfterReindex).toBe(totalBeforeReindex)
const data = await endpointRes.json()
const totalDocs = 2
const nonDrafts = 1
expect(data.message).toBe(
`Successfully reindexed ${nonDrafts} of ${totalDocs} documents from ${pagesSlug} and skipped ${totalDocs - nonDrafts} drafts.`,
)
})
it('should reindex all configured locales', async () => {
const post = await payload.create({
collection: postsSlug,
locale: 'en',
data: {
title: 'Test page published',
_status: 'published',
slug: 'test-en',
},
})
await payload.update({
collection: postsSlug,
id: post.id,
locale: 'es',
data: {
_status: 'published',
slug: 'test-es',
},
})
await payload.update({
collection: postsSlug,
id: post.id,
locale: 'de',
data: {
_status: 'published',
slug: 'test-de',
},
})
const {
docs: [postBeforeReindex],
} = await payload.find({
collection: 'search',
locale: 'all',
where: {
doc: {
equals: {
value: post.id,
relationTo: postsSlug,
},
},
},
pagination: false,
limit: 1,
depth: 0,
})
expect(postBeforeReindex?.slug).not.toBeFalsy()
const endpointRes = await restClient.POST(`/search/reindex`, {
body: JSON.stringify({
collections: [postsSlug],
}),
headers: {
Authorization: `JWT ${token}`,
},
})
expect(endpointRes.status).toBe(200)
const {
docs: [postAfterReindex],
} = await payload.find({
collection: 'search',
locale: 'all',
where: {
doc: {
equals: {
value: post.id,
relationTo: postsSlug,
},
},
},
pagination: false,
limit: 1,
depth: 0,
})
expect(postAfterReindex?.slug).not.toBeFalsy()
expect(postAfterReindex?.slug).toStrictEqual(postBeforeReindex?.slug)
})
it('should sync trashed documents correctly with search plugin', async () => {
// Create a published post
const publishedPost = await payload.create({
collection: postsSlug,
data: {
title: 'Post to be trashed',
excerpt: 'This post will be soft deleted',
_status: 'published',
},
})
// Wait for the search document to be created
await wait(200)
// Verify the search document was created
const { docs: initialSearchResults } = await payload.find({
collection: 'search',
depth: 0,
where: {
'doc.value': {
equals: publishedPost.id,
},
},
})
expect(initialSearchResults).toHaveLength(1)
expect(initialSearchResults[0]?.title).toBe('Post to be trashed')
// Soft delete the post (move to trash)
await payload.update({
collection: postsSlug,
id: publishedPost.id,
data: {
deletedAt: new Date().toISOString(),
},
})
// Wait for the search plugin to sync the trashed document
await wait(200)
// Verify the search document still exists but is properly synced
// The search document should remain and be updated correctly
const { docs: trashedSearchResults } = await payload.find({
collection: 'search',
depth: 0,
where: {
'doc.value': {
equals: publishedPost.id,
},
},
})
// The search document should still exist
expect(trashedSearchResults).toHaveLength(0)
// Clean up by permanently deleting the trashed post
await payload.delete({
collection: postsSlug,
id: publishedPost.id,
trash: true, // permanently delete
})
})
describe('locale filtering', () => {
it('should filter locales when skipSync excludes them', async () => {
// Test config has 3 locales: ['en', 'es', 'de']
// For 'filtered-locales' collection with syncEnglishOnly: true, only 'en' should be indexed
// Create a doc with syncEnglishOnly enabled
const enDoc = await payload.create({
collection: 'filtered-locales',
data: {
title: 'Filtered Doc',
syncEnglishOnly: true,
},
locale: 'en',
})
// Query for ALL search docs with locale: 'all' to see total count
const { docs: allSearchDocs } = await payload.find({
collection: 'search',
locale: 'all',
where: {
'doc.value': {
equals: enDoc.id,
},
},
})
// Should only have 1 search doc total (English only)
expect(allSearchDocs).toHaveLength(1)
expect(allSearchDocs[0]?.doc.relationTo).toBe('filtered-locales')
// Verify the search doc exists for English locale
const { docs } = await payload.find({
collection: 'search',
locale: 'all',
where: {
'doc.value': {
equals: enDoc.id,
},
},
})
expect(docs).toHaveLength(1)
const doc = docs[0]
expect(doc).toBeDefined()
expect(doc.doc.relationTo).toBe('filtered-locales')
expect(doc.title).toHaveProperty('en', 'Filtered Doc')
expect(doc.title).not.toHaveProperty('es')
expect(doc.title).not.toHaveProperty('de')
// Clean up
await payload.delete({
collection: 'filtered-locales',
id: enDoc.id,
})
})
it('should index all locales when skipSync allows all locales', async () => {
// Test config has 3 locales: ['en', 'es', 'de']
// For 'posts' collection, skipSync returns false for all locales
// Create a post
const post = await payload.create({
collection: postsSlug,
data: {
_status: 'published',
title: 'Test Post for All Locales',
},
locale: 'en',
})
// Update the post in Spanish locale
await payload.update({
collection: postsSlug,
id: post.id,
locale: 'es',
data: {
_status: 'published',
title: 'Test Post para Todos los Locales',
},
})
// Update the post in German locale
await payload.update({
collection: postsSlug,
id: post.id,
locale: 'de',
data: {
_status: 'published',
title: 'Testbeitrag für alle Sprachen',
},
})
// Query for search doc with locale: 'all'
const { docs: allSearchDocs } = await payload.find({
collection: 'search',
locale: 'all',
where: {
'doc.value': {
equals: post.id,
},
},
})
// Should have 1 search doc with all locales embedded
expect(allSearchDocs).toHaveLength(1)
expect(allSearchDocs[0]?.doc.relationTo).toBe(postsSlug)
// Verify all locales are present in the localized title field
expect(allSearchDocs[0]?.title).toHaveProperty('en', 'Test Post for All Locales')
expect(allSearchDocs[0]?.title).toHaveProperty('es', 'Test Post para Todos los Locales')
expect(allSearchDocs[0]?.title).toHaveProperty('de', 'Testbeitrag für alle Sprachen')
// Clean up
await payload.delete({
collection: postsSlug,
id: post.id,
})
})
it('should index all locales when syncEnglishOnly is false', async () => {
// For 'filtered-locales' collection with syncEnglishOnly: false, all locales should be indexed
// Create a doc with syncEnglishOnly disabled
const doc = await payload.create({
collection: 'filtered-locales',
data: {
title: 'Unfiltered Doc',
syncEnglishOnly: false,
},
locale: 'en',
})
// Verify search doc exists for English
const { docs: enSearchDocs } = await payload.find({
collection: 'search',
locale: 'en',
where: {
'doc.value': {
equals: doc.id,
},
},
})
expect(enSearchDocs).toHaveLength(1)
// Verify search doc exists for Spanish
const { docs: esSearchDocs } = await payload.find({
collection: 'search',
locale: 'es',
where: {
'doc.value': {
equals: doc.id,
},
},
})
expect(esSearchDocs).toHaveLength(1)
// Verify search doc exists for German
const { docs: deSearchDocs } = await payload.find({
collection: 'search',
locale: 'de',
where: {
'doc.value': {
equals: doc.id,
},
},
})
expect(deSearchDocs).toHaveLength(1)
// Clean up
await payload.delete({
collection: 'filtered-locales',
id: doc.id,
})
})
})
})