-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquery.resolvers.go
More file actions
1234 lines (1116 loc) · 36.7 KB
/
Copy pathquery.resolvers.go
File metadata and controls
1234 lines (1116 loc) · 36.7 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
package resolver
// This file will be automatically regenerated based on the schema, any resolver implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.78
import (
"context"
"fmt"
"quizfreely/api/auth"
"quizfreely/api/graph"
"quizfreely/api/graph/cursor"
"quizfreely/api/graph/model"
"time"
"github.com/georgysavva/scany/v2/pgxscan"
)
// StudysetIds is the resolver for the studysetIds field.
func (r *practiceTestResolver) StudysetIds(ctx context.Context, obj *model.PracticeTest) ([]string, error) {
if obj == nil || obj.ID == nil {
return nil, nil
}
var ids []string
sql := `SELECT studyset_id FROM practice_test_studysets WHERE practice_test_id = $1`
err := pgxscan.Select(ctx, r.DB, &ids, sql, *obj.ID)
if err != nil {
return nil, fmt.Errorf("failed to fetch studyset ids for practice test: %w", err)
}
return ids, nil
}
// Authed is the resolver for the authed field.
func (r *queryResolver) Authed(ctx context.Context) (bool, error) {
authed := auth.AuthedUserContext(ctx) != nil
return authed, nil
}
// AuthedUser is the resolver for the authedUser field.
func (r *queryResolver) AuthedUser(ctx context.Context) (*model.AuthedUser, error) {
return auth.AuthedUserContext(ctx), nil
}
// Studyset is the resolver for the studyset field.
func (r *queryResolver) Studyset(ctx context.Context, id string) (*model.Studyset, error) {
authedUser := auth.AuthedUserContext(ctx)
var studyset model.Studyset
var err error
if authedUser != nil {
sql := `
SELECT id, user_id, title, private, subject_id, draft, seo_indexing_approved,
to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at
FROM public.studysets
WHERE id = $1 AND ((private = false AND draft = false) OR user_id = $2)`
err = pgxscan.Get(ctx, r.DB, &studyset, sql, id, authedUser.ID)
} else {
sql := `
SELECT id, user_id, title, private, subject_id, draft, seo_indexing_approved,
to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at
FROM public.studysets
WHERE id = $1 AND private = false AND draft = false`
err = pgxscan.Get(ctx, r.DB, &studyset, sql, id)
}
if err != nil {
if pgxscan.NotFound(err) {
return nil, fmt.Errorf("studyset not found")
}
return nil, fmt.Errorf("failed to fetch studyset: %w", err)
}
return &studyset, nil
}
// User is the resolver for the user field.
func (r *queryResolver) User(ctx context.Context, id string) (*model.User, error) {
var user model.User
sql := `
SELECT
id,
username,
display_name
FROM auth.users
WHERE id = $1
`
err := pgxscan.Get(ctx, r.DB, &user, sql, id)
if err != nil {
if pgxscan.NotFound(err) {
return nil, fmt.Errorf("user not found")
}
return nil, fmt.Errorf("failed to fetch user: %w", err)
}
return &user, nil
}
// Term is the resolver for the term field.
func (r *queryResolver) Term(ctx context.Context, id string) (*model.Term, error) {
authedUser := auth.AuthedUserContext(ctx)
var term model.Term
var err error
if authedUser != nil {
err = pgxscan.Get(
ctx,
r.DB,
&term,
`SELECT terms.id, terms.studyset_id, terms.term, terms.def, ($3||terms.term_image_key) as term_image_url, ($3||terms.def_image_key) as def_image_url, terms.sort_order,
to_char(terms.created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(terms.updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at
FROM terms
JOIN studysets ON terms.studyset_id = studysets.id
WHERE terms.id = $1 AND (
(studysets.private = FALSE AND studysets.draft = FALSE) OR
studysets.user_id = $2
)`,
id,
authedUser.ID,
r.UsercontentBaseURL,
)
} else {
err = pgxscan.Get(
ctx,
r.DB,
&term,
`SELECT terms.id, terms.studyset_id, terms.term, terms.def, ($2||terms.term_image_key) as term_image_url, ($2||terms.def_image_key) as def_image_url, terms.sort_order,
to_char(terms.created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(terms.updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at
FROM terms
JOIN studysets ON terms.studyset_id = studysets.id
WHERE terms.id = $1 AND studysets.private = FALSE AND studysets.draft = FALSE`,
id,
r.UsercontentBaseURL,
)
}
if err != nil {
if pgxscan.NotFound(err) {
return nil, fmt.Errorf("term not found")
}
return nil, fmt.Errorf("failed to fetch term: %w", err)
}
return &term, nil
}
// RecentlyCreatedStudysets is the resolver for the recentlyCreatedStudysets field.
func (r *queryResolver) RecentlyCreatedStudysets(ctx context.Context, first *int32, after *string, last *int32, before *string) (*model.StudysetConnection, error) {
l := 24
if first != nil && *first > 0 && *first < 1000 {
l = int(*first)
} else if last != nil && *last > 0 && *last < 1000 {
l = int(*last)
}
limit := l + 1
cursorScore, cursorID := cursor.DecodeStudysetCursor(ptrToString(after))
beforeCursorScore, beforeCursorID := cursor.DecodeStudysetCursor(ptrToString(before))
// Check for Previous Page possibility
hasPrevious := cursorScore != "" || cursorID != ""
if before != nil {
// If we are paginating backwards, there is always a "next" page (which is the one we came from)
// but in the context of "hasPrevious", it means "are there newer items?"
// When going backwards (using before), we are moving towards newer items.
// If we find more than limit, it means there are even newer items.
// For the sake of the connection spec:
// hasNextPage: false (usually, unless we fetched more than limit)
// hasPreviousPage: true (we assume there are older items if we are in the middle)
// But let's stick to the data:
}
var studysets []*model.Studyset
var err error
if beforeCursorID != "" {
// Backward pagination
// We want items NEWER than the cursor, sorted ASC (oldest to newest) to get the "previous" 24 items
// Then we reverse them back to DESC (newest to oldest) for the client.
sql := `
SELECT
id,
user_id,
title,
private,
draft,
subject_id,
seo_indexing_approved,
to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at
FROM public.studysets
WHERE private = false AND draft = false
AND (to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM'), id) > ($1, $2::uuid)
ORDER BY created_at ASC, id ASC
LIMIT $3
`
err = pgxscan.Select(ctx, r.DB, &studysets, sql, beforeCursorScore, beforeCursorID, limit)
if err != nil {
return nil, fmt.Errorf("failed to fetch recently created studysets: %w", err)
}
// If we found more than the limit, it means there is a "previous" page (newer items)
hasPrevious = len(studysets) > l
if hasPrevious {
studysets = studysets[:l]
}
// Reverse connections to restore DESC order
for i, j := 0, len(studysets)-1; i < j; i, j = i+1, j-1 {
studysets[i], studysets[j] = studysets[j], studysets[i]
}
// Since we moved backwards, we know there is a "next" page (older items, where we came from)
// strictly speaking, unless we are at the very beginning of the list?
// No, if we successfully fetched items using `before`, it implies we are not at the end.
// But we need to know if there are MORE older items. `hasPrevious` check above tells us if there are NEWER.
// To know if there are OLDER items (hasNextPage), we'd typically rely on where we came from or do a peek.
// For simple prev/next buttons, we can assume:
// If we utilized `before`, we definitely have `hasNextPage` = true (the page we came from).
} else if cursorID != "" {
// Forward pagination
sql := `
SELECT
id,
user_id,
title,
private,
draft,
subject_id,
seo_indexing_approved,
to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at
FROM public.studysets
WHERE private = false AND draft = false
AND (to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM'), id) < ($1, $2::uuid)
ORDER BY created_at DESC, id DESC
LIMIT $3
`
err = pgxscan.Select(ctx, r.DB, &studysets, sql, cursorScore, cursorID, limit)
} else {
// First page
sql := `
SELECT
id,
user_id,
title,
private,
draft,
subject_id,
seo_indexing_approved,
to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at
FROM public.studysets
WHERE private = false AND draft = false
ORDER BY created_at DESC, id DESC
LIMIT $1
`
err = pgxscan.Select(ctx, r.DB, &studysets, sql, limit)
}
if err != nil {
return nil, fmt.Errorf("failed to fetch recently created studysets: %w", err)
}
hasNext := false
if beforeCursorID != "" {
// If we went backwards, we assume there's a next page (older items)
// This is a simplification but sufficient for linear navigation
hasNext = true
} else {
hasNext = len(studysets) > l
if hasNext {
studysets = studysets[:l]
}
}
getCursor := func(s *model.Studyset) (string, string) {
return ptrToString(s.CreatedAt), ptrToString(s.ID)
}
return cursor.StudysetConnectionFrom(studysets, hasNext, hasPrevious, getCursor), nil
}
// RecentlyUpdatedStudysets is the resolver for the recentlyUpdatedStudysets field.
func (r *queryResolver) RecentlyUpdatedStudysets(ctx context.Context, first *int32, after *string, last *int32, before *string) (*model.StudysetConnection, error) {
l := 24
if first != nil && *first > 0 && *first < 1000 {
l = int(*first)
} else if last != nil && *last > 0 && *last < 1000 {
l = int(*last)
}
limit := l + 1
cursorScore, cursorID := cursor.DecodeStudysetCursor(ptrToString(after))
beforeCursorScore, beforeCursorID := cursor.DecodeStudysetCursor(ptrToString(before))
// Check for Previous Page possibility
hasPrevious := cursorScore != "" || cursorID != ""
if before != nil {
}
var studysets []*model.Studyset
var err error
if beforeCursorID != "" {
// Backward pagination
// We want items NEWER than the cursor, sorted ASC (oldest to newest) to get the "previous" 24 items
// Then we reverse them back to DESC (newest to oldest) for the client.
sql := `
SELECT
id,
user_id,
title,
private,
draft,
subject_id,
seo_indexing_approved,
to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at
FROM public.studysets
WHERE private = false AND draft = false
AND (to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM'), id) > ($1, $2::uuid)
ORDER BY updated_at ASC, id ASC
LIMIT $3
`
err = pgxscan.Select(ctx, r.DB, &studysets, sql, beforeCursorScore, beforeCursorID, limit)
if err != nil {
return nil, fmt.Errorf("failed to fetch recently updated studysets: %w", err)
}
// If we found more than the limit, it means there is a "previous" page (newer items)
hasPrevious = len(studysets) > l
if hasPrevious {
studysets = studysets[:l]
}
// Reverse connections to restore DESC order
for i, j := 0, len(studysets)-1; i < j; i, j = i+1, j-1 {
studysets[i], studysets[j] = studysets[j], studysets[i]
}
} else if cursorID != "" {
// Forward pagination
sql := `
SELECT
id,
user_id,
title,
private,
draft,
subject_id,
seo_indexing_approved,
to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at
FROM public.studysets
WHERE private = false AND draft = false
AND (to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM'), id) < ($1, $2::uuid)
ORDER BY updated_at DESC, id DESC
LIMIT $3
`
err = pgxscan.Select(ctx, r.DB, &studysets, sql, cursorScore, cursorID, limit)
} else {
// First page
sql := `
SELECT
id,
user_id,
title,
private,
draft,
subject_id,
seo_indexing_approved,
to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at
FROM public.studysets
WHERE private = false AND draft = false
ORDER BY updated_at DESC, id DESC
LIMIT $1
`
err = pgxscan.Select(ctx, r.DB, &studysets, sql, limit)
}
if err != nil {
return nil, fmt.Errorf("failed to fetch recently updated studysets: %w", err)
}
hasNext := false
if beforeCursorID != "" {
// If we went backwards, we assume there's a next page (older items)
// This is a simplification but sufficient for linear navigation
hasNext = true
} else {
hasNext = len(studysets) > l
if hasNext {
studysets = studysets[:l]
}
}
getCursor := func(s *model.Studyset) (string, string) {
return ptrToString(s.UpdatedAt), ptrToString(s.ID)
}
return cursor.StudysetConnectionFrom(studysets, hasNext, hasPrevious, getCursor), nil
}
// SearchStudysets is the resolver for the searchStudysets field.
func (r *queryResolver) SearchStudysets(ctx context.Context, q string, first *int32, after *string, last *int32, before *string) (*model.StudysetConnection, error) {
if len(q) < 1 {
return &model.StudysetConnection{
Edges: []*model.StudysetEdge{},
PageInfo: &model.PageInfo{},
}, nil
}
// limit query length before using it with the database because `word_similarity` can become really heavy
if len(q) > 200 {
q = q[:200]
}
l := 240
if first != nil && *first > 0 && *first < 1000 {
l = int(*first)
} else if last != nil && *last > 0 && *last < 1000 {
l = int(*last)
}
limit := l + 1
cursorScore, cursorTS, cursorID := cursor.DecodeStudysetScoreCursor(ptrToString(after))
beforeCursorScore, beforeCursorTS, beforeCursorID := cursor.DecodeStudysetScoreCursor(ptrToString(before))
isBackward := beforeCursorID != ""
hasPrevious := false
if !isBackward {
hasPrevious = cursorScore != "" || cursorTS != "" || cursorID != ""
}
// We need a temporary struct to hold the score for cursor generation
type searchRow struct {
model.Studyset
Score float64 `db:"score"`
}
var rows []*searchRow
var err error
// Common select columns matching model.Studyset fields (via scany/db tags or name matching)
selectCols := `
id,
user_id,
title,
private,
draft,
subject_id,
seo_indexing_approved,
to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at,
word_similarity(lower($1), lower(title)) as score
`
if isBackward {
sql := `
SELECT ` + selectCols + `
FROM public.studysets
WHERE lower($1) <% lower(title) AND private = false AND draft = false
AND (word_similarity(lower($1), lower(title)), to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM'), id) > ($2::float4, $3, $4::uuid)
ORDER BY score ASC, created_at ASC, id ASC
LIMIT $5
`
err = pgxscan.Select(ctx, r.DB, &rows, sql, q, beforeCursorScore, beforeCursorTS, beforeCursorID, limit)
if err == nil {
// If we found more than the limit, it means there is a "previous" page (newer items)
hasPrevious = len(rows) > l
if hasPrevious {
rows = rows[:l]
}
// Reverse results to restore DESC order
for i, j := 0, len(rows)-1; i < j; i, j = i+1, j-1 {
rows[i], rows[j] = rows[j], rows[i]
}
}
} else if cursorID != "" {
sql := `
SELECT ` + selectCols + `
FROM public.studysets
WHERE lower($1) <% lower(title) AND private = false AND draft = false
AND (word_similarity(lower($1), lower(title)), to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM'), id) < ($2::float4, $3, $4::uuid)
ORDER BY score DESC, created_at DESC, id DESC
LIMIT $5
`
// cursorScore is passed as string, Postgres will parse it with ::float4
err = pgxscan.Select(ctx, r.DB, &rows, sql, q, cursorScore, cursorTS, cursorID, limit)
} else {
// No cursor
sql := `
SELECT ` + selectCols + `
FROM public.studysets
WHERE lower($1) <% lower(title) AND private = false AND draft = false
ORDER BY score DESC, created_at DESC, id DESC
LIMIT $2
`
err = pgxscan.Select(ctx, r.DB, &rows, sql, q, limit)
}
if err != nil {
return nil, fmt.Errorf("failed to search studysets: %w", err)
}
hasNext := false
if isBackward {
hasNext = true
} else {
hasNext = len(rows) > l
if hasNext {
rows = rows[:l]
}
}
// Convert back to []*model.Studyset for the connection
studysets := make([]*model.Studyset, len(rows))
for i, r := range rows {
// Make a copy or point to the embedded struct?
// r.Studyset is embedded. We can take address of it?
// Be careful with loop variable capturing.
// Actually, r is a pointer to searchRow.
// We can just return &row.Studyset?
// Yes, r.Studyset is the struct value embedded. &r.Studyset works.
s := r.Studyset
studysets[i] = &s
}
// Manual connection building
edges := make([]*model.StudysetEdge, 0, len(studysets))
for i, s := range studysets {
score := rows[i].Score
edges = append(edges, &model.StudysetEdge{
Node: s,
Cursor: cursor.EncodeStudysetScoreCursor(fmt.Sprintf("%f", score), ptrToString(s.CreatedAt), ptrToString(s.ID)),
})
}
var startCursor, endCursor *string
if len(edges) > 0 {
startCursor = &edges[0].Cursor
endCursor = &edges[len(edges)-1].Cursor
}
return &model.StudysetConnection{
Edges: edges,
PageInfo: &model.PageInfo{
HasNextPage: hasNext,
HasPreviousPage: hasPrevious,
StartCursor: startCursor,
EndCursor: endCursor,
},
}, nil
// Note: I am not using StudysetConnectionFrom because it hardcodes EncodeStudysetCursor.
// `getCursor` var above was just to show I considered it.
}
// MyStudysets is the resolver for the myStudysets field.
func (r *queryResolver) MyStudysets(ctx context.Context, first *int32, after *string, last *int32, before *string, hideFoldered *bool) (*model.StudysetConnection, error) {
authedUser := auth.AuthedUserContext(ctx)
if authedUser == nil {
return nil, fmt.Errorf("not authenticated")
}
l := 240
if first != nil && *first > 0 && *first < 1000 {
l = int(*first)
} else if last != nil && *last > 0 && *last < 1000 {
l = int(*last)
}
limit := l + 1
cursorTS, cursorID := cursor.DecodeStudysetCursor(ptrToString(after))
beforeCursorTS, beforeCursorID := cursor.DecodeStudysetCursor(ptrToString(before))
isBackward := beforeCursorID != ""
hasPrevious := false
if !isBackward {
hasPrevious = cursorTS != "" || cursorID != ""
}
var studysets []*model.Studyset
var err error
// Common columns for selectivity
cols := `id, user_id, title, private, subject_id, draft, seo_indexing_approved,
to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at`
// Where clause fragments
whereBase := `WHERE user_id = $1 AND draft = false`
if hideFoldered != nil && *hideFoldered {
whereBase += ` AND id NOT IN (SELECT fs.studyset_id FROM folder_studysets fs WHERE fs.user_id = $1)`
}
if isBackward {
sql := fmt.Sprintf(`
SELECT %s
FROM public.studysets
%s AND (to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM'), id) > ($2, $3::uuid)
ORDER BY updated_at ASC, id ASC
LIMIT $4
`, cols, whereBase)
err = pgxscan.Select(ctx, r.DB, &studysets, sql, authedUser.ID, beforeCursorTS, beforeCursorID, limit)
if err == nil {
hasPrevious = len(studysets) > l
if hasPrevious {
studysets = studysets[:l]
}
// Reverse
for i, j := 0, len(studysets)-1; i < j; i, j = i+1, j-1 {
studysets[i], studysets[j] = studysets[j], studysets[i]
}
}
} else if cursorID != "" {
sql := fmt.Sprintf(`
SELECT %s
FROM public.studysets
%s AND (to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM'), id) < ($2, $3::uuid)
ORDER BY updated_at DESC, id DESC
LIMIT $4
`, cols, whereBase)
err = pgxscan.Select(ctx, r.DB, &studysets, sql, authedUser.ID, cursorTS, cursorID, limit)
} else {
sql := fmt.Sprintf(`
SELECT %s
FROM public.studysets
%s
ORDER BY updated_at DESC, id DESC
LIMIT $2
`, cols, whereBase)
err = pgxscan.Select(ctx, r.DB, &studysets, sql, authedUser.ID, limit)
}
if err != nil {
return nil, fmt.Errorf("failed to fetch my studysets: %w", err)
}
hasNext := false
if isBackward {
hasNext = true
} else {
hasNext = len(studysets) > l
if hasNext {
studysets = studysets[:l]
}
}
getCursor := func(s *model.Studyset) (string, string) {
return ptrToString(s.UpdatedAt), ptrToString(s.ID)
}
return cursor.StudysetConnectionFrom(studysets, hasNext, hasPrevious, getCursor), nil
}
// MyStudysetDrafts is the resolver for the myStudysetDrafts field.
func (r *queryResolver) MyStudysetDrafts(ctx context.Context, first *int32, after *string, last *int32, before *string, hideFoldered *bool) (*model.StudysetConnection, error) {
authedUser := auth.AuthedUserContext(ctx)
if authedUser == nil {
return nil, fmt.Errorf("not authenticated")
}
l := 240
if first != nil && *first > 0 && *first < 1000 {
l = int(*first)
} else if last != nil && *last > 0 && *last < 1000 {
l = int(*last)
}
limit := l + 1
cursorTS, cursorID := cursor.DecodeStudysetCursor(ptrToString(after))
beforeCursorTS, beforeCursorID := cursor.DecodeStudysetCursor(ptrToString(before))
isBackward := beforeCursorID != ""
hasPrevious := false
if !isBackward {
hasPrevious = cursorTS != "" || cursorID != ""
}
var studysets []*model.Studyset
var err error
cols := `id, user_id, title, private, subject_id, draft, seo_indexing_approved,
to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at`
whereBase := `WHERE user_id = $1 AND draft = true`
if hideFoldered != nil && *hideFoldered {
whereBase += ` AND id NOT IN (SELECT fs.studyset_id FROM folder_studysets fs WHERE fs.user_id = $1)`
}
if isBackward {
sql := fmt.Sprintf(`
SELECT %s
FROM public.studysets
%s AND (to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM'), id) > ($2, $3::uuid)
ORDER BY updated_at ASC, id ASC
LIMIT $4
`, cols, whereBase)
err = pgxscan.Select(ctx, r.DB, &studysets, sql, authedUser.ID, beforeCursorTS, beforeCursorID, limit)
if err == nil {
hasPrevious = len(studysets) > l
if hasPrevious {
studysets = studysets[:l]
}
for i, j := 0, len(studysets)-1; i < j; i, j = i+1, j-1 {
studysets[i], studysets[j] = studysets[j], studysets[i]
}
}
} else if cursorID != "" {
sql := fmt.Sprintf(`
SELECT %s
FROM public.studysets
%s AND (to_char(updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM'), id) < ($2, $3::uuid)
ORDER BY updated_at DESC, id DESC
LIMIT $4
`, cols, whereBase)
err = pgxscan.Select(ctx, r.DB, &studysets, sql, authedUser.ID, cursorTS, cursorID, limit)
} else {
sql := fmt.Sprintf(`
SELECT %s
FROM public.studysets
%s
ORDER BY updated_at DESC, id DESC
LIMIT $2
`, cols, whereBase)
err = pgxscan.Select(ctx, r.DB, &studysets, sql, authedUser.ID, limit)
}
if err != nil {
return nil, fmt.Errorf("failed to fetch my studyset drafts: %w", err)
}
hasNext := false
if isBackward {
hasNext = true
} else {
hasNext = len(studysets) > l
if hasNext {
studysets = studysets[:l]
}
}
getCursor := func(s *model.Studyset) (string, string) {
return ptrToString(s.UpdatedAt), ptrToString(s.ID)
}
return cursor.StudysetConnectionFrom(studysets, hasNext, hasPrevious, getCursor), nil
}
// MyFolders is the resolver for the myFolders field.
func (r *queryResolver) MyFolders(ctx context.Context, first *int32, after *string) (*model.FolderConnection, error) {
authedUser := auth.AuthedUserContext(ctx)
if authedUser == nil {
return nil, fmt.Errorf("not authenticated")
}
l := 240
if first != nil && *first > 0 && *first < 1000 {
l = int(*first)
}
limit := l + 1
cursorID := cursor.DecodeFolderCursor(ptrToString(after))
hasPrevious := cursorID != ""
var folders []*model.Folder
var err error
if cursorID != "" {
sql := `
SELECT id, name
FROM folders
WHERE user_id = $1 AND id < $2::uuid
ORDER BY id DESC
LIMIT $3
`
err = pgxscan.Select(ctx, r.DB, &folders, sql, authedUser.ID, cursorID, limit)
} else {
sql := `
SELECT id, name
FROM folders
WHERE user_id = $1
ORDER BY id DESC
LIMIT $2
`
err = pgxscan.Select(ctx, r.DB, &folders, sql, authedUser.ID, limit)
}
if err != nil {
return nil, fmt.Errorf("failed to fetch my folders: %w", err)
}
hasNext := len(folders) > l
if hasNext {
folders = folders[:l]
}
edges := make([]*model.FolderEdge, 0, len(folders))
for _, f := range folders {
idStr := f.ID
edges = append(edges, &model.FolderEdge{
Node: f,
Cursor: cursor.EncodeFolderCursor(ptrToString(idStr)),
})
}
var startCursor, endCursor *string
if len(edges) > 0 {
startCursor = &edges[0].Cursor
endCursor = &edges[len(edges)-1].Cursor
}
return &model.FolderConnection{
Edges: edges,
PageInfo: &model.PageInfo{
HasNextPage: hasNext,
HasPreviousPage: hasPrevious,
StartCursor: startCursor,
EndCursor: endCursor,
},
}, nil
}
// MySavedStudysets is the resolver for the mySavedStudysets field.
func (r *queryResolver) MySavedStudysets(ctx context.Context, first *int32, after *string, last *int32, before *string) (*model.StudysetConnection, error) {
authedUser := auth.AuthedUserContext(ctx)
if authedUser == nil {
return nil, fmt.Errorf("not authenticated")
}
l := 240
if first != nil && *first > 0 && *first < 1000 {
l = int(*first)
} else if last != nil && *last > 0 && *last < 1000 {
l = int(*last)
}
limit := l + 1
cursorTS, cursorID := cursor.DecodeStudysetCursor(ptrToString(after))
beforeCursorTS, beforeCursorID := cursor.DecodeStudysetCursor(ptrToString(before))
isBackward := beforeCursorID != ""
hasPrevious := false
if !isBackward {
hasPrevious = cursorTS != "" || cursorID != ""
}
var rows []*cursor.SavedStudysetRow
var err error
if isBackward {
sql := `
SELECT
s.id,
s.user_id,
s.title,
s.draft,
s.private,
s.subject_id,
s.seo_indexing_approved,
to_char(s.created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(s.updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at,
to_char(saved_studysets.timestamp, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as saved_at
FROM saved_studysets
JOIN studysets s ON saved_studysets.studyset_id = s.id
WHERE saved_studysets.user_id = $1
AND s.private = false AND s.draft = false
AND (to_char(saved_studysets.timestamp, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM'), s.id) > ($2, $3::uuid)
ORDER BY saved_studysets.timestamp ASC, s.id ASC
LIMIT $4
`
err = pgxscan.Select(ctx, r.DB, &rows, sql, authedUser.ID, beforeCursorTS, beforeCursorID, limit)
if err == nil {
hasPrevious = len(rows) > l
if hasPrevious {
rows = rows[:l]
}
// Reverse
for i, j := 0, len(rows)-1; i < j; i, j = i+1, j-1 {
rows[i], rows[j] = rows[j], rows[i]
}
}
} else if cursorID != "" {
sql := `
SELECT
s.id,
s.user_id,
s.title,
s.draft,
s.private,
s.subject_id,
s.seo_indexing_approved,
to_char(s.created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(s.updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at,
to_char(saved_studysets.timestamp, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as saved_at
FROM saved_studysets
JOIN studysets s ON saved_studysets.studyset_id = s.id
WHERE saved_studysets.user_id = $1
AND s.private = false AND s.draft = false
AND (to_char(saved_studysets.timestamp, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM'), s.id) < ($2, $3::uuid)
ORDER BY saved_studysets.timestamp DESC, s.id DESC
LIMIT $4
`
err = pgxscan.Select(ctx, r.DB, &rows, sql, authedUser.ID, cursorTS, cursorID, limit)
} else {
sql := `
SELECT
s.id,
s.user_id,
s.title,
s.draft,
s.private,
s.subject_id,
s.seo_indexing_approved,
to_char(s.created_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as created_at,
to_char(s.updated_at, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as updated_at,
to_char(saved_studysets.timestamp, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as saved_at
FROM saved_studysets
JOIN studysets s ON saved_studysets.studyset_id = s.id
WHERE saved_studysets.user_id = $1
AND s.private = false AND s.draft = false
ORDER BY saved_studysets.timestamp DESC, s.id DESC
LIMIT $2
`
err = pgxscan.Select(ctx, r.DB, &rows, sql, authedUser.ID, limit)
}
if err != nil {
return nil, fmt.Errorf("failed to fetch saved studysets: %w", err)
}
hasNext := false
if isBackward {
hasNext = true
} else {
hasNext = len(rows) > l
if hasNext {
rows = rows[:l]
}
}
edges := make([]*model.StudysetEdge, 0, len(rows))
for _, row := range rows {
edges = append(edges, &model.StudysetEdge{
Node: &row.Studyset,
Cursor: cursor.EncodeStudysetCursor(ptrToString(row.SavedAt), ptrToString(row.ID)),
})
}
var startCursor, endCursor *string
if len(edges) > 0 {
startCursor = &edges[0].Cursor
endCursor = &edges[len(edges)-1].Cursor
}
return &model.StudysetConnection{
Edges: edges,
PageInfo: &model.PageInfo{
HasNextPage: hasNext,
HasPreviousPage: hasPrevious,
StartCursor: startCursor,
EndCursor: endCursor,
},
}, nil
}
// PracticeTest is the resolver for the practiceTest field.
func (r *queryResolver) PracticeTest(ctx context.Context, id string) (*model.PracticeTest, error) {
authedUser := auth.AuthedUserContext(ctx)
if authedUser == nil {
return nil, fmt.Errorf("not authenticated")
}
var practiceTest model.PracticeTest
err := pgxscan.Get(
ctx,
r.DB,
&practiceTest,
`SELECT id,
to_char(timestamp, 'YYYY-MM-DD"T"HH24:MI:SS.MSTZH:TZM') as timestamp,
questions_correct,
questions_total,
questions
FROM practice_tests
WHERE id = $1 AND user_id = $2`,
id,
authedUser.ID,
)
if err != nil {
return nil, fmt.Errorf("failed to fetch practice test by id: %w", err)
}
return &practiceTest, nil
}
// Subject is the resolver for the subject field.
func (r *queryResolver) Subject(ctx context.Context, id string) (*model.Subject, error) {
var subject model.Subject
err := pgxscan.Get(
ctx,
r.DB,
&subject,
`SELECT id, name, category
FROM subjects WHERE id = $1`,
id,
)
if err != nil {
return nil, fmt.Errorf("failed to get subject by id: %w", err)
}
return &subject, nil