-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathusers.ts
More file actions
894 lines (803 loc) · 17.4 KB
/
users.ts
File metadata and controls
894 lines (803 loc) · 17.4 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
import { gql } from 'graphql-request';
import { subDays } from 'date-fns';
import {
SHARED_POST_INFO_FRAGMENT,
TOP_READER_BADGE_FRAGMENT,
USER_SHORT_INFO_FRAGMENT,
USER_STREAK_FRAGMENT,
} from './fragments';
import type { PublicProfile, UserProfile, UserShortProfile } from '../lib/user';
import type { Connection } from './common';
import { ApiError, gqlClient } from './common';
import type { SourceMember } from './sources';
import type { SendType } from '../hooks';
import type { DayOfWeek } from '../lib/date';
import type { NotificationSettings } from '../components/notifications/utils';
export const USER_SHORT_BY_ID = `
query UserShortById($id: ID!) {
user(id: $id) {
id
name
image
username
permalink
}
}
`;
export const CHECK_LOCATION_QUERY = gql`
query checkLocation {
checkLocation {
_
}
}
`;
export const USER_BY_ID_STATIC_FIELDS_QUERY = `
query User($id: ID!) {
user(id: $id) {
id
name
image
cover
username
bio
timezone
reputation
permalink
createdAt
readmeHtml
isPlus
experienceLevel
socialLinks {
platform
url
}
location {
city
subdivision
country
}
companies {
name
image
}
contentPreference {
status
}
coresRole
}
}
`;
export const USER_README_QUERY = `
query Readme($id: ID!) {
user(id: $id) {
readme
}
}
`;
export const UPDATE_README_MUTATION = `
mutation UpdateReadme($content: String!) {
updateReadme(content: $content) {
readmeHtml
}
}
`;
const publicSourceMemberships = `
sources: publicSourceMemberships(userId: $id, first: 30) {
edges {
node {
role
source {
id
name
handle
membersCount
image
permalink
currentMember {
role
}
}
}
}
}`;
export const PROFILE_V2_EXTRA_QUERY = gql`
query ProfileV2($id: ID!) {
userStats(id: $id) {
upvotes: numPostUpvotes
views: numPostViews
numFollowers
numFollowing
}
${publicSourceMemberships}
}
`;
export const PUBLIC_SOURCE_MEMBERSHIPS_QUERY = gql`
query PublicSourceMemberships($id: ID!) {
${publicSourceMemberships}
}
`;
export type ProfileV2 = {
user: PublicProfile;
userStats: {
upvotes: number;
views: number;
numFollowers: number;
numFollowing: number;
};
sources: Connection<SourceMember>;
};
export type UserReadingRank = { currentRank: number };
export type MostReadTag = {
value: string;
count: number;
percentage?: number;
total?: number;
};
export type Tag = {
tag: string;
readingDays: number;
percentage?: number;
};
export type ProfileReadingData = UserReadingRankHistoryData &
UserReadHistoryData &
UserReadingTopTagsData &
UserStreakData;
export type UserReadingRankHistory = { rank: number; count: number };
export interface UserReadingRankHistoryData {
userReadingRankHistory: UserReadingRankHistory[];
}
export type UserReadHistory = { date: string; reads: number };
export interface UserReadHistoryData {
userReadHistory: UserReadHistory[];
}
export interface UserReadingTopTagsData {
userMostReadTags: MostReadTag[];
}
export interface UserStreakData {
userStreakProfile: UserStreak;
}
export const USER_READING_HISTORY_QUERY = gql`
query UserReadingHistory(
$id: ID!
$after: String!
$before: String!
$version: Int
$limit: Int
) {
userReadingRankHistory(
id: $id
version: $version
after: $after
before: $before
) {
rank
count
}
userReadHistory(id: $id, after: $after, before: $before, grouped: true) {
date
reads
}
userMostReadTags(id: $id, after: $after, before: $before, limit: $limit) {
value
count
total
percentage
}
userStreakProfile(id: $id) {
max
total
}
}
`;
export const USER_STREAK_HISTORY = gql`
query UserStreakHistory($id: ID!, $after: String!, $before: String!) {
userReadHistory(id: $id, after: $after, before: $before) {
date
reads
}
}
`;
const READING_HISTORY_FRAGMENT = gql`
fragment ReadingHistoryFragment on ReadingHistory {
timestamp
timestampDb
post {
...SharedPostInfo
sharedPost {
...SharedPostInfo
}
}
}
${SHARED_POST_INFO_FRAGMENT}
`;
const READING_HISTORY_CONNECTION_FRAGMENT = gql`
${READING_HISTORY_FRAGMENT}
fragment ReadingHistoryConnectionFragment on ReadingHistoryConnection {
pageInfo {
endCursor
hasNextPage
}
edges {
node {
...ReadingHistoryFragment
}
}
}
`;
export interface HidePostItemCardProps {
timestamp: Date;
postId: string;
}
export const SEARCH_READING_HISTORY_SUGGESTIONS = gql`
query SearchReadingHistorySuggestions($query: String!) {
searchReadingHistorySuggestions(query: $query) {
hits {
title
}
}
}
`;
export const SEARCH_READING_HISTORY_QUERY = gql`
${READING_HISTORY_CONNECTION_FRAGMENT}
query SearchReadingHistory($first: Int, $after: String, $query: String!) {
readHistory: searchReadingHistory(
first: $first
after: $after
query: $query
) {
...ReadingHistoryConnectionFragment
}
}
`;
export const READING_HISTORY_QUERY = gql`
${READING_HISTORY_CONNECTION_FRAGMENT}
query ReadHistory($after: String, $first: Int, $isPublic: Boolean) {
readHistory(after: $after, first: $first, isPublic: $isPublic) {
...ReadingHistoryConnectionFragment
}
}
`;
export const HIDE_READING_HISTORY_MUTATION = gql`
mutation HideReadHistory($postId: String!, $timestamp: DateTime!) {
hideReadHistory(postId: $postId, timestamp: $timestamp) {
_
}
}
`;
export const UPDATE_USER_PROFILE_MUTATION = gql`
mutation UpdateUserProfile($data: UpdateUserInput, $upload: Upload) {
updateUserProfile(data: $data, upload: $upload) {
id
name
image
username
permalink
bio
readme
createdAt
infoConfirmed
timezone
experienceLevel
language
socialLinks {
platform
url
}
}
}
`;
export const UPDATE_USER_INFO_MUTATION = gql`
mutation UpdateUserInfo(
$data: UpdateUserInfoInput
$upload: Upload
$coverUpload: Upload
) {
updateUserInfo(data: $data, upload: $upload, coverUpload: $coverUpload) {
id
name
image
cover
username
permalink
bio
readme
createdAt
infoConfirmed
timezone
experienceLevel
hideExperience
language
socialLinks {
platform
url
}
}
}
`;
export const mutateUserInfo = async (
data: Partial<UserProfile>,
upload: File,
coverUpload: File,
) => {
const res = await gqlClient.request(UPDATE_USER_INFO_MUTATION, {
data,
upload,
coverUpload,
});
return res.updateUserInfo;
};
export const UPLOAD_COVER_MUTATION = gql`
mutation UploadCoverImage($upload: Upload!) {
user: uploadCoverImage(image: $upload) {
cover
}
}
`;
export const GET_USERNAME_SUGGESTION = gql`
query GenerateUniqueUsername($name: String!) {
generateUniqueUsername(name: $name)
}
`;
export const generateUsername = async (name: string): Promise<string> => {
const result = await gqlClient.request<{ generateUniqueUsername: string }>(
GET_USERNAME_SUGGESTION,
{ name },
);
return result.generateUniqueUsername;
};
export const GET_USER_COMPANIES = gql`
query Companies {
companies {
email
company {
id
name
image
}
}
}
`;
export const ADD_USER_COMPANY_MUTATION = gql`
mutation AddUserCompany($email: String!) {
addUserCompany(email: $email) {
_
}
}
`;
export const VERIFY_USER_COMPANY_CODE_MUTATION = gql`
mutation VerifyUserCompanyCode($email: String!, $code: String!) {
verifyUserCompanyCode(email: $email, code: $code) {
email
company {
id
name
image
}
}
}
`;
export const REMOVE_USER_COMPANY_MUTATION = gql`
mutation RemoveUserCompany($email: String!) {
removeUserCompany(email: $email) {
_
}
}
`;
// Using string constructor to avoid Babel unicode-regex transformation issues
export const handleRegex = new RegExp(
'^@?[\\p{L}\\p{N}]([\\p{L}\\p{N}_]){2,38}$',
'iu',
);
// Using string constructor to avoid Babel unicode-regex transformation issues
export const socialHandleRegex = new RegExp(
'^@?([\\p{L}\\p{N}_-]){1,39}$',
'iu',
);
export const REFERRAL_CAMPAIGN_QUERY = gql`
query ReferralCampaign($referralOrigin: String!) {
referralCampaign(referralOrigin: $referralOrigin) {
referredUsersCount
referralCountLimit
referralToken
url
}
}
`;
export const GET_REFERRING_USER_QUERY = gql`
query User($id: ID!) {
user(id: $id) {
...UserShortInfo
}
}
${USER_SHORT_INFO_FRAGMENT}
`;
export const getUserShortInfo = async (
id: string,
): Promise<UserShortProfile> => {
const res = await gqlClient.request(GET_REFERRING_USER_QUERY, { id });
return res.user || null;
};
export enum UserPersonalizedDigestType {
Digest = 'digest',
ReadingReminder = 'reading_reminder',
StreakReminder = 'streak_reminder',
Brief = 'brief',
}
export type UserPersonalizedDigest = {
preferredDay: number;
preferredHour: number;
type?: UserPersonalizedDigestType;
flags: {
sendType?: SendType;
};
};
export type UserPersonalizedDigestSubscribe = {
day?: number;
hour?: number;
type?: UserPersonalizedDigestType;
sendType?: SendType;
};
export const GET_PERSONALIZED_DIGEST_SETTINGS = gql`
query PersonalizedDigest {
personalizedDigest {
preferredDay
preferredHour
type
flags {
sendType
}
}
}
`;
export const REFERRED_USERS_QUERY = gql`
query ReferredUsers {
referredUsers {
pageInfo {
endCursor
hasNextPage
}
edges {
node {
...UserShortInfo
}
}
}
}
${USER_SHORT_INFO_FRAGMENT}
`;
export const SUBSCRIBE_PERSONALIZED_DIGEST_MUTATION = gql`
mutation SubscribePersonalizedDigest(
$hour: Int
$day: Int
$type: DigestType
$sendType: UserPersonalizedDigestSendType
) {
subscribePersonalizedDigest(
hour: $hour
day: $day
type: $type
sendType: $sendType
) {
preferredDay
preferredHour
type
flags {
sendType
}
}
}
`;
export const UNSUBSCRIBE_PERSONALIZED_DIGEST_MUTATION = gql`
mutation UnsubscribePersonalizedDigest($type: DigestType) {
unsubscribePersonalizedDigest(type: $type) {
_
}
}
`;
export interface ReadingDay {
date: string;
reads: number;
}
export const getReadingStreak30Days = async (
id: string,
start: Date = subDays(new Date(), 30),
): Promise<ReadingDay[]> => {
const today = new Date();
const res = await gqlClient.request(USER_STREAK_HISTORY, {
after: start.toISOString(),
before: today.toISOString(),
id,
});
return res.userReadHistory;
};
export const USER_STREAK_QUERY = gql`
query UserStreak {
userStreak {
...UserStreakFragment
}
}
${USER_STREAK_FRAGMENT}
`;
export interface UserStreak {
max: number;
total: number;
current: number;
weekStart: DayOfWeek;
lastViewAt: Date;
}
export interface UserProfileAnalytics {
id: string;
uniqueVisitors: number;
updatedAt: Date;
}
export interface UserProfileAnalyticsHistory {
id: string;
date: string;
uniqueVisitors: number;
updatedAt: Date;
}
export const getReadingStreak = async (): Promise<UserStreak> => {
const res = await gqlClient.request(USER_STREAK_QUERY);
return res.userStreak;
};
export const USER_PROFILE_ANALYTICS_QUERY = gql`
query UserProfileAnalytics($userId: ID!) {
userProfileAnalytics(userId: $userId) {
id
uniqueVisitors
updatedAt
}
}
`;
export const USER_PROFILE_ANALYTICS_HISTORY_QUERY = gql`
query UserProfileAnalyticsHistory($userId: ID!, $first: Int) {
userProfileAnalyticsHistory(userId: $userId, first: $first) {
edges {
node {
id
date
uniqueVisitors
}
}
}
}
`;
export interface UserStreakRecoverData {
canRecover: boolean;
cost: number;
oldStreakLength: number;
regularCost?: number;
}
export const USER_STREAK_RECOVER_QUERY = gql`
query UserStreakRecover {
streakRecover {
canRecover
cost
oldStreakLength
regularCost
}
}
`;
export const USER_STREAK_RECOVER_MUTATION = gql`
mutation RecoverStreak {
recoverStreak(cores: true) {
...UserStreakFragment
balance {
amount
}
}
}
${USER_STREAK_FRAGMENT}
`;
export const DEV_CARD_QUERY = gql`
query DevCardById($id: ID!) {
devCard(id: $id) {
id
user {
...UserShortInfo
createdAt
cover
}
createdAt
theme
isProfileCover
showBorder
articlesRead
tags
sources {
name
permalink
image
}
}
userStreakProfile(id: $id) {
max
}
}
${USER_SHORT_INFO_FRAGMENT}
`;
export enum AcquisitionChannel {
Friend = 'friend',
InstagramFacebook = 'instagram_facebook',
YouTube = 'youtube',
TikTok = 'tiktok',
SearchEngine = 'search_engine',
Advertisement = 'ad',
Other = 'other',
}
export const USER_ACQUISITION_MUTATION = gql`
mutation AddUserAcquisitionChannel($acquisitionChannel: String!) {
addUserAcquisitionChannel(acquisitionChannel: $acquisitionChannel) {
_
}
}
`;
export const updateUserAcquisition = (
acquisitionChannel: AcquisitionChannel,
): Promise<void> =>
gqlClient.request(USER_ACQUISITION_MUTATION, { acquisitionChannel });
export const CLEAR_MARKETING_CTA_MUTATION = gql`
mutation ClearUserMarketingCta($campaignId: String!) {
clearUserMarketingCta(campaignId: $campaignId) {
_
}
}
`;
export const VOTE_MUTATION = gql`
mutation Vote($id: ID!, $entity: UserVoteEntity!, $vote: Int!) {
vote(id: $id, entity: $entity, vote: $vote) {
_
}
}
`;
export const UPDATE_STREAK_COUNT_MUTATION = gql`
mutation UpdateStreakConfig($weekStart: Int) {
updateStreakConfig(weekStart: $weekStart) {
...UserStreakFragment
}
}
${USER_STREAK_FRAGMENT}
`;
export const USER_INTEGRATIONS = gql`
query UserIntegrations {
userIntegrations {
pageInfo {
endCursor
hasNextPage
}
edges {
node {
id
type
name
}
}
}
}
`;
export const USER_INTEGRATION_BY_ID = gql`
query UserIntegrationById($id: ID!) {
userIntegration(id: $id) {
id
type
name
}
}
`;
export const TOP_READER_BADGE = gql`
query TopReaderBadge($userId: ID!, $limit: Int) {
topReaderBadge(limit: $limit, userId: $userId) {
...TopReader
}
}
${TOP_READER_BADGE_FRAGMENT}
`;
export const TOP_READER_BADGE_BY_ID = gql`
query TopReaderBadgeById($id: ID!) {
topReaderBadgeById(id: $id) {
...TopReader
user {
name
username
image
}
}
}
${TOP_READER_BADGE_FRAGMENT}
`;
export const GET_NOTIFICATION_SETTINGS = gql`
query NotificationSettings {
notificationSettings
}
`;
export const getBasicUserInfo = async (
userId: string,
): Promise<UserShortProfile> => {
const res = await gqlClient.request(GET_REFERRING_USER_QUERY, {
id: userId,
});
return res.user || null;
};
export enum UploadPreset {
Avatar = 'avatar',
ProfileCover = 'cover',
}
export const CLEAR_IMAGE_MUTATION = gql`
mutation ClearImage($presets: [UploadPreset]!) {
clearImage(presets: $presets) {
_
}
}
`;
export const clearImage = async (presets: string[]): Promise<void> => {
await gqlClient.request(CLEAR_IMAGE_MUTATION, { presets });
};
export const GET_PLUS_GIFTER_USER = gql`
query PlusGifterUser {
plusGifterUser {
id
name
image
username
}
}
`;
export const getPlusGifterUser = async (): Promise<UserShortProfile | null> => {
try {
const res = await gqlClient.request(GET_PLUS_GIFTER_USER);
return res.plusGifterUser;
} catch (error) {
const errorCode = error.response?.errors?.[0]?.extensions?.code;
if (errorCode === ApiError.Forbidden) {
return null;
}
throw error;
}
};
export const REQUEST_APP_ACCOUNT_TOKEN_MUTATION = gql`
mutation RequestAppAccountToken {
requestAppAccountToken
}
`;
const CLAIM_CLAIMABLE_ITEM_MUTATION = gql`
mutation ClaimClaimableItem {
claimUnclaimedItem {
claimed
}
}
`;
export const claimClaimableItem = async (): Promise<boolean> => {
try {
const {
claimUnclaimedItem: { claimed },
} = await gqlClient.request<{
claimUnclaimedItem: { claimed: boolean };
}>(CLAIM_CLAIMABLE_ITEM_MUTATION);
return claimed;
} catch (error) {
return false;
}
};
const UPLOAD_CV_MUTATION = gql`
mutation UploadResume($resume: Upload!) {
uploadResume(resume: $resume) {
_
}
}
`;
export const uploadCv = (file: File) =>
gqlClient.request(UPLOAD_CV_MUTATION, { resume: file });
const UPDATE_NOTIFICATION_SETTINGS_MUTATION = gql`
mutation UpdateNotificationSettings($notificationFlags: JSON!) {
updateNotificationSettings(notificationFlags: $notificationFlags) {
_
}
}
`;
export const updateNotificationSettings = async (
notificationFlags: NotificationSettings,
): Promise<void> => {
await gqlClient.request(UPDATE_NOTIFICATION_SETTINGS_MUTATION, {
notificationFlags,
});
};