-
Notifications
You must be signed in to change notification settings - Fork 0
/
Operations.fs
2877 lines (2342 loc) · 123 KB
/
Operations.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.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 Microsoft.Net.Http.Headers
open Giraffe
open Errors
module private PreconditionHelpers =
let validate (httpCtx: HttpContext) ctx getETag getLastModified isOptional =
let eTag = getETag ctx
let lastModified = getLastModified ctx
let res = httpCtx.ValidatePreconditions(eTag, lastModified)
// Clear headers because response-level ETag/Last-Modified headers don't
// necessarily make sense in JSON:API due to compound documents; these values
// should be communicated as attributes or meta.
httpCtx.Response.Headers.Remove "ETag" |> ignore
httpCtx.Response.Headers.Remove "Last-Modified" |> ignore
match res with
| ConditionFailed -> Error [ preconditionFailed eTag.IsSome lastModified.IsSome ]
| NoConditionsSpecified when not isOptional -> Error [ preconditionRequired eTag.IsSome lastModified.IsSome ]
| _ -> Ok()
module internal StrictModeHelpers =
[<RequiresExplicitTypeArguments>]
let checkForUnknownQueryParameters<'ctx>
(httpCtx: HttpContext)
(req: Request)
(consumed: Set<ConsumedQueryParamName>)
=
let strictMode = httpCtx.GetService<UnknownQueryParamStrictMode<'ctx>>()
let linkConfig = httpCtx.GetService<LinkConfig<'ctx>>()
// Quick return if strict mode is not enabled
if strictMode = UnknownQueryParamStrictMode.Ignore then
Ok()
else
let inRequest =
httpCtx.Request.Query.Keys
|> Set.ofSeq
// Ignore sparse fieldset, include, and skip link parameters
|> Set.filter (fun s ->
s <> "include"
&& not (req.Fieldsets.Keys |> Seq.exists (fun tn -> "fields[" + tn + "]" = s))
&& not (linkConfig.QueryParamNames |> Seq.contains s)
)
let inRequestButNotConsumed = inRequest - consumed
if inRequestButNotConsumed.IsEmpty then
Ok()
else
match strictMode with
| UnknownQueryParamStrictMode.Ignore -> Ok()
| UnknownQueryParamStrictMode.Warn logLevel ->
inRequestButNotConsumed
|> Seq.iter (fun paramName ->
let logger = httpCtx.GetService<ILoggerFactory>().CreateLogger "Felicity.StrictMode"
logger.Log(logLevel, "Request contained unknown query parameter {ParamName}", paramName)
)
Ok()
| UnknownQueryParamStrictMode.Error ->
inRequestButNotConsumed
|> Set.toList
|> List.map strictModeUnknownOrUnusedQueryParam
|> Error
type internal Preconditions<'ctx> =
abstract Validate: HttpContext -> 'ctx -> BoxedEntity -> Result<unit, Error list>
module internal Preconditions =
let noop =
{ new Preconditions<'ctx> with
member _.Validate _ _ _ = Ok()
}
type Preconditions<'ctx, 'entity> = internal {
getETag: 'ctx * 'entity -> EntityTagHeaderValue option
getLastModified: 'ctx * 'entity -> DateTimeOffset option
isOptional: bool
} with
static member internal Create() : Preconditions<'ctx, 'entity> = {
getETag = fun _ -> None
getLastModified = fun _ -> None
isOptional = false
}
interface Preconditions<'ctx> with
member this.Validate httpCtx ctx entity =
PreconditionHelpers.validate
httpCtx
(ctx, unbox<'entity> entity)
this.getETag
this.getLastModified
this.isOptional
member this.ETag(getETag: Func<'ctx, 'entity, EntityTagHeaderValue>) = {
this with
getETag = fun (ctx, e) -> getETag.Invoke(ctx, e) |> Some
}
member this.ETag(getETag: Func<'entity, EntityTagHeaderValue>) = this.ETag(fun _ e -> getETag.Invoke e)
member this.LastModified(getLastModified: Func<'ctx, 'entity, DateTimeOffset>) = {
this with
getLastModified = fun (ctx, e) -> getLastModified.Invoke(ctx, e) |> Some
}
member this.LastModified(getLastModified: Func<'entity, DateTimeOffset>) =
this.LastModified(fun _ e -> getLastModified.Invoke e)
member this.Optional = { this with isOptional = true }
type internal ResSpecificResourceLookup<'ctx> =
abstract GetByIdBoxed:
'ctx -> ResourceId -> Task<Result<(ResourceDefinition<'ctx> * BoxedEntity) option, Error list>>
type ResourceLookup<'ctx, 'entity, 'id> =
abstract GetById: 'ctx -> 'id -> Task<Result<'entity option, Error list>>
type internal ResourceLookup<'ctx> =
abstract GetByIdBoxed:
ResourceDefinition<'ctx> -> 'ctx -> ResourceId -> Task<Result<BoxedEntity option, Error list>>
type ResourceLookup<'originalCtx, 'ctx, 'entity, 'id> = internal {
mapCtx: 'originalCtx -> Task<Result<'ctx, Error list>>
getById: 'ctx -> 'id -> Task<Result<'entity option, Error list>>
} with
static member internal Create(mapCtx, getById) : ResourceLookup<'originalCtx, 'ctx, 'entity, 'id> = {
mapCtx = mapCtx
getById = getById
}
interface ResourceLookup<'ctx, 'entity, 'id> with
member this.GetById ctx id = this.getById ctx id
interface ResourceLookup<'originalCtx> with
member this.GetByIdBoxed rDef ctx rawId =
task {
match! rDef.ParseIdBoxed ctx rawId with
// Ignore ID parsing errors; in the context of fetching a resource by ID, this
// just means that the resource does not exist, which is a more helpful result.
| Error _ -> return Ok None
| Ok domainId ->
match! this.mapCtx ctx with
| Error errs -> return Error errs
| Ok mappedCtx ->
let! entity = domainId |> unbox<'id> |> this.getById mappedCtx
return entity |> Result.map (Option.map box)
}
type internal PolymorphicResourceLookup<'ctx> =
abstract GetByIdBoxed:
ResourceDefinition<'ctx> ->
'ctx ->
ResourceId ->
Task<Result<(ResourceDefinition<'ctx> * BoxedEntity) option, Error list>>
type PolymorphicResourceLookup<'originalCtx, 'ctx, 'entity, 'id> = internal {
mapCtx: 'originalCtx -> Task<Result<'ctx, Error list>>
getById: 'ctx -> 'id -> Task<Result<'entity option, Error list>>
getPolyBuilder: 'entity -> PolymorphicBuilder<'originalCtx>
} with
static member internal Create
(
mapCtx,
getById,
getPolyBuilder
) : PolymorphicResourceLookup<'originalCtx, 'ctx, 'entity, 'id> =
{
mapCtx = mapCtx
getById = getById
getPolyBuilder = getPolyBuilder
}
interface ResourceLookup<'ctx, 'entity, 'id> with
member this.GetById ctx id = this.getById ctx id
interface PolymorphicResourceLookup<'originalCtx> with
member this.GetByIdBoxed rDef ctx rawId =
task {
match! rDef.ParseIdBoxed ctx rawId with
// Ignore ID parsing errors; in the context of fetching a resource by ID, this
// just means that the resource does not exist, which is a more helpful result
| Error _ -> return Ok None
| Ok domainId ->
match! this.mapCtx ctx with
| Error errs -> return Error errs
| Ok mappedCtx ->
let! entity = domainId |> unbox<'id> |> this.getById mappedCtx
return
entity
|> Result.map (
Option.map (fun e ->
let b = this.getPolyBuilder e
b.resourceDef, b.entity
)
)
}
type internal GetResourceOperation<'ctx> =
abstract Run: ResourceDefinition<'ctx> -> 'ctx -> Request -> BoxedEntity -> ResponseBuilder<'ctx> -> HttpHandler
type GetResourceOperation<'originalCtx, 'ctx, 'entity, 'id> = internal {
mapCtx: 'originalCtx -> 'entity -> Task<Result<'ctx, Error list>>
modifyResponse: 'ctx -> 'entity -> HttpHandler
} with
static member internal Create(mapCtx) : GetResourceOperation<'originalCtx, 'ctx, 'entity, 'id> = {
mapCtx = mapCtx
modifyResponse = fun _ _ -> fun next ctx -> next ctx
}
interface GetResourceOperation<'originalCtx> with
member this.Run resDef ctx req entity resp =
fun next httpCtx ->
task {
match! this.mapCtx ctx (unbox<'entity> entity) with
| Error errors -> return! handleErrors errors next httpCtx
| Ok mappedCtx ->
match StrictModeHelpers.checkForUnknownQueryParameters<'originalCtx> httpCtx req Set.empty with
| Error errs -> return! handleErrors errs next httpCtx
| Ok() ->
let! doc, _ = resp.Write httpCtx ctx req (resDef, entity)
let! fieldTrackerHandler =
httpCtx.RequestServices
.GetRequiredService<FieldTracker<'originalCtx>>()
.TrackFields([ resDef.TypeName ], ctx, req)
let handler =
setStatusCode 200
>=> this.modifyResponse mappedCtx (unbox<'entity> entity)
>=> fieldTrackerHandler
>=> jsonApiWithETag<'originalCtx> doc
return! handler next httpCtx
}
member this.ModifyResponse(getHandler: 'ctx -> 'entity -> HttpHandler) = {
this with
modifyResponse = getHandler
}
member this.ModifyResponse(f: 'ctx -> 'entity -> HttpContext -> unit) =
this.ModifyResponse(fun ctx e ->
(fun next httpCtx ->
f ctx e httpCtx
next httpCtx
)
)
member this.ModifyResponse(handler: HttpHandler) = this.ModifyResponse(fun _ _ -> handler)
type internal GetCollectionOperation<'ctx> =
abstract Run: ResourceDefinition<'ctx> -> 'ctx -> Request -> ResponseBuilder<'ctx> -> HttpHandler
type GetCollectionOperation<'originalCtx, 'ctx, 'entity, 'id> = internal {
mapCtx: 'originalCtx -> Task<Result<'ctx, Error list>>
getCollection:
'originalCtx
-> 'ctx
-> Request
-> Task<Result<Set<ConsumedFieldName> * Set<ConsumedQueryParamName> * 'entity list, Error list>>
modifyResponse: 'ctx -> 'entity list -> HttpHandler
} with
static member internal Create(mapCtx, getCollection) : GetCollectionOperation<'originalCtx, 'ctx, 'entity, 'id> = {
mapCtx = mapCtx
getCollection = getCollection
modifyResponse = fun _ _ -> fun next ctx -> next ctx
}
interface GetCollectionOperation<'originalCtx> with
member this.Run resDef ctx req resp =
fun next httpCtx ->
task {
match! this.mapCtx ctx with
| Error errors -> return! handleErrors errors next httpCtx
| Ok mappedCtx ->
match! this.getCollection ctx mappedCtx req with
| Error errors -> return! handleErrors errors next httpCtx
| Ok(_, queryNames, entities) ->
match httpCtx.TryGetQueryStringValue "sort", queryNames.Contains "sort" with
| Some _, false -> return! handleErrors [ sortNotSupported () ] next httpCtx
| _ ->
match
StrictModeHelpers.checkForUnknownQueryParameters<'originalCtx>
httpCtx
req
queryNames
with
| Error errs -> return! handleErrors errs next httpCtx
| Ok() ->
let! doc =
resp.WriteList httpCtx ctx req (entities |> List.map (fun e -> resDef, e))
let! fieldTrackerHandler =
httpCtx.RequestServices
.GetRequiredService<FieldTracker<'originalCtx>>()
.TrackFields([ resDef.TypeName ], ctx, req)
let handler =
setStatusCode 200
>=> this.modifyResponse mappedCtx entities
>=> fieldTrackerHandler
>=> jsonApiWithETag<'originalCtx> doc
return! handler next httpCtx
}
member this.ModifyResponse(getHandler: 'ctx -> 'entity list -> HttpHandler) = {
this with
modifyResponse = getHandler
}
member this.ModifyResponse(f: 'ctx -> 'entity list -> HttpContext -> unit) =
this.ModifyResponse(fun ctx es ->
(fun next httpCtx ->
f ctx es httpCtx
next httpCtx
)
)
member this.ModifyResponse(handler: HttpHandler) = this.ModifyResponse(fun _ _ -> handler)
type internal PolymorphicGetCollectionOperation<'ctx> =
abstract Run: ResourceTypeName list -> 'ctx -> Request -> ResponseBuilder<'ctx> -> HttpHandler
type PolymorphicGetCollectionOperation<'originalCtx, 'ctx, 'entity, 'id> = internal {
mapCtx: 'originalCtx -> Task<Result<'ctx, Error list>>
getCollection:
'originalCtx
-> 'ctx
-> Request
-> Task<Result<Set<ConsumedFieldName> * Set<ConsumedQueryParamName> * 'entity list, Error list>>
getPolyBuilder: 'entity -> PolymorphicBuilder<'originalCtx>
modifyResponse: 'ctx -> 'entity list -> HttpHandler
polymorphicResourceTypesForFieldTracking: ResourceTypeName list
} with
static member internal Create
(
mapCtx,
getCollection,
getPolyBuilder
) : PolymorphicGetCollectionOperation<'originalCtx, 'ctx, 'entity, 'id> =
{
mapCtx = mapCtx
getCollection = getCollection
getPolyBuilder = getPolyBuilder
modifyResponse = fun _ _ -> fun next ctx -> next ctx
polymorphicResourceTypesForFieldTracking = []
}
interface PolymorphicGetCollectionOperation<'originalCtx> with
member this.Run collectionResTypes ctx req resp =
fun next httpCtx ->
task {
match! this.mapCtx ctx with
| Error errors -> return! handleErrors errors next httpCtx
| Ok mappedCtx ->
match! this.getCollection ctx mappedCtx req with
| Error errors -> return! handleErrors errors next httpCtx
| Ok(_, queryNames, entities) ->
match httpCtx.TryGetQueryStringValue "sort", queryNames.Contains "sort" with
| Some _, false -> return! handleErrors [ sortNotSupported () ] next httpCtx
| _ ->
match
StrictModeHelpers.checkForUnknownQueryParameters<'originalCtx>
httpCtx
req
queryNames
with
| Error errs -> return! handleErrors errs next httpCtx
| Ok() ->
let! doc =
resp.WriteList
httpCtx
ctx
req
(entities
|> List.map this.getPolyBuilder
|> List.map (fun b -> b.resourceDef, b.entity))
let collectionResTypes =
if this.polymorphicResourceTypesForFieldTracking.IsEmpty then
collectionResTypes
else
this.polymorphicResourceTypesForFieldTracking
let! fieldTrackerHandler =
httpCtx.RequestServices
.GetRequiredService<FieldTracker<'originalCtx>>()
.TrackFields(collectionResTypes, ctx, req)
let handler =
setStatusCode 200
>=> this.modifyResponse mappedCtx entities
>=> fieldTrackerHandler
>=> jsonApiWithETag<'originalCtx> doc
return! handler next httpCtx
}
member this.ModifyResponse(getHandler: 'ctx -> 'entity list -> HttpHandler) = {
this with
modifyResponse = getHandler
}
member this.ModifyResponse(f: 'ctx -> 'entity list -> HttpContext -> unit) =
this.ModifyResponse(fun ctx es ->
(fun next httpCtx ->
f ctx es httpCtx
next httpCtx
)
)
member this.ModifyResponse(handler: HttpHandler) = this.ModifyResponse(fun _ _ -> handler)
/// If you use field tracking (i.e., have called TrackFieldUsage when configuring Felicity) and at least one of the
/// resource types that can be returned by this collection belongs to another collection (i.e., does not have the same
/// collection name as the resource definition this operation belongs to), call this method for each resource type
/// that can be returned by this operation. Otherwise, field tracking won't work properly for this operation.
member this.RegisterResourceType(resourceDef: ResourceDefinition<'ctx, 'otherEntity, 'otherId>) = {
this with
polymorphicResourceTypesForFieldTracking =
resourceDef.name :: this.polymorphicResourceTypesForFieldTracking
|> List.distinct
}
type internal RequestValidationConfig = {
ValidateAccept: bool
ValidateContentType: bool
ValidateQueryParams: bool
}
type internal PostOperation<'ctx> =
abstract Run:
(RequestValidationConfig -> HttpHandler) ->
CollectionName ->
ResourceDefinition<'ctx> ->
'ctx ->
Request ->
BoxedPatcher<'ctx> ->
ResponseBuilder<'ctx> ->
HttpHandler
abstract HasPersist: bool
abstract AllowReadingBody: bool
type PostOperation<'originalCtx, 'ctx, 'entity> = internal {
mapCtx: 'originalCtx -> Request -> Task<Result<'ctx, Error list>>
create:
'originalCtx
-> 'ctx
-> Request
-> Task<Result<Set<ConsumedFieldName> * Set<ConsumedQueryParamName> * 'entity, Error list>>
afterCreate: ('ctx -> 'entity -> Task<Result<'entity, Error list>>) option
modifyResponse: 'ctx -> 'entity -> HttpHandler
return202Accepted: bool
validatePreconditions: bool
preconditionsOptional: bool
getETag: 'ctx -> EntityTagHeaderValue option
getLastModified: 'ctx -> DateTimeOffset option
} with
static member internal Create(mapCtx, create) : PostOperation<'originalCtx, 'ctx, 'entity> = {
mapCtx = mapCtx
create = create
afterCreate = None
modifyResponse = fun _ _ -> fun next ctx -> next ctx
return202Accepted = false
validatePreconditions = false
preconditionsOptional = false
getETag = fun _ -> None
getLastModified = fun _ -> None
}
interface PostOperation<'originalCtx> with
member this.HasPersist = this.afterCreate.IsSome
member this.AllowReadingBody = false
member this.Run validateRequest collName rDef ctx req patch resp =
let validationConfig = {
ValidateAccept = true
ValidateContentType = true
ValidateQueryParams = true
}
validateRequest validationConfig
>=> fun next httpCtx ->
let afterCreate =
this.afterCreate
|> Option.defaultWith (fun () ->
failwithf
"Framework bug: POST operation defined without AfterCreate. This should be caught at startup."
)
task {
match! this.mapCtx ctx req with
| Error errors -> return! handleErrors errors next httpCtx
| Ok mappedCtx ->
let validatePreconditions () =
if this.validatePreconditions then
PreconditionHelpers.validate
httpCtx
mappedCtx
this.getETag
this.getLastModified
this.preconditionsOptional
else
Ok()
match validatePreconditions () with
| Error errors -> return! handleErrors errors next httpCtx
| Ok() ->
match!
this.create ctx mappedCtx req
|> TaskResult.bind (fun (fieldNames, qns, e) ->
box e
|> patch ctx req fieldNames
|> TaskResult.map (fun (e, fns) -> Set.union fns fieldNames, qns, e)
)
with
| Error errors -> return! handleErrors errors next httpCtx
| Ok(ns, queryNames, entity0) ->
match! req.Document.Value with
| Ok(Some { data = Some { id = Include _ } }) when not <| ns.Contains "id" ->
return!
handleErrors [ collPostClientIdNotAllowed collName rDef.TypeName ] next httpCtx
| _ ->
match
StrictModeHelpers.checkForUnknownQueryParameters<'originalCtx>
httpCtx
req
queryNames
with
| Error errs -> return! handleErrors errs next httpCtx
| Ok() ->
match! afterCreate mappedCtx (unbox<'entity> entity0) with
| Error errors -> return! handleErrors errors next httpCtx
| Ok entity1 ->
if this.return202Accepted then
let! fieldTrackerHandler =
httpCtx.RequestServices
.GetRequiredService<FieldTracker<'originalCtx>>()
.TrackFields(
[],
ctx,
req,
consumedFieldNamesWithType = (rDef.TypeName, ns)
)
let handler =
setStatusCode 202
>=> this.modifyResponse mappedCtx (unbox<'entity> entity1)
>=> fieldTrackerHandler
return! handler next httpCtx
else
let! doc, selfUrlOpt = resp.Write httpCtx ctx req (rDef, entity1)
let setLocationHeader =
match selfUrlOpt with
| Some url -> setHttpHeader "Location" (url.ToString())
| _ -> fun next ctx -> next ctx
let! fieldTrackerHandler =
httpCtx.RequestServices
.GetRequiredService<FieldTracker<'originalCtx>>()
.TrackFields(
[ rDef.TypeName ],
ctx,
req,
consumedFieldNamesWithType = (rDef.TypeName, ns)
)
let handler =
setStatusCode 201
>=> setLocationHeader
>=> this.modifyResponse mappedCtx entity1
>=> fieldTrackerHandler
>=> jsonApiWithETag<'originalCtx> doc
return! handler next httpCtx
}
member this.AfterCreateTaskRes(f: Func<'ctx, 'entity, Task<Result<'entity, Error list>>>) = {
this with
afterCreate = Some(fun ctx e -> f.Invoke(ctx, e))
}
member this.AfterCreateTaskRes(f: Func<'ctx, 'entity, Task<Result<unit, Error list>>>) =
this.AfterCreateTaskRes(fun ctx e -> f.Invoke(ctx, e) |> TaskResult.map (fun () -> e))
member this.AfterCreateTaskRes(f: Func<'entity, Task<Result<'entity, Error list>>>) =
this.AfterCreateTaskRes(fun _ e -> f.Invoke e)
member this.AfterCreateTaskRes(f: Func<'entity, Task<Result<unit, Error list>>>) =
this.AfterCreateTaskRes(fun _ e -> f.Invoke e |> TaskResult.map (fun () -> e))
member this.AfterCreateAsyncRes(f: Func<'ctx, 'entity, Async<Result<'entity, Error list>>>) =
this.AfterCreateTaskRes(Task.liftAsyncFunc2 f)
member this.AfterCreateAsyncRes(f: Func<'ctx, 'entity, Async<Result<unit, Error list>>>) =
this.AfterCreateTaskRes(Task.liftAsyncFunc2 f)
member this.AfterCreateAsyncRes(f: Func<'entity, Async<Result<'entity, Error list>>>) =
this.AfterCreateTaskRes(Task.liftAsyncFunc f)
member this.AfterCreateAsyncRes(f: Func<'entity, Async<Result<unit, Error list>>>) =
this.AfterCreateTaskRes(Task.liftAsyncFunc f)
member this.AfterCreateTask(f: Func<'ctx, 'entity, Task<'entity>>) =
this.AfterCreateTaskRes(fun ctx e -> f.Invoke(ctx, e) |> Task.map Ok)
member this.AfterCreateTask(f: Func<'ctx, 'entity, Task<unit>>) =
this.AfterCreateTaskRes(fun ctx e -> f.Invoke(ctx, e) |> Task.map Ok)
member this.AfterCreateTask(f: Func<'entity, Task<'entity>>) =
this.AfterCreateTaskRes(fun e -> f.Invoke e |> Task.map Ok)
member this.AfterCreateTask(f: Func<'entity, Task<unit>>) =
this.AfterCreateTaskRes(fun e -> f.Invoke e |> Task.map Ok)
member this.AfterCreateAsync(f: Func<'ctx, 'entity, Async<'entity>>) =
this.AfterCreateTask(Task.liftAsyncFunc2 f)
member this.AfterCreateAsync(f: Func<'ctx, 'entity, Async<unit>>) =
this.AfterCreateTask(Task.liftAsyncFunc2 f)
member this.AfterCreateAsync(f: Func<'entity, Async<'entity>>) =
this.AfterCreateTask(Task.liftAsyncFunc f)
member this.AfterCreateAsync(f: Func<'entity, Async<unit>>) =
this.AfterCreateTask(Task.liftAsyncFunc f)
member this.AfterCreateRes(f: Func<'ctx, 'entity, Result<'entity, Error list>>) =
this.AfterCreateTaskRes(Task.liftFunc2 f)
member this.AfterCreateRes(f: Func<'ctx, 'entity, Result<unit, Error list>>) =
this.AfterCreateTaskRes(Task.liftFunc2 f)
member this.AfterCreateRes(f: Func<'entity, Result<'entity, Error list>>) =
this.AfterCreateTaskRes(Task.liftFunc f)
member this.AfterCreateRes(f: Func<'entity, Result<unit, Error list>>) =
this.AfterCreateTaskRes(Task.liftFunc f)
member this.AfterCreate(f: Func<'ctx, 'entity, 'entity>) =
this.AfterCreateTaskRes(TaskResult.liftFunc2 f)
member this.AfterCreate(f: Func<'ctx, 'entity, unit>) =
this.AfterCreateTaskRes(TaskResult.liftFunc2 f)
member this.AfterCreate(f: Func<'entity, 'entity>) =
this.AfterCreateTaskRes(TaskResult.liftFunc f)
member this.AfterCreate(f: Func<'entity, unit>) =
this.AfterCreateTaskRes(TaskResult.liftFunc f)
member this.Return202Accepted() = { this with return202Accepted = true }
member this.ModifyResponse(getHandler: 'ctx -> 'entity -> HttpHandler) = {
this with
modifyResponse = getHandler
}
member this.ModifyResponse(f: 'ctx -> 'entity -> HttpContext -> unit) =
this.ModifyResponse(fun ctx e ->
(fun next httpCtx ->
f ctx e httpCtx
next httpCtx
)
)
member this.ModifyResponse(handler: HttpHandler) = this.ModifyResponse(fun _ _ -> handler)
/// Validate preconditions using the specified function to get the ETag value. May be
/// combined with PreconditionsLastModified.
member this.PreconditionsETag(getETag: Func<'ctx, EntityTagHeaderValue>) = {
this with
validatePreconditions = true
getETag = fun ctx -> getETag.Invoke(ctx) |> Some
}
/// Validate preconditions using the specified function to get the LastModified value.
/// May be combined with PreconditionsETag.
member this.PreconditionsLastModified(getLastModified: Func<'ctx, DateTimeOffset>) = {
this with
validatePreconditions = true
getLastModified = fun ctx -> getLastModified.Invoke(ctx) |> Some
}
/// Make optional any preconditions supplied using PreconditionsETag or
/// PreconditionsLastModified. By default, any supplied preconditions are required.
member this.PreconditionsOptional = {
this with
preconditionsOptional = true
}
type PostCustomHelper<'ctx, 'entity>
internal
(
httpCtx: HttpContext,
ctx: 'ctx,
req: Request,
collName: string,
rDef: ResourceDefinition<'ctx>,
patcher: BoxedPatcher<'ctx>,
builder: ResponseBuilder<'ctx>
) =
member val internal ConsumedFieldNames: Set<ConsumedFieldName> = Set.empty with get, set
member val internal ConsumedQueryParams: Set<ConsumedQueryParamName> = Set.empty with get, set
member this.ValidateRequestTask(?parser: RequestParser<'originalCtx, 'a>) =
task {
parser
|> Option.iter (fun p ->
this.ConsumedFieldNames <- Set.union this.ConsumedFieldNames (Set.ofSeq p.consumedFields)
this.ConsumedQueryParams <- Set.union this.ConsumedQueryParams (Set.ofSeq p.consumedParams)
)
let idParsed =
parser
|> Option.map (fun p -> Set.ofSeq p.consumedFields)
|> Option.defaultValue Set.empty
|> Set.contains "id"
match! req.Document.Value with
| Ok(Some { data = Some { id = Include _ } }) when not idParsed ->
return Error [ collPostClientIdNotAllowed collName rDef.TypeName ]
| _ -> return Ok()
}
member this.ValidateRequestAsync(?parser: RequestParser<'originalCtx, 'a>) =
this.ValidateRequestTask(?parser = parser) |> Async.AwaitTask
member this.RunSettersTask(entity: 'entity, ?parser: RequestParser<'originalCtx, 'a>) =
parser
|> Option.iter (fun p ->
this.ConsumedFieldNames <- Set.union this.ConsumedFieldNames (Set.ofSeq p.consumedFields)
this.ConsumedQueryParams <- Set.union this.ConsumedQueryParams (Set.ofSeq p.consumedParams)
)
patcher
ctx
req
(parser
|> Option.map (fun p -> Set.ofSeq p.consumedFields)
|> Option.defaultValue Set.empty)
(box entity)
|> Task.map (
Result.map (fun (e, setFields) ->
this.ConsumedFieldNames <- Set.union this.ConsumedFieldNames setFields
unbox<'entity> e
)
)
member this.RunSettersAsync(entity: 'entity, ?parser: RequestParser<'originalCtx, 'a>) =
this.RunSettersTask(entity, ?parser = parser) |> Task.toAsync
member this.Return202Accepted() : HttpHandler =
fun next httpCtx ->
task {
let! fieldTrackerHandler =
httpCtx.RequestServices
.GetRequiredService<FieldTracker<'ctx>>()
.TrackFields(
[],
ctx,
req,
consumedFieldNamesWithType = (rDef.TypeName, this.ConsumedFieldNames)
)
return! (setStatusCode 202 >=> fieldTrackerHandler) next httpCtx
}
member this.ReturnCreatedEntity(entity: 'entity) : HttpHandler =
fun next httpCtx ->
task {
let! doc, selfUrlOpt = builder.Write httpCtx ctx req (rDef, entity)
let setLocationHeader =
match selfUrlOpt with
| Some url -> setHttpHeader "Location" (url.ToString())
| _ -> fun next ctx -> next ctx
let! fieldTrackerHandler =
httpCtx.RequestServices
.GetRequiredService<FieldTracker<'ctx>>()
.TrackFields(
[ rDef.TypeName ],
ctx,
req,
consumedFieldNamesWithType = (rDef.TypeName, this.ConsumedFieldNames)
)
let handler =
setStatusCode 201
>=> setLocationHeader
>=> fieldTrackerHandler
>=> jsonApiWithETag<'ctx> doc
return! handler next httpCtx
}
/// Validate preconditions using the specified ETag value. The preconditions are
/// required unless passing `isOptional = true`.
member _.ValidatePreconditions(eTag: EntityTagHeaderValue, ?isOptional: bool) =
PreconditionHelpers.validate httpCtx ctx (fun _ -> Some eTag) (fun _ -> None) (defaultArg isOptional false)
/// Validate preconditions using the specified LastModified value. The preconditions are
/// required unless passing `isOptional = true`.
member _.ValidatePreconditions(lastModified: DateTimeOffset, ?isOptional: bool) =
PreconditionHelpers.validate
httpCtx
ctx
(fun _ -> None)
(fun _ -> Some lastModified)
(defaultArg isOptional false)
/// Validate preconditions using the specified ETag and LastModified values. The
/// preconditions are required unless passing `isOptional = true`.
member _.ValidatePreconditions(eTag: EntityTagHeaderValue, lastModified: DateTimeOffset, ?isOptional: bool) =
PreconditionHelpers.validate
httpCtx
ctx
(fun _ -> Some eTag)
(fun _ -> Some lastModified)
(defaultArg isOptional false)
member this.ValidateStrictModeQueryParameters() =
StrictModeHelpers.checkForUnknownQueryParameters<'ctx> httpCtx req this.ConsumedQueryParams
type CustomPostOperation<'originalCtx, 'ctx, 'entity> = internal {
mapCtx: 'originalCtx -> Task<Result<'ctx, Error list>>
operation:
'originalCtx
-> 'ctx
-> Request
-> PostCustomHelper<'originalCtx, 'entity>
-> Task<Result<HttpHandler, Error list>>
allowReadingBody: bool
validationConfig: RequestValidationConfig
} with
static member internal Create(mapCtx, operation) : CustomPostOperation<'originalCtx, 'ctx, 'createResult> = {
mapCtx = mapCtx
operation = operation
allowReadingBody = false
validationConfig = {
ValidateAccept = true
ValidateContentType = true
ValidateQueryParams = true
}
}
interface PostOperation<'originalCtx> with
member _.HasPersist = true
member this.AllowReadingBody = this.allowReadingBody
member this.Run validateRequest collName rDef ctx req patch resp =
validateRequest this.validationConfig
>=> fun next httpCtx ->
task {
match! this.mapCtx ctx with
| Error errors -> return! handleErrors errors next httpCtx
| Ok mappedCtx ->
let helper =
PostCustomHelper<'originalCtx, 'entity>(httpCtx, ctx, req, collName, rDef, patch, resp)
match! this.operation ctx mappedCtx req helper with
| Ok handler -> return! handler next httpCtx
| Error errors -> return! handleErrors errors next httpCtx
}
/// Enable reading the request body manually for this operation, preventing Felicity reading the request body. This
/// means that there must be no other POST collection operations for the same collection, since Felicity can't use
/// the resource 'type' in the request body to determine which POST collection operation to use.
member this.AllowReadingBody() = { this with allowReadingBody = true }
/// Skips the requirement and validation of the JSON:API media type in the Accept request header for this custom operation
/// (for all HTTP verbs if multiple are defined).
member this.SkipStandardAcceptValidation() = {
this with
validationConfig = {
this.validationConfig with
ValidateAccept = false
}
}
/// Skips the requirement and validation of the JSON:API media type in the Content-Type request header for this custom
/// operation (for all HTTP verbs if multiple are defined).
member this.SkipStandardContentTypeValidation() = {
this with
validationConfig = {
this.validationConfig with
ValidateContentType = false
}
}
/// Skips the validation of query parameter names that requires them to conform to the requirements in the JSON:API
/// specification.
///
/// This also skips the validation of any "skip links" query parameters set up using SkipStandardLinksQueryParamName
/// and SkipCustomLinksQueryParamName when configuring JSON:API.
member this.SkipStandardQueryParamNameValidation() = {
this with
validationConfig = {
this.validationConfig with
ValidateQueryParams = false
}
}
type internal PatchOperation<'ctx> =
abstract HasPersist: bool
abstract Run:
ResourceDefinition<'ctx> ->
'ctx ->
Request ->
Preconditions<'ctx> ->
BoxedEntity ->
BoxedPatcher<'ctx> ->
ResponseBuilder<'ctx> ->
HttpHandler
type PatchOperation<'originalCtx, 'ctx, 'entity> = internal {
mapCtx: 'originalCtx -> 'entity -> Task<Result<'ctx, Error list>>
beforeUpdate: 'ctx -> 'entity -> Task<Result<'entity, Error list>>
customSetter:
'originalCtx
-> 'ctx
-> Request
-> 'entity
-> Task<Result<Set<ConsumedFieldName> * Set<ConsumedQueryParamName> * 'entity, Error list>>
afterUpdate: ('ctx -> 'entity -> 'entity -> Task<Result<'entity, Error list>>) option
modifyResponse: 'ctx -> 'entity -> HttpHandler
return202Accepted: bool
} with
static member internal Create mapCtx : PatchOperation<'originalCtx, 'ctx, 'entity> = {
mapCtx = mapCtx
beforeUpdate = fun _ x -> Ok x |> Task.result
customSetter = fun _ _ _ e -> Ok(Set.empty, Set.empty, e) |> Task.result
afterUpdate = None