-
Notifications
You must be signed in to change notification settings - Fork 3
/
controller.go
2019 lines (1622 loc) · 53.5 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 (
"fmt"
"math"
"net/http"
"reflect"
"strings"
"time"
"github.com/256dpi/jsonapi"
"github.com/256dpi/stack"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/256dpi/fire/coal"
)
// L is a short-hand type to create a list of callbacks.
type L []*Callback
// M is a short-hand type to create a map of actions.
type M map[string]*Action
// An Action defines a collection or resource action.
type Action struct {
// The allowed methods for this action.
Methods []string
// The callback for this action.
Callback *Callback
// BodyLimit defines the maximum allowed size of the request body. It
// defaults to 8M if set to zero. The DataSize helper can be used to set
// the value.
BodyLimit uint64
}
// A Controller provides a JSON API based interface to a model.
//
// 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
// Filters is a list of fields that are filterable. Only fields that are
// exposed and indexed should be made filterable.
Filters []string
// Sorters is a list of fields that are sortable. Only fields that are
// exposed and indexed should be made sortable.
Sorters []string
// Authorizers authorize the requested operation on the requested resource
// and are run before any models are loaded from the store. Returned errors
// will cause the abortion of the request with an unauthorized status by
// default.
//
// 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 later improves
// privacy as a protected resource would appear as being not found.
Authorizers []*Callback
// Validators are run to validate Create, Update and Delete operations
// after the models are loaded and the changed attributes have been assigned
// during an Update. Returned errors will cause the abortion of the request
// with a bad request status by default.
//
// 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.
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. Returned errors will cause the
// abortion of the request with an InternalServerError status by default.
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. Returned errors will cause the abortion of the
// request with an InternalServerError status by default.
Notifiers []*Callback
// NoList can be set to true if the resource is only listed through
// relationships from other resources. This is useful for resources like
// comments that should never be listed alone.
NoList bool
// 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: Fire uses the "page[number]" and "page[size]" query parameters for
// pagination.
ListLimit uint64
// DocumentLimit defines the maximum allowed size of an incoming document.
// It defaults to 8M if set to zero. The DataSize helper can be used to
// set the value.
DocumentLimit uint64
// 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,
// notifiers and decorators are run for the request.
CollectionActions map[string]*Action
ResourceActions map[string]*Action
// UseTransactions can be set to true to enable transactions for create,
// update and delete operations. If enabled, a transaction will be created
// and used for all database requests. The created session can be accessed
// through the context to use it in callbacks.
UseTransactions bool
// TolerateViolations will not raise an error if a non-writable field is
// set during a Create or Update operation. Frameworks like Ember.js just
// serialize the complete state of a model and thus might send attributes
// and relationships that are not writable.
TolerateViolations bool
// 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 record
// 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 record 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 record 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
}
func (c *Controller) prepare() {
// initialize model
coal.Init(c.Model)
// prepare parser
c.parser = jsonapi.Parser{
CollectionActions: make(map[string][]string),
ResourceActions: make(map[string][]string),
}
// 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 = DataSize("8M")
}
// add action to parser
c.parser.CollectionActions[name] = action.Methods
}
// add resource actions
for name, action := range c.ResourceActions {
// check collision
if name == "" || name == "relationships" || c.Model.Meta().Relationships[name] != nil {
panic(fmt.Sprintf(`fire: invalid resource action "%s"`, name))
}
// set default body limit
if action.BodyLimit == 0 {
action.BodyLimit = DataSize("8M")
}
// add action to parser
c.parser.ResourceActions[name] = action.Methods
}
// set default document limit
if c.DocumentLimit == 0 {
c.DocumentLimit = DataSize("8M")
}
// check soft delete field
if c.SoftDelete {
fieldName := coal.L(c.Model, "fire-soft-delete", true)
if c.Model.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.Model.Meta().Name))
}
}
// check idempotent create field
if c.IdempotentCreate {
fieldName := coal.L(c.Model, "fire-idempotent-create", true)
if c.Model.Meta().Fields[fieldName].Type.String() != "string" {
panic(fmt.Sprintf(`fire: idempotent create field "%s" for model "%s" is not of type "string"`, fieldName, c.Model.Meta().Name))
}
}
// check consistent update field
if c.ConsistentUpdate {
fieldName := coal.L(c.Model, "fire-consistent-update", true)
if c.Model.Meta().Fields[fieldName].Type.String() != "string" {
panic(fmt.Sprintf(`fire: consistent update field "%s" for model "%s" is not of type "string"`, fieldName, c.Model.Meta().Name))
}
}
}
func (c *Controller) generalHandler(prefix string, ctx *Context) {
// begin trace
ctx.Tracer.Push("fire/Controller.generalHandler")
// parse incoming JSON-API request
c.parser.Prefix = prefix
req, err := c.parser.ParseRequest(ctx.HTTPRequest)
stack.AbortIf(err)
// set request
ctx.JSONAPIRequest = req
// handle no list setting
if req.Intent == jsonapi.ListResources && c.NoList {
stack.Abort(jsonapi.ErrorFromStatus(
http.StatusMethodNotAllowed,
"listing is disabled for this resource",
))
}
// parse document if expected
var doc *jsonapi.Document
if req.Intent.DocumentExpected() {
// limit request body size
LimitBody(ctx.ResponseWriter, ctx.HTTPRequest, int64(c.DocumentLimit))
// parse document and respect document limit
doc, err = jsonapi.ParseDocument(ctx.HTTPRequest.Body)
stack.AbortIf(err)
}
// validate id if present
if req.ResourceID != "" && !coal.IsHex(req.ResourceID) {
stack.Abort(jsonapi.BadRequest("invalid resource id"))
}
// prepare context
ctx.Selector = bson.M{}
ctx.Filters = []bson.M{}
ctx.ReadableFields = c.initialFields(c.Model, ctx.JSONAPIRequest)
ctx.WritableFields = c.initialFields(c.Model, nil)
// set store
ctx.Store = c.Store
// run operation without transaction if not configured
if !c.UseTransactions {
c.runOperation(ctx, doc)
ctx.Tracer.Pop()
return
}
// run operation with transaction if enabled
stack.AbortIf(c.Store.TX(ctx.HTTPRequest.Context(), func(sc mongo.SessionContext) error {
// assign session
ctx.Session = sc
// run operation
c.runOperation(ctx, doc)
return nil
}))
// finish trace
ctx.Tracer.Pop()
}
func (c *Controller) runOperation(ctx *Context, doc *jsonapi.Document) {
// 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, doc)
case jsonapi.UpdateResource:
c.updateResource(ctx, doc)
case jsonapi.DeleteResource:
c.deleteResource(ctx)
case jsonapi.GetRelatedResources:
c.getRelatedResources(ctx)
case jsonapi.GetRelationship:
c.getRelationship(ctx)
case jsonapi.SetRelationship:
c.setRelationship(ctx, doc)
case jsonapi.AppendToRelationship:
c.appendToRelationship(ctx, doc)
case jsonapi.RemoveFromRelationship:
c.removeFromRelationship(ctx, doc)
case jsonapi.CollectionAction:
c.handleCollectionAction(ctx)
case jsonapi.ResourceAction:
c.handleResourceAction(ctx)
}
}
func (c *Controller) listResources(ctx *Context) {
// begin trace
ctx.Tracer.Push("fire/Controller.listResources")
// set operation
ctx.Operation = List
// load models
c.loadModels(ctx)
// run decorators
c.runCallbacks(c.Decorators, ctx, 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.JSONAPIRequest.Self(), ctx),
}
// run notifiers
c.runCallbacks(c.Notifiers, ctx, http.StatusInternalServerError)
// write result
stack.AbortIf(jsonapi.WriteResponse(ctx.ResponseWriter, http.StatusOK, ctx.Response))
// finish trace
ctx.Tracer.Pop()
}
func (c *Controller) findResource(ctx *Context) {
// begin trace
ctx.Tracer.Push("fire/Controller.findResource")
// set operation
ctx.Operation = Find
// load model
c.loadModel(ctx)
// run decorators
c.runCallbacks(c.Decorators, ctx, 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: ctx.JSONAPIRequest.Self(),
},
}
// run notifiers
c.runCallbacks(c.Notifiers, ctx, http.StatusInternalServerError)
// write result
stack.AbortIf(jsonapi.WriteResponse(ctx.ResponseWriter, http.StatusOK, ctx.Response))
// finish trace
ctx.Tracer.Pop()
}
func (c *Controller) createResource(ctx *Context, doc *jsonapi.Document) {
// begin trace
ctx.Tracer.Push("fire/Controller.createResource")
// set operation
ctx.Operation = Create
// basic input data check
if doc.Data == nil || doc.Data.One == nil {
stack.Abort(jsonapi.BadRequest("missing document"))
}
// check resource type
if doc.Data.One.Type != ctx.JSONAPIRequest.ResourceType {
stack.Abort(jsonapi.BadRequest("resource type mismatch"))
}
// check id
if doc.Data.One.ID != "" {
stack.Abort(jsonapi.BadRequest("unnecessary resource id"))
}
// run authorizers
c.runCallbacks(c.Authorizers, ctx, http.StatusUnauthorized)
// create new model
ctx.Model = c.Model.Meta().Make()
// assign attributes
c.assignData(ctx, doc.Data.One)
// run validators
c.runCallbacks(c.Validators, ctx, http.StatusBadRequest)
// set initial update token if consistent update is enabled
if c.ConsistentUpdate {
consistentUpdateField := coal.L(ctx.Model, "fire-consistent-update", true)
ctx.Model.MustSet(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 := ctx.Model.MustGet(idempotentCreateField).(string)
if idempotentCreateToken == "" {
stack.Abort(jsonapi.BadRequest("missing idempotent create token"))
}
// insert model
res, err := ctx.TC(ctx.Model).UpdateOne(ctx.Session, bson.M{
coal.F(ctx.Model, idempotentCreateField): idempotentCreateToken,
}, bson.M{
"$setOnInsert": ctx.Model,
}, options.Update().SetUpsert(true))
stack.AbortIf(err)
// fail if already existing
if res.MatchedCount != 0 {
stack.Abort(jsonapi.ErrorFromStatus(http.StatusConflict, "existing document with same idempotent create token"))
}
} else {
// insert model
_, err := ctx.TC(ctx.Model).InsertOne(ctx.Session, ctx.Model)
stack.AbortIf(err)
}
// run decorators
c.runCallbacks(c.Decorators, ctx, http.StatusInternalServerError)
// compose response
ctx.Response = &jsonapi.Document{
Data: &jsonapi.HybridResource{
One: c.resourceForModel(ctx, ctx.Model, nil),
},
Links: &jsonapi.DocumentLinks{
Self: ctx.JSONAPIRequest.Self() + "/" + ctx.Model.ID().Hex(),
},
}
// run notifiers
c.runCallbacks(c.Notifiers, ctx, http.StatusInternalServerError)
// write result
stack.AbortIf(jsonapi.WriteResponse(ctx.ResponseWriter, http.StatusCreated, ctx.Response))
// finish trace
ctx.Tracer.Pop()
}
func (c *Controller) updateResource(ctx *Context, doc *jsonapi.Document) {
// begin trace
ctx.Tracer.Push("fire/Controller.updateResource")
// set operation
ctx.Operation = Update
// basic input data check
if doc.Data == nil || doc.Data.One == nil {
stack.Abort(jsonapi.BadRequest("missing document"))
}
// check resource type
if doc.Data.One.Type != ctx.JSONAPIRequest.ResourceType {
stack.Abort(jsonapi.BadRequest("resource type mismatch"))
}
// check id
if doc.Data.One.ID != ctx.JSONAPIRequest.ResourceID {
stack.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 = ctx.Model.MustGet(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 = ctx.Model.MustGet(consistentUpdateField).(string)
ctx.Model.MustSet(consistentUpdateField, "")
}
// assign attributes
c.assignData(ctx, doc.Data.One)
// check if idempotent create token has been changed
if c.IdempotentCreate {
idempotentCreateField := coal.L(ctx.Model, "fire-idempotent-create", true)
idempotentCreateToken := ctx.Model.MustGet(idempotentCreateField).(string)
if storedIdempotentCreateToken != idempotentCreateToken {
stack.Abort(jsonapi.BadRequest("idempotent create token cannot be changed"))
}
}
// run validators
c.runCallbacks(c.Validators, ctx, http.StatusBadRequest)
// 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 := ctx.Model.MustGet(consistentUpdateField).(string)
if consistentUpdateToken != storedConsistentUpdateToken {
stack.Abort(jsonapi.BadRequest("invalid consistent update token"))
}
// generate new update token
ctx.Model.MustSet(consistentUpdateField, coal.New().Hex())
// update model
res, err := ctx.TC(ctx.Model).UpdateOne(ctx.Session, bson.M{
"_id": ctx.Model.ID(),
coal.F(ctx.Model, consistentUpdateField): consistentUpdateToken,
}, bson.M{
"$set": ctx.Model,
})
stack.AbortIf(err)
// fail if not updated
if res.ModifiedCount != 1 {
stack.Abort(jsonapi.ErrorFromStatus(http.StatusConflict, "existing document with different consistent update token"))
}
} else {
// update model
_, err := ctx.TC(ctx.Model).ReplaceOne(ctx.Session, bson.M{
"_id": ctx.Model.ID(),
}, ctx.Model)
stack.AbortIf(err)
}
// run decorators
c.runCallbacks(c.Decorators, ctx, 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: ctx.JSONAPIRequest.Self(),
},
}
// run notifiers
c.runCallbacks(c.Notifiers, ctx, http.StatusInternalServerError)
// write result
stack.AbortIf(jsonapi.WriteResponse(ctx.ResponseWriter, http.StatusOK, ctx.Response))
// finish trace
ctx.Tracer.Pop()
}
func (c *Controller) deleteResource(ctx *Context) {
// begin trace
ctx.Tracer.Push("fire/Controller.deleteResource")
// set operation
ctx.Operation = Delete
// load model
c.loadModel(ctx)
// run validators
c.runCallbacks(c.Validators, ctx, 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
_, err := ctx.TC(c.Model).UpdateOne(ctx.Session, bson.M{
"_id": ctx.Model.ID(),
}, bson.M{
"$set": bson.M{
coal.F(c.Model, softDeleteField): time.Now(),
},
})
stack.AbortIf(err)
} else {
// remove model
_, err := ctx.TC(c.Model).DeleteOne(ctx.Session, bson.M{
"_id": ctx.Model.ID(),
})
stack.AbortIf(err)
}
// run notifiers
c.runCallbacks(c.Notifiers, ctx, http.StatusInternalServerError)
// set status
ctx.ResponseWriter.WriteHeader(http.StatusNoContent)
// finish trace
ctx.Tracer.Pop()
}
func (c *Controller) getRelatedResources(ctx *Context) {
// begin trace
ctx.Tracer.Push("fire/Controller.getRelatedResources")
// find relationship
rel := c.Model.Meta().Relationships[ctx.JSONAPIRequest.RelatedResource]
if rel == nil {
stack.Abort(jsonapi.BadRequest("invalid relationship"))
}
// set operation
ctx.Operation = Find
// load model
c.loadModel(ctx)
// check if relationship is readable
if !Contains(ctx.ReadableFields, rel.Name) {
stack.Abort(jsonapi.BadRequest("relationship is not readable"))
}
// get related controller
rc := ctx.Group.controllers[rel.RelType]
if rc == nil {
stack.Abort(fmt.Errorf("missing related controller for %s", rel.RelType))
}
// copy context and request
newCtx := &Context{
Data: Map{},
Selector: bson.M{},
Filters: []bson.M{},
ReadableFields: rc.initialFields(rc.Model, ctx.JSONAPIRequest),
WritableFields: rc.initialFields(rc.Model, nil),
Store: ctx.Store,
JSONAPIRequest: &jsonapi.Request{
Prefix: ctx.JSONAPIRequest.Prefix,
ResourceType: rel.RelType,
Include: ctx.JSONAPIRequest.Include,
PageNumber: ctx.JSONAPIRequest.PageNumber,
PageSize: ctx.JSONAPIRequest.PageSize,
PageOffset: ctx.JSONAPIRequest.PageOffset,
PageLimit: ctx.JSONAPIRequest.PageLimit,
Sorting: ctx.JSONAPIRequest.Sorting,
Fields: ctx.JSONAPIRequest.Fields,
Filters: ctx.JSONAPIRequest.Filters,
},
HTTPRequest: ctx.HTTPRequest,
ResponseWriter: ctx.ResponseWriter,
Controller: rc,
Group: ctx.Group,
Tracer: ctx.Tracer,
}
// finish to-one relationship
if rel.ToOne {
// prepare id
var id string
// lookup id of related resource
if rel.Optional {
oid := ctx.Model.MustGet(rel.Name).(*coal.ID)
if oid != nil {
id = oid.Hex()
}
} else {
id = ctx.Model.MustGet(rel.Name).(coal.ID).Hex()
}
// tweak context
newCtx.Operation = Find
newCtx.JSONAPIRequest.Intent = jsonapi.FindResource
newCtx.JSONAPIRequest.ResourceID = id
// prepare response
newCtx.Response = &jsonapi.Document{
Data: &jsonapi.HybridResource{
One: nil,
},
Links: &jsonapi.DocumentLinks{
Self: ctx.JSONAPIRequest.Self(),
},
}
// load model if id is present
if id != "" {
// load model
rc.loadModel(newCtx)
// run decorators
c.runCallbacks(c.Decorators, newCtx, http.StatusInternalServerError)
// preload relationships
relationships := c.preloadRelationships(newCtx, []coal.Model{newCtx.Model})
// set model
newCtx.Response.Data.One = rc.resourceForModel(newCtx, newCtx.Model, relationships)
}
// run notifiers
c.runCallbacks(c.Notifiers, newCtx, http.StatusInternalServerError)
// write result
stack.AbortIf(jsonapi.WriteResponse(ctx.ResponseWriter, http.StatusOK, newCtx.Response))
}
// finish to-many relationship
if rel.ToMany {
// get ids from loaded model
ids := ctx.Model.MustGet(rel.Name).([]coal.ID)
// tweak context
newCtx.Operation = List
newCtx.JSONAPIRequest.Intent = jsonapi.ListResources
// set selector query
newCtx.Selector["_id"] = bson.M{"$in": ids}
// load related models
rc.loadModels(newCtx)
// run decorators
c.runCallbacks(c.Decorators, newCtx, http.StatusInternalServerError)
// preload relationships
relationships := rc.preloadRelationships(newCtx, newCtx.Models)
// compose response
newCtx.Response = &jsonapi.Document{
Data: &jsonapi.HybridResource{
Many: rc.resourcesForModels(newCtx, newCtx.Models, relationships),
},
Links: rc.listLinks(ctx.JSONAPIRequest.Self(), newCtx),
}
// run notifiers
c.runCallbacks(c.Notifiers, newCtx, http.StatusInternalServerError)
// write result
stack.AbortIf(jsonapi.WriteResponse(ctx.ResponseWriter, http.StatusOK, newCtx.Response))
}
// finish has-one relationship
if rel.HasOne {
// find relationship
relRel := rc.Model.Meta().Relationships[rel.RelInverse]
if relRel == nil {
stack.Abort(fmt.Errorf("no relationship matching the inverse name %s", relRel.RelInverse))
}
// tweak context
newCtx.Operation = List
newCtx.JSONAPIRequest.Intent = jsonapi.ListResources
// set selector query
newCtx.Selector[relRel.BSONField] = ctx.Model.ID()
// load related models
rc.loadModels(newCtx)
// check models
if len(newCtx.Models) > 1 {
stack.Abort(fmt.Errorf("has one relationship returned more than one result"))
}
// run decorators if found
if len(newCtx.Models) == 1 {
c.runCallbacks(c.Decorators, newCtx, http.StatusInternalServerError)
}
// compose response
newCtx.Response = &jsonapi.Document{
Data: &jsonapi.HybridResource{},
Links: &jsonapi.DocumentLinks{
Self: ctx.JSONAPIRequest.Self(),
},
}
// add if model is found
if len(newCtx.Models) == 1 {
// preload relationships
relationships := c.preloadRelationships(newCtx, []coal.Model{newCtx.Models[0]})
// set model
newCtx.Response.Data.One = rc.resourceForModel(newCtx, newCtx.Models[0], relationships)
}
// run notifiers
c.runCallbacks(c.Notifiers, newCtx, http.StatusInternalServerError)
// write result
stack.AbortIf(jsonapi.WriteResponse(ctx.ResponseWriter, http.StatusOK, newCtx.Response))
}
// finish has-many relationship
if rel.HasMany {
// find relationship
relRel := rc.Model.Meta().Relationships[rel.RelInverse]
if relRel == nil {
stack.Abort(fmt.Errorf("no relationship matching the inverse name %s", relRel.RelInverse))
}
// tweak context
newCtx.Operation = List
newCtx.JSONAPIRequest.Intent = jsonapi.ListResources
// set selector query (supports to-one and to-many relationships)
newCtx.Selector[relRel.BSONField] = bson.M{
"$in": []coal.ID{ctx.Model.ID()},
}
// load related models
rc.loadModels(newCtx)
// run decorators
c.runCallbacks(c.Decorators, newCtx, http.StatusInternalServerError)
// preload relationships
relationships := rc.preloadRelationships(newCtx, newCtx.Models)
// compose response
newCtx.Response = &jsonapi.Document{
Data: &jsonapi.HybridResource{
Many: rc.resourcesForModels(newCtx, newCtx.Models, relationships),
},
Links: rc.listLinks(ctx.JSONAPIRequest.Self(), newCtx),
}
// run notifiers
c.runCallbacks(c.Notifiers, newCtx, http.StatusInternalServerError)
// write result
stack.AbortIf(jsonapi.WriteResponse(ctx.ResponseWriter, http.StatusOK, newCtx.Response))
}
// finish trace
ctx.Tracer.Pop()
}
func (c *Controller) getRelationship(ctx *Context) {
// begin trace
ctx.Tracer.Push("fire/Controller.getRelationship")
// get relationship
field := c.Model.Meta().Relationships[ctx.JSONAPIRequest.Relationship]
if field == nil {
stack.Abort(jsonapi.BadRequest("invalid relationship"))
}
// set operation
ctx.Operation = Find
// load model
c.loadModel(ctx)
// check if relationship is readable
if !Contains(ctx.ReadableFields, field.Name) {
stack.Abort(jsonapi.BadRequest("relationship is not readable"))
}
// run decorators
c.runCallbacks(c.Decorators, ctx, http.StatusInternalServerError)
// preload relationships
relationships := c.preloadRelationships(ctx, []coal.Model{ctx.Model})
// get resource
resource := c.resourceForModel(ctx, ctx.Model, relationships)
// get relationship
ctx.Response = resource.Relationships[ctx.JSONAPIRequest.Relationship]
// run notifiers
c.runCallbacks(c.Notifiers, ctx, http.StatusInternalServerError)
// write result
stack.AbortIf(jsonapi.WriteResponse(ctx.ResponseWriter, http.StatusOK, ctx.Response))
// finish trace
ctx.Tracer.Pop()
}
func (c *Controller) setRelationship(ctx *Context, doc *jsonapi.Document) {
// begin trace
ctx.Tracer.Push("fire/Controller.setRelationship")
// abort if consistent update is enabled
if c.ConsistentUpdate {
stack.Abort(jsonapi.ErrorFromStatus(http.StatusMethodNotAllowed, "partial updates not allowed with consistent updates"))
}
// get relationship
rel := c.Model.Meta().Relationships[ctx.JSONAPIRequest.Relationship]
if rel == nil || (!rel.ToOne && !rel.ToMany) {
stack.Abort(jsonapi.BadRequest("invalid relationship"))
}
// set operation
ctx.Operation = Update
// load model
c.loadModel(ctx)
// check if relationship is writable
if !Contains(ctx.WritableFields, rel.Name) {
stack.Abort(jsonapi.BadRequest("relationship is not writable"))
}
// assign relationship
c.assignRelationship(ctx, ctx.JSONAPIRequest.Relationship, doc, rel)
// run validators
c.runCallbacks(c.Validators, ctx, http.StatusBadRequest)
// update model
_, err := ctx.TC(ctx.Model).ReplaceOne(ctx.Session, bson.M{
"_id": ctx.Model.ID(),
}, ctx.Model)
stack.AbortIf(err)
// run decorators
c.runCallbacks(c.Decorators, ctx, http.StatusInternalServerError)
// preload relationships
relationships := c.preloadRelationships(ctx, []coal.Model{ctx.Model})
// get resource
resource := c.resourceForModel(ctx, ctx.Model, relationships)
// get relationship
ctx.Response = resource.Relationships[ctx.JSONAPIRequest.Relationship]
// run notifiers
c.runCallbacks(c.Notifiers, ctx, http.StatusInternalServerError)
// write result
stack.AbortIf(jsonapi.WriteResponse(ctx.ResponseWriter, http.StatusOK, ctx.Response))
// finish trace
ctx.Tracer.Pop()
}
func (c *Controller) appendToRelationship(ctx *Context, doc *jsonapi.Document) {
// begin trace
ctx.Tracer.Push("fire/Controller.appendToRelationship")
// abort if consistent update is enabled
if c.ConsistentUpdate {
stack.Abort(jsonapi.ErrorFromStatus(http.StatusMethodNotAllowed, "partial updates not allowed with consistent updates"))