-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathsources.ts
4078 lines (3744 loc) · 112 KB
/
sources.ts
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
import { randomUUID } from 'crypto';
import { DataSource, In, Not } from 'typeorm';
import { updateFlagsStatement, WELCOME_POST_TITLE } from '../src/common';
import { isNullOrUndefined } from '../src/common/object';
import createOrGetConnection from '../src/db';
import {
defaultPublicSourceFlags,
Feed,
NotificationPreferenceSource,
Post,
PostKeyword,
PostType,
SharePost,
Source,
SourceFeed,
SourceMember,
SourceType,
SquadPublicRequest,
SquadPublicRequestStatus,
SquadSource,
User,
WelcomePost,
} from '../src/entity';
import { DisallowHandle } from '../src/entity/DisallowHandle';
import { SourceCategory } from '../src/entity/sources/SourceCategory';
import { SourceTagView } from '../src/entity/SourceTagView';
import { SourcePermissionErrorKeys } from '../src/errors';
import { NotificationType } from '../src/notifications/common';
import { SourceMemberRoles, sourceRoleRank } from '../src/roles';
import { SourcePermissions } from '../src/schema/sources';
import { postKeywordsFixture, postsFixture } from './fixture/post';
import { createSource, sourcesFixture } from './fixture/source';
import { usersFixture } from './fixture/user';
import {
disposeGraphQLTesting,
GraphQLTestClient,
GraphQLTestingState,
initializeGraphQLTesting,
MockContext,
saveFixtures,
testMutationError,
testMutationErrorCode,
testQueryErrorCode,
} from './helpers';
import { ContentPreferenceSource } from '../src/entity/contentPreference/ContentPreferenceSource';
import { ContentPreferenceStatus } from '../src/entity/contentPreference/types';
import { generateUUID } from '../src/ids';
import {
SourcePostModeration,
SourcePostModerationStatus,
} from '../src/entity/SourcePostModeration';
let con: DataSource;
let state: GraphQLTestingState;
let client: GraphQLTestClient;
let loggedUser: string = null;
beforeAll(async () => {
con = await createOrGetConnection();
state = await initializeGraphQLTesting(
() => new MockContext(con, loggedUser),
);
client = state.client;
});
const getSourceCategories = () => [
{
title: 'Basics',
enabled: true,
},
{
title: 'Web',
enabled: true,
},
{
title: 'Mobile',
enabled: true,
},
{
title: 'Games',
enabled: true,
},
{
title: 'DevOps & Cloud',
enabled: true,
},
{
title: 'Open Source',
enabled: true,
},
{
title: 'Career',
enabled: true,
},
{
title: 'AI',
enabled: true,
},
{
title: 'Fun',
enabled: true,
},
{
title: 'DevTools',
enabled: true,
},
{
title: 'DevRel',
enabled: true,
},
];
beforeEach(async () => {
loggedUser = null;
await saveFixtures(con, SourceCategory, getSourceCategories());
await saveFixtures(con, Source, [
sourcesFixture[0],
sourcesFixture[1],
sourcesFixture[5],
sourcesFixture[6],
]);
await saveFixtures(con, User, usersFixture);
await saveFixtures(
con,
Feed,
usersFixture.map((user) => ({ userId: user.id, id: user.id })),
);
await con
.getRepository(Source)
.update({ id: In(['a', 'b', 'c', 'squad']) }, { type: SourceType.Squad });
const now = new Date(2022, 11, 19);
await con.getRepository(SourceMember).save([
{
userId: '1',
sourceId: 'a',
role: SourceMemberRoles.Member,
referralToken: 'rt',
createdAt: new Date(now.getTime() + 0),
},
{
userId: '2',
sourceId: 'a',
role: SourceMemberRoles.Member,
referralToken: randomUUID(),
createdAt: new Date(now.getTime() + 1000),
},
{
userId: '2',
sourceId: 'b',
role: SourceMemberRoles.Member,
referralToken: randomUUID(),
createdAt: new Date(now.getTime() + 2000),
},
{
userId: '3',
sourceId: 'b',
role: SourceMemberRoles.Member,
referralToken: randomUUID(),
createdAt: new Date(now.getTime() + 3000),
},
{
userId: '1',
sourceId: 'squad',
role: SourceMemberRoles.Member,
referralToken: randomUUID(),
createdAt: new Date(now.getTime() + 4000),
},
{
userId: '1',
sourceId: 'm',
role: SourceMemberRoles.Admin,
referralToken: randomUUID(),
createdAt: new Date(now.getTime() + 5000),
},
]);
await con.getRepository(SourceMember).update(
{
userId: '1',
},
{ role: SourceMemberRoles.Admin },
);
await con
.getRepository(SourceMember)
.update({ userId: '2', sourceId: 'b' }, { role: SourceMemberRoles.Admin });
});
afterAll(() => disposeGraphQLTesting(state));
describe('query sourceCategory', () => {
const QUERY = `
query SourceCategory($id: String!) {
sourceCategory(id: $id) {
id
slug
title
}
}
`;
it('should return NOT_FOUND when category does not exist', async () => {
loggedUser = '1';
const uuid = randomUUID();
return testQueryErrorCode(
client,
{ query: QUERY, variables: { id: uuid } },
'NOT_FOUND',
);
});
it('should return source category by id', async () => {
loggedUser = '1';
const [category] = await con.getRepository(SourceCategory).find();
const res = await client.query(QUERY, { variables: { id: category.id } });
expect(res.errors).toBeFalsy();
expect(res.data.sourceCategory.id).toEqual(category.id);
expect(res.data.sourceCategory.title).toEqual(category.title);
});
it('should return source category by slug', async () => {
loggedUser = '1';
const res = await client.query(QUERY, {
variables: { id: 'web' },
});
expect(res.errors).toBeFalsy();
expect(res.data.sourceCategory.title).toEqual('Web');
expect(res.data.sourceCategory.slug).toEqual('web');
});
it('should return source category by id as anonymous user', async () => {
const [category] = await con.getRepository(SourceCategory).find();
const res = await client.query(QUERY, { variables: { id: category.id } });
expect(res.errors).toBeFalsy();
expect(res.data.sourceCategory.id).toEqual(category.id);
expect(res.data.sourceCategory.title).toEqual(category.title);
});
});
describe('query sourceCategories', () => {
const QUERY = `
query SourceCategories($first: Int, $after: String) {
sourceCategories(first: $first, after: $after) {
pageInfo {
endCursor
hasNextPage
}
edges {
node {
id
slug
title
}
}
}
}
`;
it('should return source categories', async () => {
loggedUser = '1';
const res = await client.query(QUERY);
expect(res.errors).toBeFalsy();
const categories = getSourceCategories();
const isAllFound = res.data.sourceCategories.edges.every(({ node }) =>
categories.some((category) => category.title === node.title),
);
expect(isAllFound).toBeTruthy();
});
it('should return source categories as an anonymous user', async () => {
const res = await client.query(QUERY);
expect(res.errors).toBeFalsy();
const categories = getSourceCategories();
const isAllFound = res.data.sourceCategories.edges.every(({ node }) =>
categories.some((category) => category.title === node.title),
);
expect(isAllFound).toBeTruthy();
});
it('should return categories ordered by priority', async () => {
await con.createQueryRunner().query(`
DO $$
DECLARE
categories TEXT[] := ARRAY['Basics','Web','Mobile','DevOps & Cloud','AI','Games','DevTools','Career','Open Source','DevRel','Fun'];
i INT;
BEGIN
-- Iterate over the array and update the table
FOR i IN 1..array_length(categories, 1) LOOP
UPDATE source_category
SET priority = i
WHERE slug = trim(BOTH '-' FROM regexp_replace(lower(trim(COALESCE(LEFT(categories[i],100),''))), '[^a-z0-9-]+', '-', 'gi'));
END LOOP;
END $$;
`);
const expected = [
'Basics',
'Web',
'Mobile',
'DevOps & Cloud',
'AI',
'Games',
'DevTools',
'Career',
'Open Source',
'DevRel',
'Fun',
];
loggedUser = '1';
const res = await client.query(QUERY);
expect(res.errors).toBeFalsy();
const mapped = res.data.sourceCategories.edges.map(
({ node }) => node.title,
);
expect(mapped).toEqual(expected);
});
});
describe('query sources', () => {
interface Props {
first: number;
featured: boolean;
filterOpenSquads: boolean;
categoryId: string;
sortByMembersCount: boolean;
}
const QUERY = ({
first = 10,
filterOpenSquads = false,
featured,
categoryId,
sortByMembersCount,
}: Partial<Props> = {}): string => `{
sources(
first: ${first},
filterOpenSquads: ${filterOpenSquads}
${isNullOrUndefined(featured) ? '' : `, featured: ${featured}`}
${isNullOrUndefined(categoryId) ? '' : `, categoryId: "${categoryId}"`}
${isNullOrUndefined(sortByMembersCount) ? '' : `, sortByMembersCount: ${sortByMembersCount}`}
) {
pageInfo {
endCursor
hasNextPage
}
edges {
node {
id
name
image
headerImage
public
type
color
flags {
featured
totalMembers
}
category {
id
}
}
}
}
}`;
it('should return only public sources', async () => {
const res = await client.query(
QUERY({ first: 10, filterOpenSquads: true }),
);
const isPublic = res.data.sources.edges.every(({ node }) => !!node.public);
expect(isPublic).toBeTruthy();
});
it('should filter by category', async () => {
const repo = con.getRepository(Source);
const anyOther = await con
.getRepository(SourceCategory)
.findOneByOrFail({ title: Not('Web') });
const web = await con
.getRepository(SourceCategory)
.findOneByOrFail({ title: 'Web' });
await repo.update({ id: 'a' }, { categoryId: anyOther.id });
await repo.update({ id: 'b' }, { categoryId: web.id });
const res = await client.query(QUERY({ first: 10, categoryId: web.id }));
const isAllWeb = res.data.sources.edges.every(
({ node }) => node.category.id === web.id,
);
expect(isAllWeb).toBeTruthy();
});
const prepareFeaturedTests = async () => {
const repo = con.getRepository(Source);
await repo.update(
{ id: 'a' },
{
flags: updateFlagsStatement({ featured: true, publicThreshold: true }),
},
);
await repo.update(
{ id: 'b' },
{
flags: updateFlagsStatement({ featured: false, publicThreshold: true }),
},
);
};
it('should return only featured sources', async () => {
await prepareFeaturedTests();
const res = await client.query(
QUERY({ first: 10, filterOpenSquads: false, featured: true }),
);
const isFeatured = res.data.sources.edges.every(
({ node }) => !!node.flags.featured,
);
expect(isFeatured).toBeTruthy();
});
it('should return public squads that passes the threshold', async () => {
await prepareFeaturedTests();
await con.getRepository(Source).update(
{ id: 'a' },
{
type: SourceType.Squad,
private: false,
flags: updateFlagsStatement<Source>({ publicThreshold: false }),
},
);
const res = await client.query(
QUERY({ first: 10, filterOpenSquads: true }),
);
const passedThreshold = res.data.sources.edges.map(({ node }) => node.id);
expect(passedThreshold).toEqual(expect.arrayContaining(['b']));
});
it('should return only non-featured sources - this means when flag is false or undefined', async () => {
await prepareFeaturedTests();
await con.getRepository(Source).save(sourcesFixture[2]);
await con.getRepository(Source).update(
{ id: 'c' },
{
type: SourceType.Squad,
private: false,
flags: updateFlagsStatement({ publicThreshold: true }),
},
);
const res = await client.query(
QUERY({ first: 10, filterOpenSquads: true, featured: false }),
);
expect(res.data.sources.edges.length).toEqual(2);
});
it('should return only not featured sources', async () => {
await prepareFeaturedTests();
const res = await client.query(
QUERY({
first: 10,
filterOpenSquads: false,
featured: false,
}),
);
const isNotFeatured = res.data.sources.edges.every(
({ node }) => !node.flags.featured,
);
expect(isNotFeatured).toBeTruthy();
});
it('should flag that more pages available', async () => {
const res = await client.query(QUERY({ first: 1 }));
expect(res.data.sources.pageInfo.hasNextPage).toBeTruthy();
});
it('should return only active sources', async () => {
await con.getRepository(Source).save([
{
id: 'd',
active: false,
name: 'D',
image: 'http://d.com',
handle: 'd',
},
]);
const res = await client.query(QUERY());
const isActive = res.data.sources.edges.every(
({ node }) => node.id !== 'd',
);
expect(isActive).toBeTruthy();
});
const prepareSquads = async () => {
const repo = con.getRepository(Source);
const res = await client.query(
QUERY({ first: 10, filterOpenSquads: true }),
);
expect(res.errors).toBeFalsy();
await repo.update(
{ id: In(['a', 'b']) },
{
type: SourceType.Squad,
private: true,
flags: updateFlagsStatement({ publicThreshold: true }),
},
);
await repo.update(
{ id: 'b' },
{
private: false,
flags: updateFlagsStatement({ publicThreshold: true }),
},
);
};
it('should return only public squads', async () => {
await prepareSquads();
const res = await client.query(
QUERY({ first: 10, filterOpenSquads: true }),
);
expect(res.errors).toBeFalsy();
expect(res.data.sources.edges.length).toEqual(1);
const allSquad = res.data.sources.edges.every(
({ node }) => node.type === SourceType.Squad && node.public === true,
);
expect(allSquad).toBeTruthy();
});
it('should return public squad color and headerImage', async () => {
await prepareSquads();
const res = await client.query(
QUERY({ first: 10, filterOpenSquads: true }),
);
expect(res.errors).toBeFalsy();
expect(res.data.sources.edges.length).toEqual(1);
expect(res.data.sources.edges[0].node.public).toBeTruthy();
expect(res.data.sources.edges[0].node.color).toEqual('avocado');
expect(res.data.sources.edges[0].node.headerImage).toEqual(
'http://image.com/header',
);
});
const saveMembers = (sourceId: string, users: string[]) => {
const repo = con.getRepository(SourceMember);
const now = new Date();
const members = users.map((userId, index) =>
repo.create({
userId,
sourceId,
referralToken: randomUUID(),
role: SourceMemberRoles.Member,
createdAt: new Date(now.getTime() + 1000 * index),
}),
);
return repo.save(members);
};
it('should return public squads ordered by members count', async () => {
await prepareSquads();
await saveFixtures(con, Source, [sourcesFixture[2]]);
await con.getRepository(SourceMember).delete({ sourceId: Not('null') });
await con.getRepository(Source).update(
{ id: Not('null') },
{
type: SourceType.Squad,
flags: updateFlagsStatement({ totalMembers: 0 }),
},
);
await saveMembers('a', ['3']);
await saveMembers('b', ['1', '2']);
await saveMembers('c', ['1', '2', '3', '4']);
const query = QUERY({ first: 10, sortByMembersCount: true });
const res = await client.query(query);
expect(res.errors).toBeFalsy();
expect(
res.data.sources.edges
.filter(({ node }) => ['a', 'b', 'c'].includes(node.id))
.map(({ node }) => node.id),
).toEqual(['c', 'b', 'a']);
});
it('should not order by members count without the right parameter', async () => {
await prepareSquads();
await saveFixtures(con, Source, [sourcesFixture[2]]);
await con.getRepository(SourceMember).delete({ sourceId: Not('null') });
await saveMembers('a', ['3']);
await saveMembers('b', ['1']);
await saveMembers('c', ['1', '2', '3', '4']);
const query = QUERY({ first: 10 });
const res = await client.query(query);
expect(res.errors).toBeFalsy();
expect(res.data.sources.edges.map(({ node }) => node.id)).toEqual(
expect.arrayContaining(['c', 'squad', 'm', 'a', 'b']),
);
});
});
describe('query searchSources', () => {
const QUERY = `
query SearchSources($query: String!) {
searchSources(query: $query) {
id
name
image
}
}`;
it('should return matching sources', async () => {
await con.getRepository(Source).insert([
{
...sourcesFixture[0],
id: 'search1',
handle: 'search_1',
},
{
...sourcesFixture[1],
id: 'search2',
handle: 'search_2',
},
]);
const res = await client.query(QUERY, { variables: { query: 'sea' } });
expect(res.errors).toBeFalsy();
expect(res.data.searchSources).toEqual([
{ id: 'search1', name: 'A', image: 'http://image.com/a' },
{ id: 'search2', name: 'B', image: 'http://image.com/b' },
]);
});
});
describe('query sourceRecommendationByTags', () => {
beforeEach(async () => {
await con
.getRepository(Post)
.save([postsFixture[0], postsFixture[1], postsFixture[4]]);
await con.getRepository(PostKeyword).save([
postKeywordsFixture[0],
postKeywordsFixture[1],
postKeywordsFixture[5],
postKeywordsFixture[6],
{
postId: postsFixture[1].id,
keyword: 'javascript',
},
]);
await con.manager.query(`UPDATE post_keyword
SET status = 'allow'`);
const materializedViewName =
con.getRepository(SourceTagView).metadata.tableName;
await con.query(`REFRESH MATERIALIZED VIEW ${materializedViewName}`);
});
const QUERY = `
query SourceRecommendationByTags($tags: [String]!) {
sourceRecommendationByTags(tags: $tags) {
id
name
image
}
}`;
it('should return matching sources', async () => {
const res = await client.query(QUERY, {
variables: { tags: ['javascript', 'html'] },
});
expect(res.errors).toBeFalsy();
expect(res.data.sourceRecommendationByTags).toEqual([
{ id: 'b', name: 'B', image: 'http://image.com/b' },
{ id: 'a', name: 'A', image: 'http://image.com/a' },
]);
});
it('should return matching sources excluding private sources', async () => {
await con.getRepository(Source).update({ id: 'b' }, { private: true });
const res = await client.query(QUERY, {
variables: { tags: ['javascript', 'html'] },
});
expect(res.errors).toBeFalsy();
expect(res.data.sourceRecommendationByTags).toEqual([
{ id: 'a', name: 'A', image: 'http://image.com/a' },
]);
});
});
describe('query mostRecentSources', () => {
const QUERY = `
query MostRecentSources {
mostRecentSources {
id
name
image
public
}
}
`;
it('should return most recent sources', async () => {
await con
.getRepository(Source)
.update({ id: In(['a', 'b']) }, { type: SourceType.Machine });
const res = await client.query(QUERY);
expect(res.errors).toBeFalsy();
expect(res.data.mostRecentSources).toEqual(
expect.arrayContaining([
{ id: 'a', name: 'A', image: 'http://image.com/a', public: true },
{ id: 'b', name: 'B', image: 'http://image.com/b', public: true },
]),
);
});
});
describe('query trendingSources', () => {
const QUERY = `
query TrendingSources {
trendingSources {
id
name
image
public
}
}
`;
it('should return most trending sources', async () => {
await con.getRepository(Post).save(
new Array(5).fill('a').map((item, index) => {
return {
id: `post_${index}`,
shortId: `post_${index}`,
title: `Post ${index}`,
tagsStr: 'tag1',
upvotes: 10 + index,
createdAt: new Date(),
sourceId: 'a',
};
}),
);
await con.getRepository(Post).save({
id: `post_6`,
shortId: `post_6`,
title: `Post 6`,
tagsStr: 'tag1',
upvotes: 10,
createdAt: new Date(),
sourceId: 'b',
});
await con.query(`REFRESH MATERIALIZED VIEW trending_post`);
await con.query(`REFRESH MATERIALIZED VIEW trending_source`);
const res = await client.query(QUERY);
expect(res.errors).toBeFalsy();
expect(res.data).toMatchObject({
trendingSources: [
{ id: 'a', name: 'A', image: 'http://image.com/a', public: true },
],
});
});
});
describe('query popularSources', () => {
const QUERY = `
query PopularSources {
popularSources {
id
name
image
public
}
}
`;
it('should return most popular sources', async () => {
await con.getRepository(Post).save(
new Array(6).fill('a').map((item, index) => {
return {
id: `post_${index}`,
shortId: `post_${index}`,
title: `Post ${index}`,
tagsStr: 'tag1',
upvotes: 10 + index,
createdAt: new Date(),
sourceId: 'a',
};
}),
);
await con.getRepository(Post).save(
new Array(5).fill('b').map((item, index) => {
return {
id: `post_${index}`,
shortId: `post_${index}`,
title: `Post ${index}`,
tagsStr: 'tag1',
upvotes: 10 + index,
createdAt: new Date(),
sourceId: 'a',
};
}),
);
await con.query(`REFRESH MATERIALIZED VIEW popular_post`);
await con.query(`REFRESH MATERIALIZED VIEW popular_source`);
const res = await client.query(QUERY);
expect(res.errors).toBeFalsy();
expect(res.data).toMatchObject({
popularSources: [
{ id: 'a', name: 'A', image: 'http://image.com/a', public: true },
],
});
});
});
describe('query topVideoSources', () => {
const QUERY = `
query TopVideoSources {
topVideoSources {
id
name
image
public
}
}
`;
it('should return top video sources', async () => {
await con.getRepository(Post).save(
new Array(6).fill('a').map((item, index) => {
return {
id: `post_a_${index}`,
shortId: `post_a_${index}`,
title: `Post ${index}`,
tagsStr: 'tag1',
upvotes: 10 + index,
createdAt: new Date(),
sourceId: 'a',
type: PostType.VideoYouTube,
};
}),
);
await con.getRepository(Post).save(
new Array(6).fill('b').map((item, index) => {
return {
id: `post_b_${index}`,
shortId: `post_b_${index}`,
title: `Post ${index}`,
tagsStr: 'tag1',
upvotes: 10 + index,
createdAt: new Date(),
sourceId: 'b',
};
}),
);
await con.query(`REFRESH MATERIALIZED VIEW popular_video_post`);
await con.query(`REFRESH MATERIALIZED VIEW popular_video_source`);
const res = await client.query(QUERY);
expect(res.errors).toBeFalsy();
expect(res.data).toMatchObject({
topVideoSources: [
{ id: 'a', name: 'A', image: 'http://image.com/a', public: true },
],
});
});
});
describe('query sourceByFeed', () => {
const QUERY = `
query SourceByFeed($data: String!) {
sourceByFeed(feed: $data) {
id
name
image
public
}
}`;
it('should not authorize when not logged in', () =>
testQueryErrorCode(
client,
{ query: QUERY, variables: { data: 'https://a.com/feed' } },
'UNAUTHENTICATED',
));
it('should return null when feed does not exist', async () => {
loggedUser = '1';
const res = await client.query(QUERY, {
variables: { data: 'https://a.com/feed' },
});
expect(res.errors).toBeFalsy();
expect(res.data.sourceByFeed).toEqual(null);
});
it('should return the source', async () => {
loggedUser = '1';
await con.getRepository(SourceFeed).save({
feed: 'https://a.com/feed',
sourceId: 'a',
});
const res = await client.query(QUERY, {
variables: { data: 'https://a.com/feed' },
});
expect(res.errors).toBeFalsy();
expect(res.data.sourceByFeed).toEqual({
id: 'a',
name: 'A',
image: 'http://image.com/a',
public: true,
});
});
});
describe('query source current member', () => {
const QUERY = `
query Source($id: ID!) {
source(id: $id) {
id
currentMember {
role
roleRank
permissions
}
}
}
`;
it('should return null for annonymous users', async () => {
const res = await client.query(QUERY, { variables: { id: 'a' } });
expect(res.data).toMatchSnapshot();
});
it(`should return null for user that's not in the source`, async () => {
loggedUser = '3';
const res = await client.query(QUERY, { variables: { id: 'a' } });
expect(res.data).toMatchSnapshot();
});
it('should return current member as admin', async () => {
loggedUser = '1';
await con
.getRepository(SourceMember)
.update({ userId: '1' }, { role: SourceMemberRoles.Admin });
const res = await client.query(QUERY, { variables: { id: 'a' } });
expect(res.data).toMatchSnapshot();
});
it('should return current member as member', async () => {
loggedUser = '1';
await con
.getRepository(SourceMember)
.update({ userId: '1' }, { role: SourceMemberRoles.Member });
const res = await client.query(QUERY, { variables: { id: 'a' } });
expect(res.data).toMatchSnapshot();
});
it('should return current member as blocked', async () => {
loggedUser = '1';
await con
.getRepository(SourceMember)
.update({ userId: '1' }, { role: SourceMemberRoles.Blocked });
const res = await client.query(QUERY, { variables: { id: 'a' } });
expect(res.data.source).toBeNull();
});
it('should not return post permission in case memberPostingRank is set above user roleRank', async () => {
loggedUser = '1';
await con.getRepository(SquadSource).save({
id: 'restrictedsquad1',
handle: 'restrictedsquad1',
name: 'Restricted Squad',
memberPostingRank: sourceRoleRank[SourceMemberRoles.Moderator],
});
await con.getRepository(SourceMember).save({
userId: '1',
sourceId: 'restrictedsquad1',
role: SourceMemberRoles.Member,
referralToken: 'restrictedsquadtoken',
createdAt: new Date(2022, 11, 19),
});
const res = await client.query(QUERY, {
variables: { id: 'restrictedsquad1' },
});
expect(
res.data.source.currentMember.permissions.includes(
SourcePermissions.Post,
),
).toBe(false);
});
it('should not return invite permission in case memberInviteRank is set above user roleRank', async () => {
loggedUser = '1';
await con.getRepository(SquadSource).save({
id: 'restrictedsquad1',
handle: 'restrictedsquad1',