-
Notifications
You must be signed in to change notification settings - Fork 0
/
Relationships.fs
4806 lines (3890 loc) · 227 KB
/
Relationships.fs
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
namespace Felicity
open System
open System.Collections.Generic
open System.Runtime.CompilerServices
open System.Runtime.InteropServices
open System.Text.Json.Serialization
open System.Threading.Tasks
open Microsoft.AspNetCore.Http
open Microsoft.Extensions.DependencyInjection
open Microsoft.Extensions.Logging
open Giraffe
open Errors
[<AutoOpen>]
module private RelationshipHelpers =
let getIncludedForSelfUrl
httpCtx
ctx
(req: Request)
(resp: ResponseBuilder<'ctx>)
relName
parentResDef
parentEntity
=
// Hack: The included resources are the same as those for the parent resource document
// when using only the include paths that start with this relationship.
let reqForIncluded = {
req with
Includes = req.Includes |> List.filter (List.tryHead >> (=) (Some relName))
}
resp.Write httpCtx ctx reqForIncluded (parentResDef, parentEntity)
|> Task.map (fun (doc, _) -> doc.included)
type Relationship<'ctx, 'entity, 'relatedEntity, 'relatedId> =
abstract Name: string
type internal RelationshipHandlers<'ctx> =
abstract Name: string
abstract IsToMany: bool
abstract IsSettable: bool
abstract IsSettableButNotGettable: bool
abstract IsSettableWithoutPersist: bool
abstract GetRelated:
('ctx -> Request -> BoxedEntity -> ResourceDefinition<'ctx> -> ResponseBuilder<'ctx> -> HttpHandler) option
abstract GetSelf:
('ctx -> Request -> BoxedEntity -> ResourceDefinition<'ctx> -> ResponseBuilder<'ctx> -> HttpHandler) option
abstract PostSelf:
('ctx
-> Request
-> Preconditions<'ctx>
-> BoxedEntity
-> ResourceDefinition<'ctx>
-> ResponseBuilder<'ctx>
-> HttpHandler) option
abstract PatchSelf:
('ctx
-> Request
-> ParentResourceTypeName
-> Preconditions<'ctx>
-> BoxedEntity
-> ResourceDefinition<'ctx>
-> ResponseBuilder<'ctx>
-> HttpHandler) option
abstract DeleteSelf:
('ctx
-> Request
-> Preconditions<'ctx>
-> BoxedEntity
-> ResourceDefinition<'ctx>
-> ResponseBuilder<'ctx>
-> HttpHandler) option
type internal ToOneRelationship<'ctx> =
abstract Name: RelationshipName
abstract SelfLink: bool
abstract RelatedLink: bool
abstract AllowedTypes: ICollection<ResourceTypeName> option
abstract BoxedGetRelated: ('ctx -> BoxedEntity -> Task<Skippable<ResourceDefinition<'ctx> * BoxedEntity>>) option
abstract GetLinkageIfNotIncluded: 'ctx -> BoxedEntity -> Task<Skippable<ResourceIdentifier>>
abstract SkipRelationship: 'ctx -> BoxedEntity -> bool
type ToOneRelationshipRelatedGetter<'ctx, 'entity, 'relatedEntity, 'relatedId> = internal {
name: string
idGetter: RequestGetter<'ctx, ('relatedId * ResourceIdentifier) option>
getRelated: ResourceLookup<'ctx, 'relatedEntity, 'relatedId>
} with
static member internal Create
(
name,
idGetter: RequestGetter<'ctx, ('relatedId * ResourceIdentifier) option>,
getRelated: ResourceLookup<'ctx, 'relatedEntity, 'relatedId>
) : ToOneRelationshipRelatedGetter<'ctx, 'entity, 'relatedEntity, 'relatedId> =
{
name = name
idGetter = idGetter
getRelated = getRelated
}
member this.Optional =
{ new RequestGetter<'ctx, 'relatedEntity option> with
member _.FieldName = Some this.name
member _.QueryParamName = None
member _.Get(ctx, req, includedTypeAndId) =
this.idGetter.Get(ctx, req, includedTypeAndId)
|> TaskResult.bind (
Option.traverseTaskResult (fun (resId, identifier) ->
this.getRelated.GetById ctx resId
|> TaskResult.mapError (fun _ -> [
relatedResourceNotFound
identifier.``type``
identifier.id
("/data/relationships/" + this.name + "/data")
])
|> TaskResult.requireSome [
relatedResourceNotFound
identifier.``type``
identifier.id
("/data/relationships/" + this.name + "/data")
]
)
)
}
interface OptionalRequestGetter<'ctx, 'relatedEntity> with
member this.FieldName = Some this.name
member this.QueryParamName = None
member this.Get(ctx, req, includedTypeAndId) =
this.Optional.Get(ctx, req, includedTypeAndId)
interface RequestGetter<'ctx, 'relatedEntity> with
member this.FieldName = Some this.name
member this.QueryParamName = None
member this.Get(ctx, req, includedTypeAndId) =
task {
let! pointer = Request.pointerForMissingRel includedTypeAndId req
return!
this.Optional.Get(ctx, req, includedTypeAndId)
|> TaskResult.requireSome [ reqParserMissingRequiredRel this.name pointer ]
}
type ToOneRelationshipIncludedGetter<'ctx, 'relatedEntity> = internal {
name: string
getParser: RequestParserHelper<'ctx> -> RequestParser<'ctx, 'relatedEntity>
allowedTypes: ResourceTypeName list
} with
static member internal Create
(
name,
getParser,
allowedTypes
) : ToOneRelationshipIncludedGetter<'ctx, 'relatedEntity> =
{
name = name
getParser = getParser
allowedTypes = allowedTypes
}
member this.Optional =
{ new RequestGetter<'ctx, 'relatedEntity option> with
member _.FieldName = Some this.name
member _.QueryParamName = None
member _.Get(ctx, req, includedTypeAndId) =
task {
match! Request.getRelsAndPointer includedTypeAndId req with
| Error errs -> return Error errs
| Ok None -> return Ok None
| Ok(Some(rels, relsPointer)) ->
match rels.TryGetValue this.name with
| true, (:? ToOne as rel) ->
match rel with
| { data = Skip } ->
return Error [ relMissingData this.name (relsPointer + "/" + this.name) ]
| { data = Include identifier } when
not (this.allowedTypes |> List.contains identifier.``type``)
->
let pointer = relsPointer + "/" + this.name + "/data/type"
return Error [ relInvalidType this.name identifier.``type`` this.allowedTypes pointer ]
| { data = Include identifier } ->
return!
RequestParserHelper<'ctx>(ctx, req, (identifier.``type``, identifier.id))
|> this.getParser
|> fun p -> p.ParseTask()
|> TaskResult.map Some
| true, x ->
return
failwith
$"Framework bug: Expected relationship '%s{this.name}' to be deserialized to %s{typeof<ToOne>.FullName}, but was %s{x.GetType().FullName}"
| false, _ -> return Ok None
}
}
interface OptionalRequestGetter<'ctx, 'relatedEntity> with
member this.FieldName = Some this.name
member this.QueryParamName = None
member this.Get(ctx, req, includedTypeAndId) =
this.Optional.Get(ctx, req, includedTypeAndId)
interface RequestGetter<'ctx, 'relatedEntity> with
member this.FieldName = Some this.name
member this.QueryParamName = None
member this.Get(ctx, req, includedTypeAndId) =
task {
let! pointer = Request.pointerForMissingRel includedTypeAndId req
return!
this.Optional.Get(ctx, req, includedTypeAndId)
|> TaskResult.requireSome [ reqParserMissingRequiredRel this.name pointer ]
}
type ToOneRelationship<'ctx, 'setCtx, 'entity, 'relatedEntity, 'relatedId> = internal {
name: string
setOrder: int
mapSetCtx: 'ctx -> 'entity -> Task<Result<'setCtx, Error list>>
resolveEntity: ('relatedEntity -> PolymorphicBuilder<'ctx>) option
resolveId: ('relatedId -> ResourceDefinition<'ctx, 'relatedEntity, 'relatedId>) option
idParsers:
Map<ResourceTypeName, 'ctx -> ResourceId -> Task<Result<'relatedId, (ParsedValueInfo -> Error) list>>> option
get: ('ctx -> 'entity -> Task<'relatedEntity Skippable>) option
set:
('ctx -> 'setCtx -> Pointer -> 'relatedId * ResourceIdentifier -> 'entity -> Task<Result<'entity, Error list>>) option
getLinkageIfNotIncluded: 'ctx -> 'entity -> Task<ResourceIdentifier Skippable>
skipRelationship: 'ctx -> 'entity -> bool
hasConstraints: bool
getConstraints: 'ctx -> 'entity -> Task<(string * obj) list>
beforeModifySelf: 'setCtx -> 'entity -> Task<Result<'entity, Error list>>
afterModifySelf: ('setCtx -> 'entity -> 'entity -> Task<Result<'entity, Error list>>) option
modifyGetRelatedResponse: 'ctx -> 'entity -> 'relatedEntity -> HttpHandler
modifyGetSelfResponse: 'ctx -> 'entity -> 'relatedEntity -> HttpHandler
modifyPatchSelfOkResponse: 'setCtx -> 'entity -> 'relatedEntity -> HttpHandler
modifyPatchSelfAcceptedResponse: 'setCtx -> 'entity -> HttpHandler
patchSelfReturn202Accepted: bool
} with
static member internal Create
(
name: string,
mapSetCtx,
resolveEntity,
resolveId,
idParsers
) : ToOneRelationship<'ctx, 'setCtx, 'entity, 'relatedEntity, 'relatedId> =
{
name = name
setOrder = 0
mapSetCtx = mapSetCtx
resolveEntity = resolveEntity
resolveId = resolveId
idParsers = idParsers
get = None
set = None
getLinkageIfNotIncluded = fun _ _ -> Task.result Skip
skipRelationship = fun _ _ -> false
hasConstraints = false
getConstraints = fun _ _ -> Task.result []
beforeModifySelf = fun _ e -> Ok e |> Task.result
afterModifySelf = None
modifyGetRelatedResponse = fun _ _ _ -> fun next ctx -> next ctx
modifyGetSelfResponse = fun _ _ _ -> fun next ctx -> next ctx
modifyPatchSelfOkResponse = fun _ _ _ -> fun next ctx -> next ctx
modifyPatchSelfAcceptedResponse = fun _ _ -> fun next ctx -> next ctx
patchSelfReturn202Accepted = false
}
member private _.toIdSetter (getRelated: ResourceLookup<'ctx, 'lookupType, 'relatedId>) entitySetter =
fun ctx setCtx (dataPointer: Pointer) (relatedId, identifier: ResourceIdentifier) entity ->
getRelated.GetById ctx relatedId
|> TaskResult.mapError (List.map (Error.setSourcePointer dataPointer))
|> TaskResult.requireSome [ relatedResourceNotFound identifier.``type`` identifier.id dataPointer ]
|> TaskResult.bind (fun r ->
entitySetter setCtx r entity
|> TaskResult.mapError (List.map (Error.setSourcePointer dataPointer))
)
member private this.OptionalWithIdentifier =
{ new RequestGetter<'ctx, ('relatedId * ResourceIdentifier) option> with
member _.FieldName = Some this.name
member _.QueryParamName = None
member _.Get(ctx, req, includedTypeAndId) =
task {
let idParsers =
this.idParsers
|> Option.defaultWith (fun () ->
failwith
$"Attempted to parse resource ID for polymorphic relationship '%s{this.name}', but no ID parsers have been specified."
)
match! Request.getRelsAndPointer includedTypeAndId req with
| Error errs -> return Error errs
| Ok None -> return Ok None
| Ok(Some(rels, relsPointer)) ->
match rels.TryGetValue this.name with
| true, (:? ToOne as rel) ->
match rel with
| { data = Skip } ->
return Error [ relMissingData this.name (relsPointer + "/" + this.name) ]
| { data = Include identifier } ->
match idParsers.TryGetValue identifier.``type`` with
| false, _ ->
let allowedTypes = idParsers |> Map.toList |> List.map fst
let pointer = relsPointer + "/" + this.name + "/data/type"
return Error [ relInvalidType this.name identifier.``type`` allowedTypes pointer ]
| true, parseId ->
return!
parseId ctx identifier.id
// Ignore ID parsing errors; in the context of fetching a related resource by ID,
// this just means that the resource does not exist, which is a more helpful result.
|> TaskResult.mapError (fun _ -> [
relatedResourceNotFound
identifier.``type``
identifier.id
(relsPointer + "/" + this.name + "/data")
])
|> TaskResult.map (fun x -> Some(x, identifier))
| true, x ->
return
failwith
$"Framework bug: Expected relationship '%s{this.name}' to be deserialized to %s{typeof<ToOne>.FullName}, but was %s{x.GetType().FullName}"
| false, _ -> return Ok None
}
}
member this.Optional =
{ new RequestGetter<'ctx, 'relatedId option> with
member _.FieldName = this.OptionalWithIdentifier.FieldName
member _.QueryParamName = this.OptionalWithIdentifier.QueryParamName
member _.Get(ctx, req, includedTypeAndId) =
this.OptionalWithIdentifier.Get(ctx, req, includedTypeAndId)
|> AsyncResult.map (Option.map fst)
}
interface OptionalRequestGetter<'ctx, 'relatedId> with
member this.FieldName = Some this.name
member this.QueryParamName = None
member this.Get(ctx, req, includedTypeAndId) =
this.Optional.Get(ctx, req, includedTypeAndId)
interface RequestGetter<'ctx, 'relatedId> with
member this.FieldName = Some this.name
member this.QueryParamName = None
member this.Get(ctx, req, includedTypeAndId) =
task {
let! pointer = Request.pointerForMissingRel includedTypeAndId req
return!
this.Optional.Get(ctx, req, includedTypeAndId)
|> TaskResult.requireSome [ reqParserMissingRequiredRel this.name pointer ]
}
interface ProhibitedRequestGetter with
member this.FieldName = Some this.name
member this.QueryParamName = None
member this.GetErrors(req, includedTypeAndId) =
task {
match! req.Document.Value with
| Error errs -> return errs
| Ok(Some {
data = Some { relationships = Include rels }
}) when rels.ContainsKey this.name ->
let! pointerForMissingRel = Request.pointerForMissingRel includedTypeAndId req
let pointer = pointerForMissingRel + "/" + this.name
return [ reqParserProhibitedRel this.name pointer ]
| _ -> return []
}
interface FieldSetter<'ctx> with
member this.Names = Set.singleton this.name
member this.SetOrder = this.setOrder
member this.Set ctx req entity numSetters =
task {
match! req.Document.Value with
| Error errs -> return Error errs
| Ok(Some {
data = Some { relationships = Include rels }
}) ->
match this.set, rels.TryGetValue this.name with
| _, (false, _) -> return Ok(entity, false) // not provided in request
| None, (true, _) ->
if numSetters[this.name] > 1 then
// Provided in request and no setter, but there exists another setter, so ignore
return Ok(entity, false)
else
return Error [ setRelReadOnly this.name ("/data/relationships/" + this.name) ]
| Some set, (true, (:? ToOne as rel)) ->
match! this.mapSetCtx ctx (unbox<'entity> entity) with
| Error errs -> return Error errs
| Ok setCtx ->
let idParsers =
this.idParsers
|> Option.defaultWith (fun () ->
failwithf
"Framework bug: Relationship setter defined without ID parsers. This should be caught at startup."
)
match rel.data with
| Skip -> return Error [ relMissingData this.name ("/data/relationships/" + this.name) ]
| Include identifier ->
match idParsers.TryGetValue identifier.``type`` with
| false, _ ->
let allowedTypes = idParsers |> Map.toList |> List.map fst
let pointer = "/data/relationships/" + this.name + "/data/type"
return Error [ relInvalidType this.name identifier.``type`` allowedTypes pointer ]
| true, parseId ->
return!
parseId ctx identifier.id
// Ignore ID parsing errors; in the context of fetching a related resource by ID,
// this just means that the resource does not exist, which is a more helpful result.
|> TaskResult.mapError (fun _ -> [
relatedResourceNotFound
identifier.``type``
identifier.id
("/data/relationships/" + this.name + "/data")
])
|> TaskResult.bind (fun domain ->
set
ctx
setCtx
("/data/relationships/" + this.name + "/data")
(domain, identifier)
(unbox<'entity> entity)
)
|> TaskResult.map (fun e -> box<'entity> e, true)
| Some _, (true, rel) ->
return
failwith
$"Framework bug: Expected relationship '%s{this.name}' to be deserialized to %s{typeof<ToOne>.FullName}, but was %s{rel.GetType().FullName}"
| _ -> return Ok(entity, false) // no relationships provided
}
interface ToOneRelationship<'ctx> with
member this.Name = this.name
member this.SelfLink = this.get.IsSome
member this.RelatedLink = this.get.IsSome
member this.AllowedTypes = this.idParsers |> Option.map Map.keys
member this.BoxedGetRelated =
this.get
|> Option.map (fun getRelated ->
let resolveEntity =
this.resolveEntity
|> Option.defaultWith (fun () ->
failwithf
"Framework bug: Relationship getter defined without entity resolver. This should be caught at startup."
)
fun ctx entity ->
getRelated ctx (unbox<'entity> entity)
|> Task.map (
Skippable.map (fun x ->
let b = resolveEntity x
b.resourceDef, b.entity
)
)
)
member this.GetLinkageIfNotIncluded ctx entity =
this.getLinkageIfNotIncluded ctx (unbox<'entity> entity)
member this.SkipRelationship ctx entity =
this.skipRelationship ctx (unbox<'entity> entity)
member this.Related(getRelated: ResourceLookup<'ctx, 'lookupType, 'relatedId>) =
ToOneRelationshipRelatedGetter<'ctx, 'entity, 'lookupType, 'relatedId>
.Create(this.name, this.OptionalWithIdentifier, getRelated)
member this.Included(getParser: RequestParserHelper<'ctx> -> RequestParser<'ctx, 'relatedEntity>) =
ToOneRelationshipIncludedGetter.Create(
this.name,
getParser,
this.idParsers
|> Option.map (Map.toList >> List.map fst)
|> Option.defaultValue []
)
interface Relationship<'ctx, 'entity, 'relatedEntity, 'relatedId> with
member this.Name = this.name
interface FieldQueryParser<'ctx, 'entity, 'relatedId, string> with
member this.Name = this.name
member this.ToDomain ctx getInfo str =
match this.idParsers |> Option.defaultValue Map.empty |> Map.toList with
| [] ->
failwith
$"Relationship '%s{this.name}' does not contain any ID parsers and may not be used to parse query IDs"
| [ _, parseId ] ->
parseId ctx str
|> TaskResult.mapError (List.map (fun getErr -> getErr (getInfo str)))
| _ :: _ :: _ ->
failwith
$"Relationship '%s{this.name}' contains ID parsers for several types and may therefore not be used to parse query IDs"
interface Field<'ctx> with
member this.Name = this.name
interface ConstrainedField<'ctx> with
member this.Name = this.name
member this.HasConstraints = this.hasConstraints
member this.BoxedGetConstraints ctx e =
this.getConstraints ctx (unbox<'entity> e)
member this.RequiresExplicitInclude = false
interface RelationshipHandlers<'ctx> with
member this.Name = this.name
member _.IsToMany = false
member this.IsSettable = this.set.IsSome
member this.IsSettableButNotGettable = this.set.IsSome && this.get.IsNone
member this.IsSettableWithoutPersist = this.set.IsSome && this.afterModifySelf.IsNone
member this.GetRelated =
this.get
|> Option.map (fun getRelated ->
let resolveEntity =
this.resolveEntity
|> Option.defaultWith (fun () ->
failwithf
"Framework bug: Relationship getter defined without entity resolver. This should be caught at startup."
)
fun ctx req entity resDef resp ->
fun next httpCtx ->
task {
match StrictModeHelpers.checkForUnknownQueryParameters<'ctx> httpCtx req Set.empty with
| Error errs -> return! handleErrors errs next httpCtx
| Ok() ->
let entity = unbox<'entity> entity
match! getRelated ctx entity with
| Skip -> return! handleErrors [ getRelWhileSkip () ] next httpCtx
| Include relatedEntity ->
let b = resolveEntity relatedEntity
let! doc, _ = resp.Write httpCtx ctx req (b.resourceDef, b.entity)
let! fieldTrackerHandler =
match this.idParsers with
| None ->
logFieldTrackerPolymorphicRelTraversalWarning
httpCtx
resDef.TypeName
this.name
Task.result (fun next ctx -> next ctx)
| Some parsers ->
let primaryResourceTypes = parsers.Keys |> Seq.toList
httpCtx.RequestServices
.GetRequiredService<FieldTracker<'ctx>>()
.TrackFields(
primaryResourceTypes,
ctx,
req,
(resDef.TypeName, this.name)
)
let handler =
setStatusCode 200
>=> this.modifyGetRelatedResponse ctx entity relatedEntity
>=> fieldTrackerHandler
>=> jsonApiWithETag<'ctx> doc
return! handler next httpCtx
}
)
member this.GetSelf =
this.get
|> Option.map (fun getRelated ->
let resolveEntity =
this.resolveEntity
|> Option.defaultWith (fun () ->
failwithf
"Framework bug: Relationship getter defined without entity resolver. This should be caught at startup."
)
fun ctx req entity resDef resp ->
fun next httpCtx ->
task {
match StrictModeHelpers.checkForUnknownQueryParameters<'ctx> httpCtx req Set.empty with
| Error errs -> return! handleErrors errs next httpCtx
| Ok() ->
let entity = unbox<'entity> entity
match! getRelated ctx entity with
| Skip -> return! handleErrors [ getRelWhileSkip () ] next httpCtx
| Include relatedEntity ->
let b = resolveEntity relatedEntity
let! included = getIncludedForSelfUrl httpCtx ctx req resp this.name resDef entity
let doc: ResourceIdentifierDocument = {
jsonapi = Skip
links = Skip
meta = Skip
data =
Some {
``type`` = b.resourceDef.TypeName
id = b.resourceDef.GetIdBoxed b.entity
}
included = included
}
let! fieldTrackerHandler =
httpCtx.RequestServices
.GetRequiredService<FieldTracker<'ctx>>()
.TrackFields(
[ resDef.TypeName ],
ctx,
req,
(resDef.TypeName, this.name),
this.name
)
let handler =
setStatusCode 200
>=> this.modifyGetSelfResponse ctx entity relatedEntity
>=> fieldTrackerHandler
>=> jsonApiWithETag<'ctx> doc
return! handler next httpCtx
}
)
member _.PostSelf = None
member this.PatchSelf =
(this.get, this.set)
||> Option.map2 (fun getRelated set ->
let idParsers =
this.idParsers
|> Option.defaultWith (fun () ->
failwithf
"Framework bug: Relationship setter defined without ID parsers. This should be caught at startup."
)
let resolveEntity =
this.resolveEntity
|> Option.defaultWith (fun () ->
failwithf
"Framework bug: Relationship getter defined without entity resolver. This should be caught at startup."
)
let afterModifySelf =
this.afterModifySelf
|> Option.defaultWith (fun () ->
failwithf
"Framework bug: Relationship setter defined without AfterModifySelf. This should be caught at startup."
)
fun ctx req parentTypeName preconditions entity0 resDef resp ->
fun next httpCtx ->
task {
match StrictModeHelpers.checkForUnknownQueryParameters<'ctx> httpCtx req Set.empty with
| Error errs -> return! handleErrors errs next httpCtx
| Ok() ->
match! this.mapSetCtx ctx (unbox<'entity> entity0) with
| Error errs -> return! handleErrors errs next httpCtx
| Ok setCtx ->
match! req.IdentifierDocument.Value with
| Error errs -> return! handleErrors errs next httpCtx
| Ok None -> return! handleErrors [ modifyRelSelfMissingData "" ] next httpCtx
| Ok(Some { data = None }) ->
return!
handleErrors
[ relInvalidNull parentTypeName this.name "/data" ]
next
httpCtx
| Ok(Some { data = Some id }) ->
match preconditions.Validate httpCtx ctx entity0 with
| Error errors -> return! handleErrors errors next httpCtx
| Ok() ->
match! this.beforeModifySelf setCtx (unbox<'entity> entity0) with
| Error errors -> return! handleErrors errors next httpCtx
| Ok entity1 ->
match idParsers.TryGetValue id.``type`` with
| false, _ ->
let allowedTypes = idParsers |> Map.toList |> List.map fst
return!
handleErrors
[
relInvalidTypeSelf
id.``type``
allowedTypes
"/data/type"
]
next
httpCtx
| true, parseId ->
let! entity2Res =
parseId ctx id.id
// Ignore ID parsing errors; in the context of fetching a related resource by ID,
// this just means that the resource does not exist, which is a more helpful result.
|> TaskResult.mapError (fun _ -> [
relatedResourceNotFound id.``type`` id.id "/data"
])
|> TaskResult.bind (fun domain ->
set
ctx
setCtx
"/data"
(domain, id)
(unbox<'entity> entity1)
)
match entity2Res with
| Error errs -> return! handleErrors errs next httpCtx
| Ok entity2 ->
match!
afterModifySelf
setCtx
(unbox<'entity> entity0)
(unbox<'entity> entity2)
with
| Error errors -> return! handleErrors errors next httpCtx
| Ok entity3 ->
if this.patchSelfReturn202Accepted then
let handler =
setStatusCode 202
>=> this.modifyPatchSelfAcceptedResponse
setCtx
(unbox<'entity> entity2)
return! handler next httpCtx
else
match! getRelated ctx (unbox<'entity> entity3) with
| Skip ->
let logger =
httpCtx.GetLogger("Felicity.Relationships")
logger.LogError(
"Relationship {RelationshipName} was updated using a self URL, but no success response could be returned because the relationship getter returned Skip. This violates the JSON:API specification. Make sure that the relationship getter never returns Skip after an update.",
this.name
)
return!
handleErrors
[ relModifySelfWhileSkip () ]
next
httpCtx
| Include relatedEntity ->
let b = resolveEntity relatedEntity
let! included =
getIncludedForSelfUrl
httpCtx
ctx
req
resp
this.name
resDef
entity3
let doc: ResourceIdentifierDocument = {
jsonapi = Skip
links = Skip
meta = Skip
data =
Some {
``type`` = b.resourceDef.TypeName
id = b.resourceDef.GetIdBoxed b.entity
}
included = included
}
let! fieldTrackerHandler =
httpCtx.RequestServices
.GetRequiredService<FieldTracker<'ctx>>()
.TrackFields(
[ resDef.TypeName ],
ctx,
req,
(resDef.TypeName, this.name),
this.name
)
let handler =
setStatusCode 200
>=> this.modifyPatchSelfOkResponse
setCtx
(unbox<'entity> entity3)
relatedEntity
>=> fieldTrackerHandler
>=> jsonApiWithETag<'ctx> doc
return! handler next httpCtx
}
)
member _.DeleteSelf = None
member this.Name = this.name
/// Specify the order in which this field will be set relative to other fields during
/// POST collection and PATCH resource requests. By default, all fields have SetOrder =
/// 0. Negative numbers are allowed. The order of fields with identical SetOrder is
/// unspecified.
member this.SetOrder(i: int) = { this with setOrder = i }
member this.GetTaskSkip(get: Func<'ctx, 'entity, Task<'relatedEntity Skippable>>) =
if this.resolveEntity.IsNone then
failwithf "Can only add getter if the polymorphic resource definition contains an entity resolver."
{
this with
get = Some(fun ctx e -> get.Invoke(ctx, e))
}
member this.GetTaskSkip(get: Func<'entity, Task<'relatedEntity Skippable>>) =
this.GetTaskSkip(fun _ e -> get.Invoke(e))
member this.GetAsyncSkip(get: Func<'ctx, 'entity, Async<'relatedEntity Skippable>>) =
this.GetTaskSkip(Task.liftAsyncFunc2 get)
member this.GetAsyncSkip(get: Func<'entity, Async<'relatedEntity Skippable>>) =
this.GetTaskSkip(Task.liftAsyncFunc get)
member this.GetTask(get: Func<'ctx, 'entity, Task<'relatedEntity>>) =
this.GetTaskSkip(fun ctx r -> get.Invoke(ctx, r) |> Task.map Include)
member this.GetTask(get: Func<'entity, Task<'relatedEntity>>) =
this.GetTaskSkip(fun _ r -> get.Invoke r |> Task.map Include)
member this.GetAsync(get: Func<'ctx, 'entity, Async<'relatedEntity>>) = this.GetTask(Task.liftAsyncFunc2 get)
member this.GetAsync(get: Func<'entity, Async<'relatedEntity>>) = this.GetTask(Task.liftAsyncFunc get)
member this.GetSkip(get: Func<'ctx, 'entity, Skippable<'relatedEntity>>) =
this.GetTaskSkip(fun ctx r -> get.Invoke(ctx, r) |> Task.result)
member this.GetSkip(get: Func<'entity, Skippable<'relatedEntity>>) =
this.GetTaskSkip(fun _ r -> get.Invoke(r) |> Task.result)
member this.Get(get: Func<'ctx, 'entity, 'relatedEntity>) =
this.GetTaskSkip(fun ctx r -> get.Invoke(ctx, r) |> Include |> Task.result)
member this.Get(get: Func<'entity, 'relatedEntity>) =
this.GetTaskSkip(fun _ r -> get.Invoke r |> Include |> Task.result)
member this.GetLinkageIfNotIncludedTaskSkip(get: Func<'ctx, 'entity, Task<'relatedId Skippable>>) =
if this.resolveId.IsNone then
failwithf "Can only add linkage getter if the polymorphic resource definition contains an ID resolver."
{
this with
getLinkageIfNotIncluded =
fun ctx e ->
task {
match! get.Invoke(ctx, e) with
| Skip -> return Skip
| Include relatedId ->
let resDef = this.resolveId.Value relatedId
return
Include {
``type`` = resDef.name
id = resDef.id.fromDomain relatedId
}
}
}
member this.GetLinkageIfNotIncludedAsyncSkip(get: Func<'ctx, 'entity, Async<'relatedId Skippable>>) =
this.GetLinkageIfNotIncludedTaskSkip(Task.liftAsyncFunc2 get)
member this.GetLinkageIfNotIncludedTask(get: Func<'ctx, 'entity, Task<'relatedId>>) =
this.GetLinkageIfNotIncludedTaskSkip(fun ctx r -> get.Invoke(ctx, r) |> Task.map Include)
member this.GetLinkageIfNotIncludedTask(get: Func<'entity, Task<'relatedId>>) =
this.GetLinkageIfNotIncludedTaskSkip(fun _ r -> get.Invoke r |> Task.map Include)
member this.GetLinkageIfNotIncludedAsync(get: Func<'ctx, 'entity, Async<'relatedId>>) =
this.GetLinkageIfNotIncludedTask(Task.liftAsyncFunc2 get)
member this.GetLinkageIfNotIncludedAsync(get: Func<'entity, Async<'relatedId>>) =
this.GetLinkageIfNotIncludedTask(Task.liftAsyncFunc get)
member this.GetLinkageIfNotIncludedSkip(get: Func<'ctx, 'entity, Skippable<'relatedId>>) =
this.GetLinkageIfNotIncludedTaskSkip(fun ctx r -> get.Invoke(ctx, r) |> Task.result)
member this.GetLinkageIfNotIncluded(get: Func<'ctx, 'entity, 'relatedId>) =
this.GetLinkageIfNotIncludedTaskSkip(fun ctx r -> get.Invoke(ctx, r) |> Include |> Task.result)
member this.GetLinkageIfNotIncluded(get: Func<'entity, 'relatedId>) =
this.GetLinkageIfNotIncludedTaskSkip(fun _ r -> get.Invoke r |> Include |> Task.result)
/// Omits the entire relationship (links, data, and meta) in the returned resource if the predicate returns true. If
/// using one of the Get...Skip methods, this method should also be called. Otherwise, relationship links will always
/// be present in the response, but GET operations against them will return an error if the getter returns Skip.
member this.SkipRelationshipIf(predicate: 'ctx -> 'entity -> bool) = {
this with
skipRelationship = predicate
}
/// Omits the entire relationship (links, data, and meta) in the returned resource if the predicate returns true. If
/// using one of the Get...Skip methods, this method should also be called. Otherwise, relationship links will always
/// be present in the response, but GET operations against them will return an error if the getter returns Skip.
member this.SkipRelationshipIf(predicate: 'entity -> bool) = {
this with
skipRelationship = fun _ e -> predicate e
}
member private this.SetTaskRes
(set: Func<'ctx, 'setCtx, Pointer, 'relatedId * ResourceIdentifier, 'entity, Task<Result<'entity, Error list>>>)
=
if this.idParsers.IsNone then
failwithf "Can only add setter if the polymorphic resource definition contains ID parsers."
{
this with
set =
Some(fun ctx setCtx ptr relIdWithIdentifier e ->
set.Invoke(ctx, setCtx, ptr, relIdWithIdentifier, e)
)
}
member this.SetTaskRes(set: Func<'setCtx, 'relatedId, 'entity, Task<Result<'entity, Error list>>>) =
this.SetTaskRes(fun _ ctx pointer relIdWithIdentifier e ->
set.Invoke(ctx, fst relIdWithIdentifier, e)
|> TaskResult.mapError (List.map (Error.setSourcePointer pointer))
)
member this.SetTaskRes(set: Func<'relatedId, 'entity, Task<Result<'entity, Error list>>>) =
this.SetTaskRes(fun _ id e -> set.Invoke(id, e))
member this.SetTaskRes
(
getRelated: ResourceLookup<'ctx, 'lookupType, 'relatedId>,
set: Func<'setCtx, 'lookupType, 'entity, Task<Result<'entity, Error list>>>
) =
this.SetTaskRes(this.toIdSetter getRelated (fun ctx relId e -> set.Invoke(ctx, relId, e)))
member this.SetTaskRes
(
getRelated: ResourceLookup<'ctx, 'lookupType, 'relatedId>,
set: Func<'lookupType, 'entity, Task<Result<'entity, Error list>>>
) =
this.SetTaskRes(this.toIdSetter getRelated (fun _ id e -> set.Invoke(id, e)))
member this.SetAsyncRes(set: Func<'setCtx, 'relatedId, 'entity, Async<Result<'entity, Error list>>>) =
this.SetTaskRes(Task.liftAsyncFunc3 set)
member this.SetAsyncRes(set: Func<'relatedId, 'entity, Async<Result<'entity, Error list>>>) =
this.SetTaskRes(Task.liftAsyncFunc2 set)
member this.SetAsyncRes
(
getRelated: ResourceLookup<'ctx, 'lookupType, 'relatedId>,
set: Func<'setCtx, 'lookupType, 'entity, Async<Result<'entity, Error list>>>
) =
this.SetTaskRes(getRelated, Task.liftAsyncFunc3 set)
member this.SetAsyncRes