forked from goadesign/goa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdefinitions.go
1808 lines (1665 loc) · 50.7 KB
/
definitions.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 design
import (
"fmt"
"net/http"
"path"
"sort"
"strings"
"github.com/dimfeld/httppath"
"github.com/goadesign/goa/dslengine"
)
type (
// APIDefinition defines the global properties of the API.
APIDefinition struct {
// Name of API
Name string
// Title of API
Title string
// Description of API
Description string
// Version is the version of the API described by this design.
Version string
// Host is the default API hostname
Host string
// Schemes is the supported API URL schemes
Schemes []string
// BasePath is the common base path to all API endpoints
BasePath string
// Params define the common path parameters to all API endpoints
Params *AttributeDefinition
// Consumes lists the mime types supported by the API controllers
Consumes []*EncodingDefinition
// Produces lists the mime types generated by the API controllers
Produces []*EncodingDefinition
// Origins defines the CORS policies that apply to this API.
Origins map[string]*CORSDefinition
// TermsOfService describes or links to the API terms of service
TermsOfService string
// Contact provides the API users with contact information
Contact *ContactDefinition
// License describes the API license
License *LicenseDefinition
// Docs points to the API external documentation
Docs *DocsDefinition
// Resources is the set of exposed resources indexed by name
Resources map[string]*ResourceDefinition
// Types indexes the user defined types by name
Types map[string]*UserTypeDefinition
// MediaTypes indexes the API media types by canonical identifier
MediaTypes map[string]*MediaTypeDefinition
// Traits available to all API resources and actions indexed by name
Traits map[string]*dslengine.TraitDefinition
// Responses available to all API actions indexed by name
Responses map[string]*ResponseDefinition
// Response template factories available to all API actions indexed by name
ResponseTemplates map[string]*ResponseTemplateDefinition
// Built-in responses
DefaultResponses map[string]*ResponseDefinition
// Built-in response templates
DefaultResponseTemplates map[string]*ResponseTemplateDefinition
// DSLFunc contains the DSL used to create this definition if any
DSLFunc func()
// Metadata is a list of key/value pairs
Metadata dslengine.MetadataDefinition
// SecuritySchemes lists the available security schemes available
// to the API.
SecuritySchemes []*SecuritySchemeDefinition
// Security defines security requirements for all the
// resources and actions, unless overridden by Resource or
// Action-level Security() calls.
Security *SecurityDefinition
// NoExamples indicates whether to bypass automatic example generation.
NoExamples bool
// rand is the random generator used to generate examples.
rand *RandomGenerator
}
// ContactDefinition contains the API contact information.
ContactDefinition struct {
// Name of the contact person/organization
Name string `json:"name,omitempty"`
// Email address of the contact person/organization
Email string `json:"email,omitempty"`
// URL pointing to the contact information
URL string `json:"url,omitempty"`
}
// LicenseDefinition contains the license information for the API.
LicenseDefinition struct {
// Name of license used for the API
Name string `json:"name,omitempty"`
// URL to the license used for the API
URL string `json:"url,omitempty"`
}
// DocsDefinition points to external documentation.
DocsDefinition struct {
// Description of documentation.
Description string `json:"description,omitempty"`
// URL to documentation.
URL string `json:"url,omitempty"`
}
// ResourceDefinition describes a REST resource.
// It defines both a media type and a set of actions that can be executed through HTTP
// requests.
ResourceDefinition struct {
// Resource name
Name string
// Schemes is the supported API URL schemes
Schemes []string
// Common URL prefix to all resource action HTTP requests
BasePath string
// Path and query string parameters that apply to all actions.
Params *AttributeDefinition
// Name of parent resource if any
ParentName string
// Optional description
Description string
// Default media type, describes the resource attributes
MediaType string
// Default view name if default media type is MediaTypeDefinition
DefaultViewName string
// Exposed resource actions indexed by name
Actions map[string]*ActionDefinition
// FileServers is the list of static asset serving endpoints
FileServers []*FileServerDefinition
// Action with canonical resource path
CanonicalActionName string
// Map of response definitions that apply to all actions indexed by name.
Responses map[string]*ResponseDefinition
// Request headers that apply to all actions.
Headers *AttributeDefinition
// Origins defines the CORS policies that apply to this resource.
Origins map[string]*CORSDefinition
// DSLFunc contains the DSL used to create this definition if any.
DSLFunc func()
// metadata is a list of key/value pairs
Metadata dslengine.MetadataDefinition
// Security defines security requirements for the Resource,
// for actions that don't define one themselves.
Security *SecurityDefinition
}
// CORSDefinition contains the definition for a specific origin CORS policy.
CORSDefinition struct {
// Parent API or resource
Parent dslengine.Definition
// Origin
Origin string
// List of authorized headers, "*" authorizes all
Headers []string
// List of authorized HTTP methods
Methods []string
// List of headers exposed to clients
Exposed []string
// How long to cache a preflight request response
MaxAge uint
// Sets Access-Control-Allow-Credentials header
Credentials bool
// Sets Whether the Origin string is a regular expression
Regexp bool
}
// EncodingDefinition defines an encoder supported by the API.
EncodingDefinition struct {
// MIMETypes is the set of possible MIME types for the content being encoded or decoded.
MIMETypes []string
// PackagePath is the path to the Go package that implements the encoder/decoder.
// The package must expose a `EncoderFactory` or `DecoderFactory` function
// that the generated code calls. The methods must return objects that implement
// the goa.EncoderFactory or goa.DecoderFactory interface respectively.
PackagePath string
// Function is the name of the Go function used to instantiate the encoder/decoder.
// Defaults to NewEncoder and NewDecoder respecitively.
Function string
// Encoder is true if the definition is for a encoder, false if it's for a decoder.
Encoder bool
}
// ResponseDefinition defines a HTTP response status and optional validation rules.
ResponseDefinition struct {
// Response name
Name string
// HTTP status
Status int
// Response description
Description string
// Response body type if any
Type DataType
// Response body media type if any
MediaType string
// Response view name if MediaType is MediaTypeDefinition
ViewName string
// Response header definitions
Headers *AttributeDefinition
// Parent action or resource
Parent dslengine.Definition
// Metadata is a list of key/value pairs
Metadata dslengine.MetadataDefinition
// Standard is true if the response definition comes from the goa default responses
Standard bool
}
// ResponseTemplateDefinition defines a response template.
// A response template is a function that takes an arbitrary number
// of strings and returns a response definition.
ResponseTemplateDefinition struct {
// Response template name
Name string
// Response template function
Template func(params ...string) *ResponseDefinition
}
// ActionDefinition defines a resource action.
// It defines both an HTTP endpoint and the shape of HTTP requests and responses made to
// that endpoint.
// The shape of requests is defined via "parameters", there are path parameters
// parameters and a payload parameter (request body).
// (i.e. portions of the URL that define parameter values), query string
ActionDefinition struct {
// Action name, e.g. "create"
Name string
// Action description, e.g. "Creates a task"
Description string
// Docs points to the API external documentation
Docs *DocsDefinition
// Parent resource
Parent *ResourceDefinition
// Specific action URL schemes
Schemes []string
// Action routes
Routes []*RouteDefinition
// Map of possible response definitions indexed by name
Responses map[string]*ResponseDefinition
// Path and query string parameters
Params *AttributeDefinition
// Query string parameters only
QueryParams *AttributeDefinition
// Payload blueprint (request body) if any
Payload *UserTypeDefinition
// PayloadOptional is true if the request payload is optional, false otherwise.
PayloadOptional bool
// Request headers that need to be made available to action
Headers *AttributeDefinition
// Metadata is a list of key/value pairs
Metadata dslengine.MetadataDefinition
// Security defines security requirements for the action
Security *SecurityDefinition
}
// FileServerDefinition defines an endpoint that servers static assets.
FileServerDefinition struct {
// Parent resource
Parent *ResourceDefinition
// Description for docs
Description string
// Docs points to the API external documentation
Docs *DocsDefinition
// FilePath is the file path to the static asset(s)
FilePath string
// RequestPath is the HTTP path that servers the assets.
RequestPath string
// Metadata is a list of key/value pairs
Metadata dslengine.MetadataDefinition
// Security defines security requirements for the file server.
Security *SecurityDefinition
}
// LinkDefinition defines a media type link, it specifies a URL to a related resource.
LinkDefinition struct {
// Link name
Name string
// View used to render link if not "link"
View string
// URITemplate is the RFC6570 URI template of the link Href.
URITemplate string
// Parent media Type
Parent *MediaTypeDefinition
}
// ViewDefinition defines which members and links to render when building a response.
// The view is a JSON object whose property names must match the names of the parent media
// type members.
// The members fields are inherited from the parent media type but may be overridden.
ViewDefinition struct {
// Set of properties included in view
*AttributeDefinition
// Name of view
Name string
// Parent media Type
Parent *MediaTypeDefinition
}
// RouteDefinition represents an action route.
RouteDefinition struct {
// Verb is the HTTP method, e.g. "GET", "POST", etc.
Verb string
// Path is the URL path e.g. "/tasks/:id"
Path string
// Parent is the action this route applies to.
Parent *ActionDefinition
// Metadata is a list of key/value pairs
Metadata dslengine.MetadataDefinition
}
// AttributeDefinition defines a JSON object member with optional description, default
// value and validations.
AttributeDefinition struct {
// Attribute type
Type DataType
// Attribute reference type if any
Reference DataType
// Optional description
Description string
// Optional validations
Validation *dslengine.ValidationDefinition
// Metadata is a list of key/value pairs
Metadata dslengine.MetadataDefinition
// Optional member default value
DefaultValue interface{}
// Optional member example value
Example interface{}
// Optional view used to render Attribute (only applies to media type attributes).
View string
// NonZeroAttributes lists the names of the child attributes that cannot have a
// zero value (and thus whose presence does not need to be validated).
NonZeroAttributes map[string]bool
// DSLFunc contains the initialization DSL. This is used for user types.
DSLFunc func()
}
// ContainerDefinition defines a generic container definition that contains attributes.
// This makes it possible for plugins to use attributes in their own data structures.
ContainerDefinition interface {
// Attribute returns the container definition embedded attribute.
Attribute() *AttributeDefinition
}
// ResourceIterator is the type of functions given to IterateResources.
ResourceIterator func(r *ResourceDefinition) error
// MediaTypeIterator is the type of functions given to IterateMediaTypes.
MediaTypeIterator func(m *MediaTypeDefinition) error
// UserTypeIterator is the type of functions given to IterateUserTypes.
UserTypeIterator func(m *UserTypeDefinition) error
// ActionIterator is the type of functions given to IterateActions.
ActionIterator func(a *ActionDefinition) error
// FileServerIterator is the type of functions given to IterateFileServers.
FileServerIterator func(f *FileServerDefinition) error
// HeaderIterator is the type of functions given to IterateHeaders.
HeaderIterator func(name string, isRequired bool, h *AttributeDefinition) error
// ResponseIterator is the type of functions given to IterateResponses.
ResponseIterator func(r *ResponseDefinition) error
)
// NewAPIDefinition returns a new design with built-in response templates.
func NewAPIDefinition() *APIDefinition {
api := &APIDefinition{
DefaultResponseTemplates: make(map[string]*ResponseTemplateDefinition),
DefaultResponses: make(map[string]*ResponseDefinition),
}
t := func(params ...string) *ResponseDefinition {
if len(params) < 1 {
dslengine.ReportError("expected media type as argument when invoking response template OK")
return nil
}
return &ResponseDefinition{
Name: OK,
Status: 200,
MediaType: params[0],
}
}
api.DefaultResponseTemplates[OK] = &ResponseTemplateDefinition{
Name: OK,
Template: t,
}
for _, p := range []struct {
status int
name string
}{
{100, Continue},
{101, SwitchingProtocols},
{200, OK},
{201, Created},
{202, Accepted},
{203, NonAuthoritativeInfo},
{204, NoContent},
{205, ResetContent},
{206, PartialContent},
{300, MultipleChoices},
{301, MovedPermanently},
{302, Found},
{303, SeeOther},
{304, NotModified},
{305, UseProxy},
{307, TemporaryRedirect},
{400, BadRequest},
{401, Unauthorized},
{402, PaymentRequired},
{403, Forbidden},
{404, NotFound},
{405, MethodNotAllowed},
{406, NotAcceptable},
{407, ProxyAuthRequired},
{408, RequestTimeout},
{409, Conflict},
{410, Gone},
{411, LengthRequired},
{412, PreconditionFailed},
{413, RequestEntityTooLarge},
{414, RequestURITooLong},
{415, UnsupportedMediaType},
{416, RequestedRangeNotSatisfiable},
{417, ExpectationFailed},
{418, Teapot},
{422, UnprocessableEntity},
{500, InternalServerError},
{501, NotImplemented},
{502, BadGateway},
{503, ServiceUnavailable},
{504, GatewayTimeout},
{505, HTTPVersionNotSupported},
} {
api.DefaultResponses[p.name] = &ResponseDefinition{
Name: p.name,
Description: http.StatusText(p.status),
Status: p.status,
}
}
return api
}
// DSLName is the name of the DSL as displayed to the user during execution.
func (a *APIDefinition) DSLName() string {
return "goa API"
}
// DependsOn returns the other roots this root depends on, nothing for APIDefinition.
func (a *APIDefinition) DependsOn() []dslengine.Root {
return nil
}
// IterateSets calls the given iterator possing in the API definition, user types, media types and
// finally resources.
func (a *APIDefinition) IterateSets(iterator dslengine.SetIterator) {
// First run the top level API DSL to initialize responses and
// response templates needed by resources.
iterator([]dslengine.Definition{a})
// Then run the user type DSLs
typeAttributes := make([]dslengine.Definition, len(a.Types))
i := 0
a.IterateUserTypes(func(u *UserTypeDefinition) error {
u.AttributeDefinition.DSLFunc = u.DSLFunc
typeAttributes[i] = u.AttributeDefinition
i++
return nil
})
iterator(typeAttributes)
// Then the media type DSLs
mediaTypes := make([]dslengine.Definition, len(a.MediaTypes))
i = 0
a.IterateMediaTypes(func(mt *MediaTypeDefinition) error {
mediaTypes[i] = mt
i++
return nil
})
iterator(mediaTypes)
// Then, the Security schemes definitions
var securitySchemes []dslengine.Definition
for _, scheme := range a.SecuritySchemes {
securitySchemes = append(securitySchemes, dslengine.Definition(scheme))
}
iterator(securitySchemes)
// And now that we have everything - the resources. The resource
// lifecycle handlers dispatch to their children elements, like Actions,
// etc.. We must process parent resources first to ensure that query
// string and path parameters are initialized by the time a child
// resource action parameters are categorized.
resources := make([]*ResourceDefinition, len(a.Resources))
i = 0
a.IterateResources(func(res *ResourceDefinition) error {
resources[i] = res
i++
return nil
})
sort.Sort(byParent(resources))
defs := make([]dslengine.Definition, len(resources))
for i, r := range resources {
defs[i] = r
}
iterator(defs)
}
// Reset sets all the API definition fields to their zero value except the default responses and
// default response templates.
func (a *APIDefinition) Reset() {
n := NewAPIDefinition()
*a = *n
}
// Context returns the generic definition name used in error messages.
func (a *APIDefinition) Context() string {
if a.Name != "" {
return fmt.Sprintf("API %#v", a.Name)
}
return "unnamed API"
}
// PathParams returns the base path parameters of a.
func (a *APIDefinition) PathParams() *AttributeDefinition {
names := ExtractWildcards(a.BasePath)
obj := make(Object)
for _, n := range names {
obj[n] = a.Params.Type.ToObject()[n]
}
return &AttributeDefinition{Type: obj}
}
// IterateMediaTypes calls the given iterator passing in each media type sorted in alphabetical order.
// Iteration stops if an iterator returns an error and in this case IterateMediaTypes returns that
// error.
func (a *APIDefinition) IterateMediaTypes(it MediaTypeIterator) error {
names := make([]string, len(a.MediaTypes))
i := 0
for n := range a.MediaTypes {
names[i] = n
i++
}
sort.Strings(names)
for _, n := range names {
if err := it(a.MediaTypes[n]); err != nil {
return err
}
}
return nil
}
// IterateUserTypes calls the given iterator passing in each user type sorted in alphabetical order.
// Iteration stops if an iterator returns an error and in this case IterateUserTypes returns that
// error.
func (a *APIDefinition) IterateUserTypes(it UserTypeIterator) error {
names := make([]string, len(a.Types))
i := 0
for n := range a.Types {
names[i] = n
i++
}
sort.Strings(names)
for _, n := range names {
if err := it(a.Types[n]); err != nil {
return err
}
}
return nil
}
// IterateResponses calls the given iterator passing in each response sorted in alphabetical order.
// Iteration stops if an iterator returns an error and in this case IterateResponses returns that
// error.
func (a *APIDefinition) IterateResponses(it ResponseIterator) error {
names := make([]string, len(a.Responses))
i := 0
for n := range a.Responses {
names[i] = n
i++
}
sort.Strings(names)
for _, n := range names {
if err := it(a.Responses[n]); err != nil {
return err
}
}
return nil
}
// RandomGenerator is seeded after the API name. It's used to generate examples.
func (a *APIDefinition) RandomGenerator() *RandomGenerator {
if a.rand == nil {
a.rand = NewRandomGenerator(a.Name)
}
return a.rand
}
// MediaTypeWithIdentifier returns the media type with a matching
// media type identifier. Two media type identifiers match if their
// values sans suffix match. So for example "application/vnd.foo+xml",
// "application/vnd.foo+json" and "application/vnd.foo" all match.
func (a *APIDefinition) MediaTypeWithIdentifier(id string) *MediaTypeDefinition {
canonicalID := CanonicalIdentifier(id)
for _, mt := range a.MediaTypes {
if canonicalID == CanonicalIdentifier(mt.Identifier) {
return mt
}
}
return nil
}
// IterateResources calls the given iterator passing in each resource sorted in alphabetical order.
// Iteration stops if an iterator returns an error and in this case IterateResources returns that
// error.
func (a *APIDefinition) IterateResources(it ResourceIterator) error {
names := make([]string, len(a.Resources))
i := 0
for n := range a.Resources {
names[i] = n
i++
}
sort.Strings(names)
for _, n := range names {
if err := it(a.Resources[n]); err != nil {
return err
}
}
return nil
}
// DSL returns the initialization DSL.
func (a *APIDefinition) DSL() func() {
return a.DSLFunc
}
// Finalize sets the Consumes and Produces fields to the defaults if empty.
// Also it records built-in media types that are used by the user design.
func (a *APIDefinition) Finalize() {
if len(a.Consumes) == 0 {
a.Consumes = DefaultDecoders
}
if len(a.Produces) == 0 {
a.Produces = DefaultEncoders
}
found := false
a.IterateResources(func(r *ResourceDefinition) error {
if found {
return nil
}
return r.IterateActions(func(action *ActionDefinition) error {
if found {
return nil
}
for _, resp := range action.Responses {
if resp.MediaType == ErrorMediaIdentifier {
if a.MediaTypes == nil {
a.MediaTypes = make(map[string]*MediaTypeDefinition)
}
a.MediaTypes[CanonicalIdentifier(ErrorMediaIdentifier)] = ErrorMedia
found = true
break
}
}
return nil
})
})
}
// NewResourceDefinition creates a resource definition but does not
// execute the DSL.
func NewResourceDefinition(name string, dsl func()) *ResourceDefinition {
return &ResourceDefinition{
Name: name,
MediaType: "text/plain",
DSLFunc: dsl,
}
}
// Context returns the generic definition name used in error messages.
func (r *ResourceDefinition) Context() string {
if r.Name != "" {
return fmt.Sprintf("resource %#v", r.Name)
}
return "unnamed resource"
}
// PathParams returns the base path parameters of r.
func (r *ResourceDefinition) PathParams() *AttributeDefinition {
names := ExtractWildcards(r.BasePath)
obj := make(Object)
if r.Params != nil {
for _, n := range names {
if p, ok := r.Params.Type.ToObject()[n]; ok {
obj[n] = p
}
}
}
return &AttributeDefinition{Type: obj}
}
// IterateActions calls the given iterator passing in each resource action sorted in alphabetical order.
// Iteration stops if an iterator returns an error and in this case IterateActions returns that
// error.
func (r *ResourceDefinition) IterateActions(it ActionIterator) error {
names := make([]string, len(r.Actions))
i := 0
for n := range r.Actions {
names[i] = n
i++
}
sort.Strings(names)
for _, n := range names {
if err := it(r.Actions[n]); err != nil {
return err
}
}
return nil
}
// IterateFileServers calls the given iterator passing each resource file server sorted by file
// path. Iteration stops if an iterator returns an error and in this case IterateFileServers returns
// that error.
func (r *ResourceDefinition) IterateFileServers(it FileServerIterator) error {
sort.Sort(ByFilePath(r.FileServers))
for _, f := range r.FileServers {
if err := it(f); err != nil {
return err
}
}
return nil
}
// IterateHeaders calls the given iterator passing in each response sorted in alphabetical order.
// Iteration stops if an iterator returns an error and in this case IterateHeaders returns that
// error.
func (r *ResourceDefinition) IterateHeaders(it HeaderIterator) error {
return iterateHeaders(r.Headers, r.Headers.IsRequired, it)
}
// CanonicalAction returns the canonical action of the resource if any.
// The canonical action is used to compute hrefs to resources.
func (r *ResourceDefinition) CanonicalAction() *ActionDefinition {
name := r.CanonicalActionName
if name == "" {
name = "show"
}
ca, _ := r.Actions[name]
return ca
}
// URITemplate returns a URI template to this resource.
// The result is the empty string if the resource does not have a "show" action
// and does not define a different canonical action.
func (r *ResourceDefinition) URITemplate() string {
ca := r.CanonicalAction()
if ca == nil || len(ca.Routes) == 0 {
return ""
}
return ca.Routes[0].FullPath()
}
// FullPath computes the base path to the resource actions concatenating the API and parent resource
// base paths as needed.
func (r *ResourceDefinition) FullPath() string {
if strings.HasPrefix(r.BasePath, "//") {
return httppath.Clean(r.BasePath)
}
var basePath string
if p := r.Parent(); p != nil {
if ca := p.CanonicalAction(); ca != nil {
if routes := ca.Routes; len(routes) > 0 {
// Note: all these tests should be true at code generation time
// as DSL validation makes sure that parent resources have a
// canonical path.
basePath = path.Join(routes[0].FullPath())
}
}
} else {
basePath = Design.BasePath
}
return httppath.Clean(path.Join(basePath, r.BasePath))
}
// Parent returns the parent resource if any, nil otherwise.
func (r *ResourceDefinition) Parent() *ResourceDefinition {
if r.ParentName != "" {
if parent, ok := Design.Resources[r.ParentName]; ok {
return parent
}
}
return nil
}
// AllOrigins compute all CORS policies for the resource taking into account any API policy.
// The result is sorted alphabetically by policy origin.
func (r *ResourceDefinition) AllOrigins() []*CORSDefinition {
all := make(map[string]*CORSDefinition)
for n, o := range Design.Origins {
all[n] = o
}
for n, o := range r.Origins {
all[n] = o
}
names := make([]string, len(all))
i := 0
for n := range all {
names[i] = n
i++
}
sort.Strings(names)
cors := make([]*CORSDefinition, len(names))
for i, n := range names {
cors[i] = all[n]
}
return cors
}
// PreflightPaths returns the paths that should handle OPTIONS requests.
func (r *ResourceDefinition) PreflightPaths() []string {
var paths []string
r.IterateActions(func(a *ActionDefinition) error {
for _, r := range a.Routes {
if r.Verb == "OPTIONS" {
continue
}
found := false
fp := r.FullPath()
for _, p := range paths {
if fp == p {
found = true
break
}
}
if !found {
paths = append(paths, fp)
}
}
return nil
})
r.IterateFileServers(func(fs *FileServerDefinition) error {
found := false
fp := fs.RequestPath
for _, p := range paths {
if fp == p {
found = true
break
}
}
if !found {
paths = append(paths, fp)
}
return nil
})
return paths
}
// DSL returns the initialization DSL.
func (r *ResourceDefinition) DSL() func() {
return r.DSLFunc
}
// Finalize is run post DSL execution. It merges response definitions, creates implicit action
// parameters, initializes querystring parameters, sets path parameters as non zero attributes
// and sets the fallbacks for security schemes.
func (r *ResourceDefinition) Finalize() {
meta := r.Metadata["swagger:generate"]
r.IterateFileServers(func(f *FileServerDefinition) error {
if meta != nil {
if _, ok := f.Metadata["swagger:generate"]; !ok {
f.Metadata["swagger:generate"] = meta
}
}
f.Finalize()
return nil
})
r.IterateActions(func(a *ActionDefinition) error {
if meta != nil {
if _, ok := a.Metadata["swagger:generate"]; !ok {
a.Metadata["swagger:generate"] = meta
}
}
a.Finalize()
return nil
})
}
// UserTypes returns all the user types used by the resource action payloads and parameters.
func (r *ResourceDefinition) UserTypes() map[string]*UserTypeDefinition {
types := make(map[string]*UserTypeDefinition)
for _, a := range r.Actions {
for n, ut := range a.UserTypes() {
types[n] = ut
}
}
if len(types) == 0 {
return nil
}
return types
}
// byParent makes it possible to sort resources - parents first the children.
type byParent []*ResourceDefinition
func (p byParent) Len() int { return len(p) }
func (p byParent) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p byParent) Less(i, j int) bool {
for k := 0; k < i; k++ {
// We need to inspect _all_ previous fields to see if they are a parent. Sort doesn't do this.
if p[i].Name == p[k].ParentName {
return true
}
}
return false
}
// Context returns the generic definition name used in error messages.
func (cors *CORSDefinition) Context() string {
return fmt.Sprintf("CORS policy for resource %s origin %s", cors.Parent.Context(), cors.Origin)
}
// Context returns the generic definition name used in error messages.
func (enc *EncodingDefinition) Context() string {
return fmt.Sprintf("encoding for %s", strings.Join(enc.MIMETypes, ", "))
}
// Context returns the generic definition name used in error messages.
func (a *AttributeDefinition) Context() string {
return ""
}
// AllRequired returns the list of all required fields from the underlying object.
// An attribute type can be itself an attribute (e.g. a MediaTypeDefinition or a UserTypeDefinition)
// This happens when the DSL uses references for example. So traverse the hierarchy and collect
// all the required validations.
func (a *AttributeDefinition) AllRequired() (required []string) {
if a == nil || a.Validation == nil {
return
}
required = a.Validation.Required
if ds, ok := a.Type.(DataStructure); ok {
required = append(required, ds.Definition().AllRequired()...)
}
return
}
// IsRequired returns true if the given string matches the name of a required
// attribute, false otherwise.
func (a *AttributeDefinition) IsRequired(attName string) bool {
for _, name := range a.AllRequired() {
if name == attName {
return true
}
}
return false
}
// HasDefaultValue returns true if the given attribute has a default value.
func (a *AttributeDefinition) HasDefaultValue(attName string) bool {
if a.Type.IsObject() {
att := a.Type.ToObject()[attName]
return att.DefaultValue != nil
}
return false
}
// SetDefault sets the default for the attribute. It also converts HashVal
// and ArrayVal to map and slice respectively.
func (a *AttributeDefinition) SetDefault(def interface{}) {
switch actual := def.(type) {
case HashVal:
a.DefaultValue = actual.ToMap()
case ArrayVal:
a.DefaultValue = actual.ToSlice()
default:
a.DefaultValue = actual
}
}
// AddValues adds the Enum values to the attribute's validation definition.
// It also performs any conversion needed for HashVal and ArrayVal types.
func (a *AttributeDefinition) AddValues(values []interface{}) {
if a.Validation == nil {
a.Validation = &dslengine.ValidationDefinition{}
}
a.Validation.Values = make([]interface{}, len(values))
for i, v := range values {
switch actual := v.(type) {
case HashVal:
a.Validation.Values[i] = actual.ToMap()
case ArrayVal:
a.Validation.Values[i] = actual.ToSlice()
default:
a.Validation.Values[i] = actual
}
}
}
// AllNonZero returns the complete list of all non-zero attribute name.
func (a *AttributeDefinition) AllNonZero() []string {