-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcontroller.go
2694 lines (2213 loc) · 70.3 KB
/
controller.go
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 fire
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"math"
"math/bits"
"net/http"
"reflect"
"sort"
"strings"
"time"
"github.com/256dpi/jsonapi/v2"
"github.com/256dpi/serve"
"github.com/256dpi/xo"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsontype"
"github.com/256dpi/fire/coal"
"github.com/256dpi/fire/stick"
)
const blankCursor = "*"
var cursorEncoding = base64.URLEncoding.WithPadding(base64.NoPadding)
// Stage defines a controller callback stage.
type Stage int
// The available controller callback stages.
const (
Authorizer Stage = 1 << iota
Verifier
Modifier
Validator
Decorator
Notifier
)
var allStages = []Stage{
Authorizer,
Verifier,
Modifier,
Validator,
Decorator,
Notifier,
}
// Split will split a compound stage into a list of separate stages.
func (s Stage) Split() []Stage {
// collect stages
list := make([]Stage, 0, bits.OnesCount8(uint8(s)))
for _, stage := range allStages {
if s&stage != 0 {
list = append(list, stage)
}
}
return list
}
// FilterHandler defines a function that turns filter values into a filter
// expression.
type FilterHandler func(ctx *Context, values []string) (bson.M, error)
// A Controller provides a JSON API based interface to a model.
//
// Database transactions are automatically used for list, find, create, update
// and delete operations. The created session can be accessed through the
// context to use it in callbacks.
//
// Note: A controller must not be modified after being added to a group.
type Controller struct {
// The model that this controller should provide (e.g. &Foo{}).
Model coal.Model
// The store that is used to retrieve and persist the model.
Store *coal.Store
// Supported may be set to limit the supported operations of a controller.
// By default, all operations are supported. If the operation is not
// supported the request will be aborted with an unsupported method error.
Supported Matcher
// Search will enable full text search.
//
// Note: The "search" query parameter is for searching.
Search bool
// Filters is a list of fields that are filterable. Only fields that are
// exposed and indexed should be made filterable.
//
// Note: The filter[field] query parameters are used for filtering.
Filters []string
// FilterHandlers is a map of custom filter handlers that convert filter
// values into a filter expression. Handlers thar return a nil or empty
// expression will delegate the handling to the default filter algorithm.
FilterHandlers map[string]FilterHandler
// Sorters is a list of fields that are sortable. Only fields that are
// exposed and indexed should be made sortable.
//
// Note: The "sort" query parameters is used for sorting.
Sorters []string
// Properties is a mapping of model properties to attribute keys. These
// properties are called and their result set as attributes before returning
// the response.
Properties map[string]string
// Authorizers authorize the requested operation on the requested resource
// and are run before any models are loaded from the store. Returned "safe"
// errors will cause the abortion of the request with an unauthorized status.
//
// The callbacks are expected to return an error if the requester should be
// informed about being unauthorized to access the resource, or add filters
// to the context to only return accessible resources. The latter improves
// privacy as a protected resource would appear as being not found.
//
// Operations: All
Authorizers []*Callback
// Verifiers verify the requested operation on the requested resource and
// are run after models are loaded from the store. Returned "safe" errors
// will cause the abortions of the request with an unauthorized status.
//
// The callbacks are expected to return an error if the requester should be
// informed about being unauthorized to access the resource.
//
// Operations: !CollectionAction
Verifiers []*Callback
// Modifiers are run to modify the model during Create, Update and Delete
// operations after the model is loaded and the changed attributes have been
// assigned during an Update but before the model is validated. Returned
// "safe" errors will cause the abortion of the request with a bad request
// status.
//
// The callbacks are expected to modify the model to ensure default values,
// aggregate fields or in general add data to the model.
//
// Operations: Create, Update, Delete
Modifiers []*Callback
// Validators are run to validate Create, Update and Delete operations
// after the model is loaded, got modified and passed basic validation.
// Returned "safe" errors will cause the abortion of the request with a bad
// request.
//
// The callbacks are expected to validate the model being created, updated
// or deleted and return errors if the presented attributes or relationships
// are invalid or do not comply with the stated requirements. Necessary
// authorization checks should be repeated and now also include the model's
// attributes and relationships. The model should not be further modified to
// ensure that the validators do not influence each other.
//
// Operations: Create, Update, Delete
Validators []*Callback
// Decorators are run after the models or model have been loaded from the
// database for List and Find operations or the model has been saved or
// updated for Create and Update operations.
//
// Operations: !Delete, !ResourceAction, !CollectionAction
Decorators []*Callback
// Notifiers are run before the final response is written to the client
// and provide a chance to modify the response and notify other systems
// about the applied changes.
//
// Operations: !ResourceAction, !CollectionAction
Notifiers []*Callback
// ListLimit can be set to a value higher than 1 to enforce paginated
// responses and restrain the page size to be within one and the limit.
//
// Note: The "page[number]" and "page[size]" query parameters are used for
// offset based pagination.
ListLimit int64
// CursorPagination can be set to require cursor based pagination. It can be
// enforced by also setting ListLimit. Cursor pagination will use the sort
// fields (including _id as the tiebreaker) to return a cursor that can be
// used to traverse large collections without incurring the performance
// costs of offset based pagination. This also implicitly adds the _id field
// as the last sorting field for all queries using pagination. For the
// pagination to be stable the filter and sorting fields must also remain
// stable between requests.
//
// Note: The "page[after]", "page[before]" and "page[size]" query parameters
// are used for cursor based pagination.
CursorPagination bool
// DocumentLimit defines the maximum allowed size of an incoming document.
// The serve.ByteSize helper can be used to set the value.
//
// Default: 8M.
DocumentLimit int64
// ReadTimeout and WriteTimeout specify the timeouts for read and write
// operations.
//
// Default: 30s.
ReadTimeout time.Duration
WriteTimeout time.Duration
// CollectionActions and ResourceActions are custom actions that are run
// on the collection (e.g. "posts/delete-cache") or resource (e.g.
// "users/1/recover-password"). The request context is forwarded to
// the specified callback after running the authorizers. No validators,
// modifiers, decorators and notifiers are run for these requests.
CollectionActions map[string]*Action
ResourceActions map[string]*Action
// TolerateViolations will prevent errors if the specified non-writable
// fields are changed during a Create or Update operation.
TolerateViolations []string
// IdempotentCreate can be set to true to enable the idempotent create
// mechanism. When creating resources, clients have to generate and submit a
// unique "create token". The controller will then first check if a document
// with the supplied token has already been created. The controller will
// determine the token field from the provided model using the
// "fire-idempotent-create" flag. It is recommended to add a unique index on
// the token field and also enable the soft delete mechanism to prevent
// duplicates if a short-lived document has already been deleted.
IdempotentCreate bool
// ConsistentUpdate can be set to true to enable the consistent update
// mechanism. When updating a resource, the client has to first load the
// most recent resource and retain the server generated "update token" and
// send it with the update in the defined update token field. The controller
// will then check if the stored document still has the same token. The
// controller will determine the token field from the provided model using
// the "fire-consistent-update" flag.
ConsistentUpdate bool
// SoftDelete can be set to true to enable the soft delete mechanism. If
// enabled, the controller will flag documents as deleted instead of
// immediately removing them. It will also exclude soft deleted documents
// from queries. The controller will determine the timestamp field from the
// provided model using the "fire-soft-delete" flag. It is advised to create
// a TTL index to delete the documents automatically after some timeout.
SoftDelete bool
parser jsonapi.Parser
meta *coal.Meta
properties map[string]func(coal.Model) (interface{}, error)
}
func (c *Controller) prepare() {
// ensure supported
if c.Supported == nil {
c.Supported = All()
}
// prepare parser
c.parser = jsonapi.Parser{
CollectionActions: make(map[string][]string),
ResourceActions: make(map[string][]string),
}
// cache meta
c.meta = coal.GetMeta(c.Model)
// add collection actions
for name, action := range c.CollectionActions {
// check collision
if name == "" || coal.IsHex(name) {
panic(fmt.Sprintf(`fire: invalid collection action "%s"`, name))
}
// set default body limit
if action.BodyLimit == 0 {
action.BodyLimit = serve.MustByteSize("8M")
}
// set default timeout
if action.Timeout == 0 {
action.Timeout = 30 * time.Second
}
// add to parser
c.parser.CollectionActions[name] = action.Methods
}
// add resource actions
for name, action := range c.ResourceActions {
// check collision
if name == "" || name == "relationships" || c.meta.Relationships[name] != nil {
panic(fmt.Sprintf(`fire: invalid resource action "%s"`, name))
}
// set default body limit
if action.BodyLimit == 0 {
action.BodyLimit = serve.MustByteSize("8M")
}
// set default timeout
if action.Timeout == 0 {
action.Timeout = 30 * time.Second
}
// add to parser
c.parser.ResourceActions[name] = action.Methods
}
// ensure document limit
if c.DocumentLimit == 0 {
c.DocumentLimit = serve.MustByteSize("8M")
}
// ensure timeouts
if c.ReadTimeout == 0 {
c.ReadTimeout = 30 * time.Second
}
if c.WriteTimeout == 0 {
c.WriteTimeout = 30 * time.Second
}
// check soft delete field
if c.SoftDelete {
fieldName := coal.L(c.Model, "fire-soft-delete", true)
if c.meta.Fields[fieldName].Type.String() != "*time.Time" {
panic(fmt.Sprintf(`fire: soft delete field "%s" for model "%s" is not of type "*time.Time"`, fieldName, c.meta.Name))
}
}
// check idempotent create field
if c.IdempotentCreate {
fieldName := coal.L(c.Model, "fire-idempotent-create", true)
if c.meta.Fields[fieldName].Type.String() != "string" {
panic(fmt.Sprintf(`fire: idempotent create field "%s" for model "%s" is not of type "string"`, fieldName, c.meta.Name))
}
}
// check consistent update field
if c.ConsistentUpdate {
fieldName := coal.L(c.Model, "fire-consistent-update", true)
if c.meta.Fields[fieldName].Type.String() != "string" {
panic(fmt.Sprintf(`fire: consistent update field "%s" for model "%s" is not of type "string"`, fieldName, c.meta.Name))
}
}
// check filter handlers
for name := range c.FilterHandlers {
if !stick.Contains(c.Filters, name) {
panic(fmt.Sprintf(`fire: filter handler for missing filter "%s"`, name))
}
}
// lookup properties
c.properties = map[string]func(coal.Model) (interface{}, error){}
for name := range c.Properties {
c.properties[name] = P(c.Model, name)
}
}
func (c *Controller) handle(prefix string, ctx *Context, selector bson.M, write bool) {
// trace
ctx.Tracer.Push("fire/Controller.handle")
defer ctx.Tracer.Pop()
// prepare parser
parser := c.parser
parser.Prefix = prefix
// parse incoming JSON-API request if not yet present
if ctx.JSONAPIRequest == nil {
req, err := parser.ParseRequest(ctx.HTTPRequest)
xo.AbortIf(err)
ctx.JSONAPIRequest = req
}
// parse document if not yet present and expected
if ctx.Request == nil && ctx.JSONAPIRequest.Intent.DocumentExpected() {
// limit request body size
serve.LimitBody(ctx.ResponseWriter, ctx.HTTPRequest, c.DocumentLimit)
// parse document and respect document limit
doc, err := jsonapi.ParseDocument(ctx.HTTPRequest.Body)
xo.AbortIf(err)
// set document
ctx.Request = doc
}
// validate ID if present
if ctx.JSONAPIRequest.ResourceID != "" && !coal.IsHex(ctx.JSONAPIRequest.ResourceID) {
xo.Abort(jsonapi.BadRequest("invalid resource ID"))
}
// set operation
switch ctx.JSONAPIRequest.Intent {
case jsonapi.ListResources:
ctx.Operation = List
case jsonapi.FindResource:
ctx.Operation = Find
case jsonapi.CreateResource:
ctx.Operation = Create
case jsonapi.UpdateResource:
ctx.Operation = Update
case jsonapi.DeleteResource:
ctx.Operation = Delete
case jsonapi.GetRelatedResources, jsonapi.GetRelationship:
ctx.Operation = Find
case jsonapi.SetRelationship, jsonapi.AppendToRelationship, jsonapi.RemoveFromRelationship:
ctx.Operation = Update
case jsonapi.CollectionAction:
ctx.Operation = CollectionAction
case jsonapi.ResourceAction:
ctx.Operation = ResourceAction
}
// check if supported
if !c.Supported(ctx) {
xo.Abort(jsonapi.ErrorFromStatus(
http.StatusMethodNotAllowed,
"unsupported operation",
))
}
// ensure selector
if selector == nil {
selector = bson.M{}
}
// prepare context
ctx.Store = c.Store
ctx.Selector = selector
ctx.Filters = []bson.M{}
ctx.ReadableFields = c.initialFields(false, ctx.JSONAPIRequest)
ctx.WritableFields = c.initialFields(true, nil)
ctx.ReadableProperties = c.initialProperties(ctx.JSONAPIRequest)
ctx.RelationshipFilters = map[string][]bson.M{}
// run operation with transaction if not an action
if !ctx.Operation.Action() {
xo.AbortIf(c.Store.T(ctx.Context, ctx.Operation.Read(), func(tc context.Context) error {
return ctx.With(tc, func() error {
c.runOperation(ctx)
return nil
})
}))
} else {
c.runOperation(ctx)
}
// write response if available
if write && ctx.Response != nil {
xo.AbortIf(jsonapi.WriteResponse(ctx.ResponseWriter, ctx.ResponseCode, ctx.Response))
}
}
func (c *Controller) runOperation(ctx *Context) {
// call specific handlers
switch ctx.JSONAPIRequest.Intent {
case jsonapi.ListResources:
c.listResources(ctx)
case jsonapi.FindResource:
c.findResource(ctx)
case jsonapi.CreateResource:
c.createResource(ctx)
case jsonapi.UpdateResource:
c.updateResource(ctx)
case jsonapi.DeleteResource:
c.deleteResource(ctx)
case jsonapi.GetRelatedResources:
c.getRelatedResources(ctx)
case jsonapi.GetRelationship:
c.getRelationship(ctx)
case jsonapi.SetRelationship:
c.setRelationship(ctx)
case jsonapi.AppendToRelationship:
c.appendToRelationship(ctx)
case jsonapi.RemoveFromRelationship:
c.removeFromRelationship(ctx)
case jsonapi.CollectionAction:
c.handleCollectionAction(ctx)
case jsonapi.ResourceAction:
c.handleResourceAction(ctx)
}
}
func (c *Controller) listResources(ctx *Context) {
// trace
ctx.Tracer.Push("fire/Controller.listResources")
defer ctx.Tracer.Pop()
// create context
ct, cancel := context.WithTimeout(ctx.Context, c.ReadTimeout)
defer cancel()
// replace context
ctx.Context = ct
// load models
c.loadModels(ctx)
// run decorators
c.runCallbacks(ctx, Decorator, c.Decorators, http.StatusInternalServerError)
// preload relationships
relationships := c.preloadRelationships(ctx, ctx.Models)
// compose response
ctx.Response = &jsonapi.Document{
Data: &jsonapi.HybridResource{
Many: c.resourcesForModels(ctx, ctx.Models, relationships),
},
Links: c.listLinks(ctx),
}
ctx.ResponseCode = http.StatusOK
// run notifiers
c.runCallbacks(ctx, Notifier, c.Notifiers, http.StatusInternalServerError)
}
func (c *Controller) findResource(ctx *Context) {
// trace
ctx.Tracer.Push("fire/Controller.findResource")
defer ctx.Tracer.Pop()
// create context
ct, cancel := context.WithTimeout(ctx.Context, c.ReadTimeout)
defer cancel()
// replace context
ctx.Context = ct
// load model
c.loadModel(ctx)
// run decorators
c.runCallbacks(ctx, Decorator, c.Decorators, http.StatusInternalServerError)
// preload relationships
relationships := c.preloadRelationships(ctx, []coal.Model{ctx.Model})
// compose response
ctx.Response = &jsonapi.Document{
Data: &jsonapi.HybridResource{
One: c.resourceForModel(ctx, ctx.Model, relationships),
},
Links: &jsonapi.DocumentLinks{
Self: jsonapi.Link(ctx.JSONAPIRequest.Self()),
},
}
ctx.ResponseCode = http.StatusOK
// run notifiers
c.runCallbacks(ctx, Notifier, c.Notifiers, http.StatusInternalServerError)
}
func (c *Controller) createResource(ctx *Context) {
// trace
ctx.Tracer.Push("fire/Controller.createResource")
defer ctx.Tracer.Pop()
// create context
ct, cancel := context.WithTimeout(ctx.Context, c.WriteTimeout)
defer cancel()
// replace context
ctx.Context = ct
// basic input data check
if ctx.Request.Data == nil || ctx.Request.Data.One == nil {
xo.Abort(jsonapi.BadRequest("missing document"))
}
// check resource type
if ctx.Request.Data.One.Type != ctx.JSONAPIRequest.ResourceType {
xo.Abort(jsonapi.BadRequest("resource type mismatch"))
}
// check ID
if ctx.Request.Data.One.ID != "" {
xo.Abort(jsonapi.BadRequest("unnecessary resource ID"))
}
// run authorizers
c.runCallbacks(ctx, Authorizer, c.Authorizers, http.StatusUnauthorized)
// create model with ID
ctx.Model = c.meta.Make()
ctx.Model.GetBase().DocID = coal.New()
// run verifiers
c.runCallbacks(ctx, Verifier, c.Verifiers, http.StatusUnauthorized)
// assign attributes
c.assignData(ctx, ctx.Request.Data.One)
// run modifiers
c.runCallbacks(ctx, Modifier, c.Modifiers, http.StatusBadRequest)
// validate model
err := ctx.Model.Validate()
if xo.IsSafe(err) {
xo.Abort(jsonapi.BadRequest(err.Error()))
} else if err != nil {
xo.Abort(err)
}
// run validators
c.runCallbacks(ctx, Validator, c.Validators, http.StatusBadRequest)
// set initial update token if consistent update is enabled
if c.ConsistentUpdate {
consistentUpdateField := coal.L(ctx.Model, "fire-consistent-update", true)
stick.MustSet(ctx.Model, consistentUpdateField, coal.New().Hex())
}
// check if idempotent create is enabled
if c.IdempotentCreate {
// get idempotent create field
idempotentCreateField := coal.L(ctx.Model, "fire-idempotent-create", true)
// get supplied idempotent create token
idempotentCreateToken := stick.MustGet(ctx.Model, idempotentCreateField).(string)
if idempotentCreateToken == "" {
xo.Abort(jsonapi.BadRequest("missing idempotent create token"))
}
// insert model
inserted, err := ctx.Store.M(c.Model).InsertIfMissing(ctx, bson.M{
idempotentCreateField: idempotentCreateToken,
}, ctx.Model, false)
if coal.IsDuplicate(err) {
xo.Abort(ErrDocumentNotUnique.Wrap())
}
xo.AbortIf(err)
// fail if not inserted
if !inserted {
xo.Abort(jsonapi.ErrorFromStatus(http.StatusConflict, "existing document with same idempotent create token"))
}
} else {
// insert model
err := ctx.Store.M(c.Model).Insert(ctx, ctx.Model)
if coal.IsDuplicate(err) {
xo.Abort(ErrDocumentNotUnique.Wrap())
}
xo.AbortIf(err)
}
// run decorators
c.runCallbacks(ctx, Decorator, c.Decorators, http.StatusInternalServerError)
// prepare link
selfLink := ctx.JSONAPIRequest.Merge(jsonapi.Request{
ResourceID: ctx.Model.ID().Hex(),
})
// compose response
ctx.Response = &jsonapi.Document{
Data: &jsonapi.HybridResource{
One: c.resourceForModel(ctx, ctx.Model, nil),
},
Links: &jsonapi.DocumentLinks{
Self: jsonapi.Link(selfLink.Self()),
},
}
ctx.ResponseCode = http.StatusCreated
// run notifiers
c.runCallbacks(ctx, Notifier, c.Notifiers, http.StatusInternalServerError)
}
func (c *Controller) updateResource(ctx *Context) {
// trace
ctx.Tracer.Push("fire/Controller.updateResource")
defer ctx.Tracer.Pop()
// create context
ct, cancel := context.WithTimeout(ctx.Context, c.WriteTimeout)
defer cancel()
// replace context
ctx.Context = ct
// basic input data check
if ctx.Request.Data == nil || ctx.Request.Data.One == nil {
xo.Abort(jsonapi.BadRequest("missing document"))
}
// check resource type
if ctx.Request.Data.One.Type != ctx.JSONAPIRequest.ResourceType {
xo.Abort(jsonapi.BadRequest("resource type mismatch"))
}
// check ID
if ctx.Request.Data.One.ID != ctx.JSONAPIRequest.ResourceID {
xo.Abort(jsonapi.BadRequest("resource ID mismatch"))
}
// load model
c.loadModel(ctx)
// get stored idempotent create token
var storedIdempotentCreateToken string
if c.IdempotentCreate {
idempotentCreateField := coal.L(ctx.Model, "fire-idempotent-create", true)
storedIdempotentCreateToken = stick.MustGet(ctx.Model, idempotentCreateField).(string)
}
// get and reset stored consistent update token
var storedConsistentUpdateToken string
if c.ConsistentUpdate {
consistentUpdateField := coal.L(ctx.Model, "fire-consistent-update", true)
storedConsistentUpdateToken = stick.MustGet(ctx.Model, consistentUpdateField).(string)
stick.MustSet(ctx.Model, consistentUpdateField, "")
}
// assign attributes
c.assignData(ctx, ctx.Request.Data.One)
// run modifiers
c.runCallbacks(ctx, Modifier, c.Modifiers, http.StatusBadRequest)
// validate model
err := ctx.Model.Validate()
if xo.IsSafe(err) {
xo.Abort(jsonapi.BadRequest(err.Error()))
} else if err != nil {
xo.Abort(err)
}
// run validators
c.runCallbacks(ctx, Validator, c.Validators, http.StatusBadRequest)
// check if idempotent create token has been changed
if c.IdempotentCreate {
idempotentCreateField := coal.L(ctx.Model, "fire-idempotent-create", true)
idempotentCreateToken := stick.MustGet(ctx.Model, idempotentCreateField).(string)
if storedIdempotentCreateToken != idempotentCreateToken {
xo.Abort(jsonapi.BadRequest("idempotent create token cannot be changed"))
}
}
// check if consistent update is enabled
if c.ConsistentUpdate {
// get consistency update field
consistentUpdateField := coal.L(ctx.Model, "fire-consistent-update", true)
// get consistent update token
consistentUpdateToken := stick.MustGet(ctx.Model, consistentUpdateField).(string)
if consistentUpdateToken != storedConsistentUpdateToken {
xo.Abort(jsonapi.BadRequest("invalid consistent update token"))
}
// generate new update token
stick.MustSet(ctx.Model, consistentUpdateField, coal.New().Hex())
// update model
found, err := ctx.Store.M(c.Model).ReplaceFirst(ctx, bson.M{
"_id": ctx.Model.ID(),
consistentUpdateField: consistentUpdateToken,
}, ctx.Model, false)
if coal.IsDuplicate(err) {
xo.Abort(ErrDocumentNotUnique.Wrap())
}
xo.AbortIf(err)
// fail if not found
if !found {
xo.Abort(jsonapi.ErrorFromStatus(http.StatusConflict, "existing document with different consistent update token"))
}
} else {
// replace model
found, err := ctx.Store.M(c.Model).Replace(ctx, ctx.Model, false)
if coal.IsDuplicate(err) {
xo.Abort(ErrDocumentNotUnique.Wrap())
}
xo.AbortIf(err)
// check if missing
if !found {
xo.Abort(ErrResourceNotFound.Wrap())
}
}
// run decorators
c.runCallbacks(ctx, Decorator, c.Decorators, http.StatusInternalServerError)
// preload relationships
relationships := c.preloadRelationships(ctx, []coal.Model{ctx.Model})
// compose response
ctx.Response = &jsonapi.Document{
Data: &jsonapi.HybridResource{
One: c.resourceForModel(ctx, ctx.Model, relationships),
},
Links: &jsonapi.DocumentLinks{
Self: jsonapi.Link(ctx.JSONAPIRequest.Self()),
},
}
ctx.ResponseCode = http.StatusOK
// run notifiers
c.runCallbacks(ctx, Notifier, c.Notifiers, http.StatusInternalServerError)
}
func (c *Controller) deleteResource(ctx *Context) {
// trace
ctx.Tracer.Push("fire/Controller.deleteResource")
defer ctx.Tracer.Pop()
// create context
ct, cancel := context.WithTimeout(ctx.Context, c.WriteTimeout)
defer cancel()
// replace context
ctx.Context = ct
// load model
c.loadModel(ctx)
// run modifiers
c.runCallbacks(ctx, Modifier, c.Modifiers, http.StatusBadRequest)
// validate model
err := ctx.Model.Validate()
if xo.IsSafe(err) {
xo.Abort(jsonapi.BadRequest(err.Error()))
} else if err != nil {
xo.Abort(err)
}
// run validators
c.runCallbacks(ctx, Validator, c.Validators, http.StatusBadRequest)
// check if soft delete has been enabled
if c.SoftDelete {
// get soft delete field
softDeleteField := coal.L(c.Model, "fire-soft-delete", true)
// soft delete model
found, err := ctx.Store.M(c.Model).Update(ctx, nil, ctx.Model.ID(), bson.M{
"$set": bson.M{
softDeleteField: time.Now(),
},
}, false)
xo.AbortIf(err)
// check if missing
if !found {
xo.Abort(ErrResourceNotFound.Wrap())
}
} else {
// delete model
found, err := ctx.Store.M(c.Model).Delete(ctx, nil, ctx.Model.ID())
xo.AbortIf(err)
// check if missing
if !found {
xo.Abort(ErrResourceNotFound.Wrap())
}
}
// run notifiers
c.runCallbacks(ctx, Notifier, c.Notifiers, http.StatusInternalServerError)
// set status
ctx.ResponseWriter.WriteHeader(http.StatusNoContent)
}
func (c *Controller) getRelatedResources(ctx *Context) {
// trace
ctx.Tracer.Push("fire/Controller.getRelatedResources")
defer ctx.Tracer.Pop()
// create context
ct, cancel := context.WithTimeout(ctx.Context, c.ReadTimeout)
defer cancel()
// replace context
ctx.Context = ct
// find relationship
rel := c.meta.Relationships[ctx.JSONAPIRequest.RelatedResource]
if rel == nil {
xo.Abort(jsonapi.BadRequest("invalid relationship"))
}
// load model
c.loadModel(ctx)
// check if relationship is readable
if !stick.Contains(c.readableFields(ctx, ctx.Model), rel.Name) {
xo.Abort(jsonapi.BadRequest("relationship is not readable"))
}
// get related controller
rc := ctx.Group.controllers[rel.RelType]
if rc == nil {
xo.Abort(xo.F("missing related controller for %s", rel.RelType))
}
// prepare sub context
subCtx := &Context{
Context: ctx,
Data: stick.Map{},
Parent: ctx.Model,
HTTPRequest: ctx.HTTPRequest,
ResponseWriter: nil,
Controller: rc,
Group: ctx.Group,
Tracer: ctx.Tracer,
}
// copy and prepare request
req := *ctx.JSONAPIRequest
req.Intent = jsonapi.ListResources
req.ResourceType = rel.RelType
req.ResourceID = ""
req.RelatedResource = ""
subCtx.JSONAPIRequest = &req
// finish to-one relationship
if rel.ToOne {
// lookup ID of related resource
id := coal.New()
if rel.Optional {
rid := stick.MustGet(ctx.Model, rel.Name).(*coal.ID)
if rid != nil {
id = *rid
}
} else {
id = stick.MustGet(ctx.Model, rel.Name).(coal.ID)
}
// prepare selector
selector := bson.M{
"_id": id,
}
// when run to request even if the relation is not present to capture
// a proper response with potential meta information
// handle virtual request
rc.handle("", subCtx, selector, false)
// check response
if len(subCtx.Response.Data.Many) > 1 {
xo.Abort(xo.F("to one relationship returned more than one result"))
}
// pull out resource
if len(subCtx.Response.Data.Many) == 1 {
subCtx.Response.Data.One = subCtx.Response.Data.Many[0]
}
// unset list
subCtx.Response.Data.Many = nil
}
// finish to-many relationship
if rel.ToMany {
// get IDs from loaded model
ids := stick.MustGet(ctx.Model, rel.Name).([]coal.ID)
// prepare selector
selector := bson.M{
"_id": bson.M{"$in": ids},
}
// handle virtual request
rc.handle("", subCtx, selector, false)
}
// finish has-one relationship
if rel.HasOne {
// find inverse relationship
inverse := rc.meta.Relationships[rel.RelInverse]
if inverse == nil {
xo.Abort(xo.F("no relationship matching the inverse name %s", inverse.RelInverse))
}
// prepare selector
selector := bson.M{
inverse.Name: ctx.Model.ID(),
}
// handle virtual request
rc.handle("", subCtx, selector, false)
// check response
if len(subCtx.Response.Data.Many) > 1 {
xo.Abort(xo.F("has one relationship returned more than one result"))
}
// pull out resource
if len(subCtx.Response.Data.Many) == 1 {
subCtx.Response.Data.One = subCtx.Response.Data.Many[0]