-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathint.spec.ts
More file actions
5802 lines (5067 loc) · 168 KB
/
int.spec.ts
File metadata and controls
5802 lines (5067 loc) · 168 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
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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable vitest/no-conditional-expect */
import type { MongooseAdapter } from '@payloadcms/db-mongodb'
import type { PostgresAdapter } from '@payloadcms/db-postgres'
import type { Table } from 'drizzle-orm'
import type {
DataFromCollectionSlug,
Payload,
PayloadRequest,
TypeWithID,
ValidationError,
} from 'payload'
import {
migrateRelationshipsV2_V3,
migrateVersionsV1_V2,
} from '@payloadcms/db-mongodb/migration-utils'
import { randomUUID } from 'crypto'
import * as drizzlePg from 'drizzle-orm/pg-core'
import * as drizzleSqlite from 'drizzle-orm/sqlite-core'
import fs from 'fs'
import mongoose, { Types } from 'mongoose'
import path from 'path'
import {
commitTransaction,
initTransaction,
isolateObjectProperty,
killTransaction,
QueryError,
} from 'payload'
import { assert } from 'ts-essentials'
import { fileURLToPath } from 'url'
import { afterAll, beforeAll, beforeEach, expect } from 'vitest'
import type { NextRESTClient } from '../__helpers/shared/NextRESTClient.js'
import type { Global2, Post } from './payload-types.js'
import { sanitizeQueryValue } from '../../packages/db-mongodb/src/queries/sanitizeQueryValue.js'
import { describe, it } from '../__helpers/int/vitest.js'
import { initPayloadInt } from '../__helpers/shared/initPayloadInt.js'
import { removeFiles } from '../__helpers/shared/removeFiles.js'
import { devUser } from '../credentials.js'
import { seed } from './seed.js'
import {
defaultValuesSlug,
errorOnUnnamedFieldsSlug,
fieldsPersistanceSlug,
postsSlug,
} from './shared.js'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
let payload: Payload
let user: Record<string, unknown> & TypeWithID
let token: string
let restClient: NextRESTClient
const collection = postsSlug
const title = 'title'
process.env.PAYLOAD_CONFIG_PATH = path.join(dirname, 'config.ts')
describe('database', () => {
beforeAll(async () => {
process.env.SEED_IN_CONFIG_ONINIT = 'false' // Makes it so the payload config onInit seed is not run. Otherwise, the seed would be run unnecessarily twice for the initial test run - once for beforeEach and once for onInit
;({ payload, restClient } = await initPayloadInt(dirname))
payload.db.migrationDir = path.join(dirname, './migrations')
await seed(payload)
await restClient.login({
slug: 'users',
credentials: devUser,
})
const loginResult = await payload.login({
collection: 'users',
data: {
email: devUser.email,
password: devUser.password,
},
})
user = loginResult.user
token = loginResult.token
})
afterAll(async () => {
await payload.destroy()
})
describe('id type', () => {
it('should sanitize incoming IDs if ID type is number', async () => {
const created = await restClient
.POST(`/posts`, {
body: JSON.stringify({
title: 'post to test that ID comes in as proper type',
}),
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => res.json())
const { doc: updated } = await restClient
.PATCH(`/posts/${created.doc.id}`, {
body: JSON.stringify({
title: 'hello',
}),
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((res) => res.json())
expect(updated.id).toStrictEqual(created.doc.id)
})
it('should create with generated ID text from hook', async () => {
const doc = await payload.create({
collection: 'custom-ids',
data: {},
})
expect(doc.id).toBeDefined()
})
it('should not create duplicate versions with custom id type', async () => {
const doc = await payload.create({
collection: 'custom-ids',
data: {
title: 'hey',
},
})
await payload.update({
id: doc.id,
collection: 'custom-ids',
data: {},
})
await payload.update({
id: doc.id,
collection: 'custom-ids',
data: {},
})
const versionsQuery = await payload.db.findVersions({
collection: 'custom-ids',
req: {} as PayloadRequest,
where: {
latest: {
equals: true,
},
'version.title': {
equals: 'hey',
},
},
})
expect(versionsQuery.totalDocs).toStrictEqual(1)
})
it('should not accidentally treat nested id fields as custom id', () => {
expect(payload.collections['fake-custom-ids'].customIDType).toBeUndefined()
})
it('should not overwrite supplied block and array row IDs on create', async () => {
const arrayRowID = '67648ed5c72f13be6eacf24e'
const blockID = '6764de9af79a863575c5f58c'
const doc = await payload.create({
collection: postsSlug,
data: {
arrayWithIDs: [
{
id: arrayRowID,
},
],
blocksWithIDs: [
{
id: blockID,
blockType: 'block-first',
},
],
title: 'test',
},
})
expect(doc.arrayWithIDs[0].id).toStrictEqual(arrayRowID)
expect(doc.blocksWithIDs[0].id).toStrictEqual(blockID)
})
it('should overwrite supplied block and array row IDs on duplicate', async () => {
const arrayRowID = '6764deb5201e9e36aeba3b6c'
const blockID = '6764dec58c68f337a758180c'
const doc = await payload.create({
collection: postsSlug,
data: {
arrayWithIDs: [
{
id: arrayRowID,
},
],
blocksWithIDs: [
{
id: blockID,
blockType: 'block-first',
},
],
title: 'test',
},
})
const duplicate = await payload.duplicate({
id: doc.id,
collection: postsSlug,
})
expect(duplicate.arrayWithIDs[0].id).not.toStrictEqual(arrayRowID)
expect(duplicate.blocksWithIDs[0].id).not.toStrictEqual(blockID)
})
it('should properly give the result with hasMany relationships with custom numeric IDs', async () => {
await payload.create({ collection: 'categories-custom-id', data: { id: 9999 } })
const res = await payload.create({
collection: 'posts',
data: { categoriesCustomID: [9999], title: 'post' },
depth: 0,
})
expect(res.categoriesCustomID[0]).toBe(9999)
const resFind = await payload.findByID({ id: res.id, collection: 'posts', depth: 0 })
expect(resFind.categoriesCustomID[0]).toBe(9999)
})
})
describe('timestamps', () => {
it('should have createdAt and updatedAt timestamps to the millisecond', async () => {
const result = await payload.create({
collection: postsSlug,
data: {
title: 'hello',
},
})
const createdAtDate = new Date(result.createdAt)
expect(createdAtDate.getMilliseconds()).toBeDefined()
// Cleanup, as this test suite does not use clearAndSeedEverything
await payload.db.deleteMany({
collection: postsSlug,
where: {},
})
})
it('should allow createdAt to be set in create', async () => {
const createdAt = new Date('2021-01-01T00:00:00.000Z').toISOString()
const result = await payload.create({
collection: postsSlug,
data: {
createdAt,
title: 'hello',
},
})
const doc = await payload.findByID({
id: result.id,
collection: postsSlug,
})
expect(result.createdAt).toStrictEqual(createdAt)
expect(doc.createdAt).toStrictEqual(createdAt)
// Cleanup, as this test suite does not use clearAndSeedEverything
await payload.db.deleteMany({
collection: postsSlug,
where: {},
})
})
it('should allow updatedAt to be set in create', async () => {
const updatedAt = new Date('2022-01-01T00:00:00.000Z').toISOString()
const result = await payload.create({
collection: postsSlug,
data: {
title: 'hello',
updatedAt,
},
})
expect(result.updatedAt).toStrictEqual(updatedAt)
// Cleanup, as this test suite does not use clearAndSeedEverything
await payload.db.deleteMany({
collection: postsSlug,
where: {},
})
})
it('should allow createdAt to be set in update', async () => {
const post = await payload.create({
collection: postsSlug,
data: {
title: 'hello',
},
})
const createdAt = new Date('2021-01-01T00:00:00.000Z').toISOString()
const result: any = await payload.db.updateOne({
id: post.id,
collection: postsSlug,
data: {
createdAt,
},
})
const doc = await payload.findByID({
id: result.id,
collection: postsSlug,
})
expect(doc.createdAt).toStrictEqual(createdAt)
// Cleanup, as this test suite does not use clearAndSeedEverything
await payload.db.deleteMany({
collection: postsSlug,
where: {},
})
})
it('should allow updatedAt to be set in update', async () => {
const post = await payload.create({
collection: postsSlug,
data: {
title: 'hello',
},
})
const updatedAt = new Date('2021-01-01T00:00:00.000Z').toISOString()
const result: any = await payload.db.updateOne({
id: post.id,
collection: postsSlug,
data: {
updatedAt,
},
})
const doc = await payload.findByID({
id: result.id,
collection: postsSlug,
})
expect(doc.updatedAt).toStrictEqual(updatedAt)
// Cleanup, as this test suite does not use clearAndSeedEverything
await payload.db.deleteMany({
collection: postsSlug,
where: {},
})
})
it('ensure updatedAt is automatically set when using db.updateOne', async () => {
const post = await payload.create({
collection: postsSlug,
data: {
title: 'hello',
},
})
const result: any = await payload.db.updateOne({
id: post.id,
collection: postsSlug,
data: {
title: 'hello2',
},
})
expect(result.updatedAt).not.toStrictEqual(post.updatedAt)
// Cleanup, as this test suite does not use clearAndSeedEverything
await payload.db.deleteMany({
collection: postsSlug,
where: {},
})
})
it('ensure updatedAt is not automatically set when using db.updateOne if it is explicitly set to `null`', async () => {
const post = await payload.create({
collection: postsSlug,
data: {
title: 'hello',
},
})
const result: any = await payload.db.updateOne({
id: post.id,
collection: postsSlug,
data: {
title: 'hello2',
updatedAt: null,
},
})
expect(result.updatedAt).toStrictEqual(post.updatedAt)
// Cleanup, as this test suite does not use clearAndSeedEverything
await payload.db.deleteMany({
collection: postsSlug,
where: {},
})
})
it('should allow createdAt to be set in updateVersion', async () => {
const category = await payload.create({
collection: 'categories',
data: {
title: 'hello',
},
})
await payload.update({
id: category.id,
collection: 'categories',
data: {
title: 'hello2',
},
})
const versions = await payload.findVersions({
collection: 'categories',
depth: 0,
sort: '-createdAt',
})
const createdAt = new Date('2021-01-01T00:00:00.000Z').toISOString()
for (const version of versions.docs) {
await payload.db.updateVersion({
id: version.id,
collection: 'categories',
versionData: {
...version.version,
createdAt,
},
})
}
const updatedVersions = await payload.findVersions({
collection: 'categories',
depth: 0,
sort: '-createdAt',
})
expect(updatedVersions.docs).toHaveLength(2)
for (const version of updatedVersions.docs) {
expect(version.createdAt).toStrictEqual(createdAt)
}
// Cleanup, as this test suite does not use clearAndSeedEverything
await payload.db.deleteMany({
collection: 'categories',
where: {},
})
await payload.db.deleteVersions({
collection: 'categories',
where: {},
})
})
it('should allow updatedAt to be set in updateVersion', async () => {
const category = await payload.create({
collection: 'categories',
data: {
title: 'hello',
},
})
await payload.update({
id: category.id,
collection: 'categories',
data: {
title: 'hello2',
},
})
const versions = await payload.findVersions({
collection: 'categories',
depth: 0,
sort: '-createdAt',
})
const updatedAt = new Date('2021-01-01T00:00:00.000Z').toISOString()
for (const version of versions.docs) {
await payload.db.updateVersion({
id: version.id,
collection: 'categories',
versionData: {
...version.version,
updatedAt,
},
})
}
const updatedVersions = await payload.findVersions({
collection: 'categories',
depth: 0,
sort: '-updatedAt',
})
expect(updatedVersions.docs).toHaveLength(2)
for (const version of updatedVersions.docs) {
expect(version.updatedAt).toStrictEqual(updatedAt)
}
// Cleanup, as this test suite does not use clearAndSeedEverything
await payload.db.deleteMany({
collection: 'categories',
where: {},
})
await payload.db.deleteVersions({
collection: 'categories',
where: {},
})
})
async function noTimestampsTestLocalAPI() {
const createdDoc: any = await payload.create({
collection: 'noTimeStamps',
data: {
title: 'hello',
},
})
expect(createdDoc.createdAt).toBeUndefined()
expect(createdDoc.updatedAt).toBeUndefined()
const updated: any = await payload.update({
id: createdDoc.id,
collection: 'noTimeStamps',
data: {
title: 'updated',
},
})
expect(updated.createdAt).toBeUndefined()
expect(updated.updatedAt).toBeUndefined()
const date = new Date('2021-01-01T00:00:00.000Z').toISOString()
const createdDocWithTimestamps: any = await payload.create({
collection: 'noTimeStamps',
data: {
createdAt: date,
title: 'hello',
updatedAt: date,
},
})
expect(createdDocWithTimestamps.createdAt).toBeUndefined()
expect(createdDocWithTimestamps.updatedAt).toBeUndefined()
const updatedDocWithTimestamps: any = await payload.update({
id: createdDocWithTimestamps.id,
collection: 'noTimeStamps',
data: {
createdAt: date,
title: 'updated',
updatedAt: date,
},
})
expect(updatedDocWithTimestamps.createdAt).toBeUndefined()
expect(updatedDocWithTimestamps.updatedAt).toBeUndefined()
}
async function noTimestampsTestDB(aa) {
const createdDoc: any = await payload.db.create({
collection: 'noTimeStamps',
data: {
title: 'hello',
},
})
expect(createdDoc.createdAt).toBeUndefined()
expect(createdDoc.updatedAt).toBeUndefined()
const updated: any = await payload.db.updateOne({
id: createdDoc.id,
collection: 'noTimeStamps',
data: {
title: 'updated',
},
})
expect(updated.createdAt).toBeUndefined()
expect(updated.updatedAt).toBeUndefined()
const date = new Date('2021-01-01T00:00:00.000Z').toISOString()
const createdDocWithTimestamps: any = await payload.db.create({
collection: 'noTimeStamps',
data: {
createdAt: date,
title: 'hello',
updatedAt: date,
},
})
expect(createdDocWithTimestamps.createdAt).toBeUndefined()
expect(createdDocWithTimestamps.updatedAt).toBeUndefined()
const updatedDocWithTimestamps: any = await payload.db.updateOne({
id: createdDocWithTimestamps.id,
collection: 'noTimeStamps',
data: {
createdAt: date,
title: 'updated',
updatedAt: date,
},
})
expect(updatedDocWithTimestamps.createdAt).toBeUndefined()
expect(updatedDocWithTimestamps.updatedAt).toBeUndefined()
}
// eslint-disable-next-line vitest/expect-expect
it('ensure timestamps are not created in update or create when timestamps are disabled', async () => {
await noTimestampsTestLocalAPI()
})
// eslint-disable-next-line vitest/expect-expect
it('ensure timestamps are not created in db adapter update or create when timestamps are disabled', async () => {
await noTimestampsTestDB(true)
})
// eslint-disable-next-line vitest/expect-expect
it(
'ensure timestamps are not created in update or create when timestamps are disabled even with allowAdditionalKeys true',
{ db: 'mongo' },
async () => {
const originalAllowAdditionalKeys = payload.db.allowAdditionalKeys
payload.db.allowAdditionalKeys = true
await noTimestampsTestLocalAPI()
payload.db.allowAdditionalKeys = originalAllowAdditionalKeys
},
)
// eslint-disable-next-line vitest/expect-expect
it(
'ensure timestamps are not created in db adapter update or create when timestamps are disabled even with allowAdditionalKeys true',
{ db: 'mongo' },
async () => {
const originalAllowAdditionalKeys = payload.db.allowAdditionalKeys
payload.db.allowAdditionalKeys = true
await noTimestampsTestDB()
payload.db.allowAdditionalKeys = originalAllowAdditionalKeys
},
)
})
describe('Data strictness', () => {
it('should not save and leak password, confirm-password from Local API', async () => {
const createdUser = await payload.create({
collection: 'users',
data: {
password: 'some-password',
// @ts-expect-error
'confirm-password': 'some-password',
email: 'user1@payloadcms.com',
},
})
let keys = Object.keys(createdUser)
expect(keys).not.toContain('password')
expect(keys).not.toContain('confirm-password')
const foundUser = await payload.findByID({ id: createdUser.id, collection: 'users' })
keys = Object.keys(foundUser)
expect(keys).not.toContain('password')
expect(keys).not.toContain('confirm-password')
})
it('should not save and leak password, confirm-password from payload.db', async () => {
const createdUser = await payload.db.create({
collection: 'users',
data: {
'confirm-password': 'some-password',
email: 'user2@payloadcms.com',
password: 'some-password',
},
})
let keys = Object.keys(createdUser)
expect(keys).not.toContain('password')
expect(keys).not.toContain('confirm-password')
const foundUser = await payload.db.findOne({
collection: 'users',
where: { id: createdUser.id },
})
keys = Object.keys(foundUser)
expect(keys).not.toContain('password')
expect(keys).not.toContain('confirm-password')
})
})
it('should query hasMany select field with contains operator', async () => {
const { id } = await payload.create({
collection: 'select-has-many',
data: {
roles: ['admin'],
},
})
const result = await payload.find({
collection: 'select-has-many',
where: {
roles: {
contains: 'admin',
},
},
})
expect(result.docs).toHaveLength(1)
expect(result.docs.some((doc) => doc.id === id)).toBe(true)
await payload.delete({ collection: 'select-has-many', id })
})
it('ensure querying hasMany select field with contains operator does not do partial matching', async () => {
const { id } = await payload.create({
collection: 'select-has-many',
data: {
food: ['bananabread'],
},
})
const result = await payload.find({
collection: 'select-has-many',
where: {
food: {
contains: 'banana',
},
},
})
expect(result.docs).toHaveLength(0)
await payload.delete({ collection: 'select-has-many', id })
})
describe('allow ID on create', () => {
beforeAll(() => {
payload.db.allowIDOnCreate = true
payload.config.db.allowIDOnCreate = true
})
afterAll(() => {
payload.db.allowIDOnCreate = false
payload.config.db.allowIDOnCreate = false
})
it('local API - accepts ID on create', async () => {
let id: any = null
if (payload.db.name === 'mongoose') {
id = new mongoose.Types.ObjectId().toHexString()
} else if (payload.db.idType === 'uuid') {
id = randomUUID()
} else {
id = 9999
}
const post = await payload.create({ collection: 'posts', data: { id, title: 'created' } })
expect(post.id).toBe(id)
})
it('rEST API - accepts ID on create', async () => {
let id: any = null
if (payload.db.name === 'mongoose') {
id = new mongoose.Types.ObjectId().toHexString()
} else if (payload.db.idType === 'uuid') {
id = randomUUID()
} else {
id = 99999
}
const response = await restClient.POST(`/posts`, {
body: JSON.stringify({
id,
title: 'created',
}),
})
const post = await response.json()
expect(post.doc.id).toBe(id)
})
it('graphQL - accepts ID on create', async () => {
let id: any = null
if (payload.db.name === 'mongoose') {
id = new mongoose.Types.ObjectId().toHexString()
} else if (payload.db.idType === 'uuid') {
id = randomUUID()
} else {
id = 999999
}
const query = `mutation {
createPost(data: {title: "created", id: ${typeof id === 'string' ? `"${id}"` : id}}) {
id
title
}
}`
const res = await restClient
.GRAPHQL_POST({ body: JSON.stringify({ query }) })
.then((res) => res.json())
const doc = res.data.createPost
expect(doc).toMatchObject({ id, title: 'created' })
expect(doc.id).toBe(id)
})
})
it('should find distinct field values of the collection', async () => {
await payload.delete({ collection: 'posts', where: {} })
const titles = [
'title-1',
'title-2',
'title-3',
'title-4',
'title-5',
'title-6',
'title-7',
'title-8',
'title-9',
].map((title) => ({ title }))
for (const { title } of titles) {
const docsCount = Math.random() > 0.5 ? 3 : Math.random() > 0.5 ? 2 : 1
for (let i = 0; i < docsCount; i++) {
await payload.create({ collection: 'posts', data: { title } })
}
}
const res = await payload.findDistinct({
collection: 'posts',
field: 'title',
})
expect(res.values).toStrictEqual(titles)
const resLimit = await payload.findDistinct({
collection: 'posts',
field: 'title',
limit: 3,
})
expect(resLimit.values).toStrictEqual(
['title-1', 'title-2', 'title-3'].map((title) => ({ title })),
)
// count is still 9
expect(resLimit.totalDocs).toBe(9)
const resDesc = await payload.findDistinct({
collection: 'posts',
field: 'title',
sort: '-title',
})
expect(resDesc.values).toStrictEqual(titles.toReversed())
const resAscDefault = await payload.findDistinct({
collection: 'posts',
field: 'title',
})
expect(resAscDefault.values).toStrictEqual(titles)
})
it('should sort find on a different field with findDistinct', async () => {
await payload.delete({ collection: 'posts', where: {} })
const titles: {
title: string
}[] = [
'title-1',
'title-2',
'title-3',
'title-4',
'title-5',
'title-6',
'title-7',
'title-8',
'title-9',
].map((title) => ({ title }))
const numbers = [42, 7, 3, 19, 73, 8, 100, 1, 56]
const titlesSortedByNumber = titles.toSorted(
(a, b) => numbers[titles.indexOf(a)]! - numbers[titles.indexOf(b)]!,
)
for (const entry of titles) {
const docsCount = Math.random() > 0.5 ? 3 : Math.random() > 0.5 ? 2 : 1
for (let i = 0; i < docsCount; i++) {
await payload.create({
collection: 'posts',
data: {
number: numbers[titles.indexOf(entry)]! + Math.random(),
title: entry.title,
},
})
}
}
const resDesc = await payload.findDistinct({
collection: 'posts',
field: 'title',
sort: '-number',
})
const resAsc = await payload.findDistinct({
collection: 'posts',
field: 'title',
sort: 'number',
})
const reversed = titlesSortedByNumber.toReversed()
expect(resAsc.values).toStrictEqual(titlesSortedByNumber)
expect(resDesc.values).toStrictEqual(reversed)
})
it('should populate distinct relationships when depth>0', async () => {
await payload.delete({ collection: 'posts', where: {} })
const categories = ['category-1', 'category-2', 'category-3', 'category-4'].map((title) => ({
title,
}))
const categoriesIDS: { category: string }[] = []
for (const { title } of categories) {
const doc = await payload.create({ collection: 'categories', data: { title } })
categoriesIDS.push({ category: doc.id })
}
for (const { category } of categoriesIDS) {
const docsCount = Math.random() > 0.5 ? 3 : Math.random() > 0.5 ? 2 : 1
for (let i = 0; i < docsCount; i++) {
await payload.create({ collection: 'posts', data: { category, title: randomUUID() } })
}
}
const resultDepth0 = await payload.findDistinct({
collection: 'posts',
field: 'category',
sort: 'category.title',
})
expect(resultDepth0.values).toStrictEqual(categoriesIDS)
const resultDepth1 = await payload.findDistinct({
collection: 'posts',
depth: 1,
field: 'category',
sort: 'category.title',
})
for (let i = 0; i < resultDepth1.values.length; i++) {
const fromRes = resultDepth1.values[i] as any
const id = categoriesIDS[i].category as any
const title = categories[i]?.title
expect(fromRes.category.title).toBe(title)
expect(fromRes.category.id).toBe(id)
}
})
it('should populate distinct relationships of hasMany: true when depth>0', async () => {
await payload.delete({ collection: 'posts', where: {} })
await payload.delete({ collection: 'categories', where: {} })
const categories = ['category-1', 'category-2', 'category-3', 'category-4'].map((title) => ({
title,
}))
const categoriesIDS: { categories: string }[] = []
for (const { title } of categories) {
const doc = await payload.create({ collection: 'categories', data: { title } })
categoriesIDS.push({ categories: doc.id })
}
await payload.create({
collection: 'posts',
data: {
categories: [categoriesIDS[0]?.categories, categoriesIDS[1]?.categories],
title: '1',
},
})
await payload.create({
collection: 'posts',
data: {
categories: [
categoriesIDS[0]?.categories,
categoriesIDS[2]?.categories,
categoriesIDS[3]?.categories,
],
title: '2',
},
})