schema.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. // Copyright 2015 go-swagger maintainers
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package spec
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "net/url"
  19. "strings"
  20. "github.com/go-openapi/jsonpointer"
  21. "github.com/go-openapi/swag"
  22. )
  23. // BooleanProperty creates a boolean property
  24. func BooleanProperty() *Schema {
  25. return &Schema{SchemaProps: SchemaProps{Type: []string{"boolean"}}}
  26. }
  27. // BoolProperty creates a boolean property
  28. func BoolProperty() *Schema { return BooleanProperty() }
  29. // StringProperty creates a string property
  30. func StringProperty() *Schema {
  31. return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}
  32. }
  33. // CharProperty creates a string property
  34. func CharProperty() *Schema {
  35. return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}
  36. }
  37. // Float64Property creates a float64/double property
  38. func Float64Property() *Schema {
  39. return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "double"}}
  40. }
  41. // Float32Property creates a float32/float property
  42. func Float32Property() *Schema {
  43. return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "float"}}
  44. }
  45. // Int8Property creates an int8 property
  46. func Int8Property() *Schema {
  47. return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int8"}}
  48. }
  49. // Int16Property creates an int16 property
  50. func Int16Property() *Schema {
  51. return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int16"}}
  52. }
  53. // Int32Property creates an int32 property
  54. func Int32Property() *Schema {
  55. return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int32"}}
  56. }
  57. // Int64Property creates an int64 property
  58. func Int64Property() *Schema {
  59. return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int64"}}
  60. }
  61. // StrFmtProperty creates a property for the named string format
  62. func StrFmtProperty(format string) *Schema {
  63. return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: format}}
  64. }
  65. // DateProperty creates a date property
  66. func DateProperty() *Schema {
  67. return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date"}}
  68. }
  69. // DateTimeProperty creates a date time property
  70. func DateTimeProperty() *Schema {
  71. return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date-time"}}
  72. }
  73. // MapProperty creates a map property
  74. func MapProperty(property *Schema) *Schema {
  75. return &Schema{SchemaProps: SchemaProps{Type: []string{"object"},
  76. AdditionalProperties: &SchemaOrBool{Allows: true, Schema: property}}}
  77. }
  78. // RefProperty creates a ref property
  79. func RefProperty(name string) *Schema {
  80. return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}}
  81. }
  82. // RefSchema creates a ref property
  83. func RefSchema(name string) *Schema {
  84. return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}}
  85. }
  86. // ArrayProperty creates an array property
  87. func ArrayProperty(items *Schema) *Schema {
  88. if items == nil {
  89. return &Schema{SchemaProps: SchemaProps{Type: []string{"array"}}}
  90. }
  91. return &Schema{SchemaProps: SchemaProps{Items: &SchemaOrArray{Schema: items}, Type: []string{"array"}}}
  92. }
  93. // ComposedSchema creates a schema with allOf
  94. func ComposedSchema(schemas ...Schema) *Schema {
  95. s := new(Schema)
  96. s.AllOf = schemas
  97. return s
  98. }
  99. // SchemaURL represents a schema url
  100. type SchemaURL string
  101. // MarshalJSON marshal this to JSON
  102. func (r SchemaURL) MarshalJSON() ([]byte, error) {
  103. if r == "" {
  104. return []byte("{}"), nil
  105. }
  106. v := map[string]interface{}{"$schema": string(r)}
  107. return json.Marshal(v)
  108. }
  109. // UnmarshalJSON unmarshal this from JSON
  110. func (r *SchemaURL) UnmarshalJSON(data []byte) error {
  111. var v map[string]interface{}
  112. if err := json.Unmarshal(data, &v); err != nil {
  113. return err
  114. }
  115. return r.fromMap(v)
  116. }
  117. func (r *SchemaURL) fromMap(v map[string]interface{}) error {
  118. if v == nil {
  119. return nil
  120. }
  121. if vv, ok := v["$schema"]; ok {
  122. if str, ok := vv.(string); ok {
  123. u, err := url.Parse(str)
  124. if err != nil {
  125. return err
  126. }
  127. *r = SchemaURL(u.String())
  128. }
  129. }
  130. return nil
  131. }
  132. // SchemaProps describes a JSON schema (draft 4)
  133. type SchemaProps struct {
  134. ID string `json:"id,omitempty"`
  135. Ref Ref `json:"-"`
  136. Schema SchemaURL `json:"-"`
  137. Description string `json:"description,omitempty"`
  138. Type StringOrArray `json:"type,omitempty"`
  139. Format string `json:"format,omitempty"`
  140. Title string `json:"title,omitempty"`
  141. Default interface{} `json:"default,omitempty"`
  142. Maximum *float64 `json:"maximum,omitempty"`
  143. ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"`
  144. Minimum *float64 `json:"minimum,omitempty"`
  145. ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"`
  146. MaxLength *int64 `json:"maxLength,omitempty"`
  147. MinLength *int64 `json:"minLength,omitempty"`
  148. Pattern string `json:"pattern,omitempty"`
  149. MaxItems *int64 `json:"maxItems,omitempty"`
  150. MinItems *int64 `json:"minItems,omitempty"`
  151. UniqueItems bool `json:"uniqueItems,omitempty"`
  152. MultipleOf *float64 `json:"multipleOf,omitempty"`
  153. Enum []interface{} `json:"enum,omitempty"`
  154. MaxProperties *int64 `json:"maxProperties,omitempty"`
  155. MinProperties *int64 `json:"minProperties,omitempty"`
  156. Required []string `json:"required,omitempty"`
  157. Items *SchemaOrArray `json:"items,omitempty"`
  158. AllOf []Schema `json:"allOf,omitempty"`
  159. OneOf []Schema `json:"oneOf,omitempty"`
  160. AnyOf []Schema `json:"anyOf,omitempty"`
  161. Not *Schema `json:"not,omitempty"`
  162. Properties map[string]Schema `json:"properties,omitempty"`
  163. AdditionalProperties *SchemaOrBool `json:"additionalProperties,omitempty"`
  164. PatternProperties map[string]Schema `json:"patternProperties,omitempty"`
  165. Dependencies Dependencies `json:"dependencies,omitempty"`
  166. AdditionalItems *SchemaOrBool `json:"additionalItems,omitempty"`
  167. Definitions Definitions `json:"definitions,omitempty"`
  168. }
  169. // SwaggerSchemaProps are additional properties supported by swagger schemas, but not JSON-schema (draft 4)
  170. type SwaggerSchemaProps struct {
  171. Discriminator string `json:"discriminator,omitempty"`
  172. ReadOnly bool `json:"readOnly,omitempty"`
  173. XML *XMLObject `json:"xml,omitempty"`
  174. ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
  175. Example interface{} `json:"example,omitempty"`
  176. }
  177. // Schema the schema object allows the definition of input and output data types.
  178. // These types can be objects, but also primitives and arrays.
  179. // This object is based on the [JSON Schema Specification Draft 4](http://json-schema.org/)
  180. // and uses a predefined subset of it.
  181. // On top of this subset, there are extensions provided by this specification to allow for more complete documentation.
  182. //
  183. // For more information: http://goo.gl/8us55a#schemaObject
  184. type Schema struct {
  185. VendorExtensible
  186. SchemaProps
  187. SwaggerSchemaProps
  188. ExtraProps map[string]interface{} `json:"-"`
  189. }
  190. // JSONLookup implements an interface to customize json pointer lookup
  191. func (s Schema) JSONLookup(token string) (interface{}, error) {
  192. if ex, ok := s.Extensions[token]; ok {
  193. return &ex, nil
  194. }
  195. if ex, ok := s.ExtraProps[token]; ok {
  196. return &ex, nil
  197. }
  198. r, _, err := jsonpointer.GetForToken(s.SchemaProps, token)
  199. if r != nil || (err != nil && !strings.HasPrefix(err.Error(), "object has no field")) {
  200. return r, err
  201. }
  202. r, _, err = jsonpointer.GetForToken(s.SwaggerSchemaProps, token)
  203. return r, err
  204. }
  205. // WithID sets the id for this schema, allows for chaining
  206. func (s *Schema) WithID(id string) *Schema {
  207. s.ID = id
  208. return s
  209. }
  210. // WithTitle sets the title for this schema, allows for chaining
  211. func (s *Schema) WithTitle(title string) *Schema {
  212. s.Title = title
  213. return s
  214. }
  215. // WithDescription sets the description for this schema, allows for chaining
  216. func (s *Schema) WithDescription(description string) *Schema {
  217. s.Description = description
  218. return s
  219. }
  220. // WithProperties sets the properties for this schema
  221. func (s *Schema) WithProperties(schemas map[string]Schema) *Schema {
  222. s.Properties = schemas
  223. return s
  224. }
  225. // SetProperty sets a property on this schema
  226. func (s *Schema) SetProperty(name string, schema Schema) *Schema {
  227. if s.Properties == nil {
  228. s.Properties = make(map[string]Schema)
  229. }
  230. s.Properties[name] = schema
  231. return s
  232. }
  233. // WithAllOf sets the all of property
  234. func (s *Schema) WithAllOf(schemas ...Schema) *Schema {
  235. s.AllOf = schemas
  236. return s
  237. }
  238. // WithMaxProperties sets the max number of properties an object can have
  239. func (s *Schema) WithMaxProperties(max int64) *Schema {
  240. s.MaxProperties = &max
  241. return s
  242. }
  243. // WithMinProperties sets the min number of properties an object must have
  244. func (s *Schema) WithMinProperties(min int64) *Schema {
  245. s.MinProperties = &min
  246. return s
  247. }
  248. // Typed sets the type of this schema for a single value item
  249. func (s *Schema) Typed(tpe, format string) *Schema {
  250. s.Type = []string{tpe}
  251. s.Format = format
  252. return s
  253. }
  254. // AddType adds a type with potential format to the types for this schema
  255. func (s *Schema) AddType(tpe, format string) *Schema {
  256. s.Type = append(s.Type, tpe)
  257. if format != "" {
  258. s.Format = format
  259. }
  260. return s
  261. }
  262. // CollectionOf a fluent builder method for an array parameter
  263. func (s *Schema) CollectionOf(items Schema) *Schema {
  264. s.Type = []string{jsonArray}
  265. s.Items = &SchemaOrArray{Schema: &items}
  266. return s
  267. }
  268. // WithDefault sets the default value on this parameter
  269. func (s *Schema) WithDefault(defaultValue interface{}) *Schema {
  270. s.Default = defaultValue
  271. return s
  272. }
  273. // WithRequired flags this parameter as required
  274. func (s *Schema) WithRequired(items ...string) *Schema {
  275. s.Required = items
  276. return s
  277. }
  278. // AddRequired adds field names to the required properties array
  279. func (s *Schema) AddRequired(items ...string) *Schema {
  280. s.Required = append(s.Required, items...)
  281. return s
  282. }
  283. // WithMaxLength sets a max length value
  284. func (s *Schema) WithMaxLength(max int64) *Schema {
  285. s.MaxLength = &max
  286. return s
  287. }
  288. // WithMinLength sets a min length value
  289. func (s *Schema) WithMinLength(min int64) *Schema {
  290. s.MinLength = &min
  291. return s
  292. }
  293. // WithPattern sets a pattern value
  294. func (s *Schema) WithPattern(pattern string) *Schema {
  295. s.Pattern = pattern
  296. return s
  297. }
  298. // WithMultipleOf sets a multiple of value
  299. func (s *Schema) WithMultipleOf(number float64) *Schema {
  300. s.MultipleOf = &number
  301. return s
  302. }
  303. // WithMaximum sets a maximum number value
  304. func (s *Schema) WithMaximum(max float64, exclusive bool) *Schema {
  305. s.Maximum = &max
  306. s.ExclusiveMaximum = exclusive
  307. return s
  308. }
  309. // WithMinimum sets a minimum number value
  310. func (s *Schema) WithMinimum(min float64, exclusive bool) *Schema {
  311. s.Minimum = &min
  312. s.ExclusiveMinimum = exclusive
  313. return s
  314. }
  315. // WithEnum sets a the enum values (replace)
  316. func (s *Schema) WithEnum(values ...interface{}) *Schema {
  317. s.Enum = append([]interface{}{}, values...)
  318. return s
  319. }
  320. // WithMaxItems sets the max items
  321. func (s *Schema) WithMaxItems(size int64) *Schema {
  322. s.MaxItems = &size
  323. return s
  324. }
  325. // WithMinItems sets the min items
  326. func (s *Schema) WithMinItems(size int64) *Schema {
  327. s.MinItems = &size
  328. return s
  329. }
  330. // UniqueValues dictates that this array can only have unique items
  331. func (s *Schema) UniqueValues() *Schema {
  332. s.UniqueItems = true
  333. return s
  334. }
  335. // AllowDuplicates this array can have duplicates
  336. func (s *Schema) AllowDuplicates() *Schema {
  337. s.UniqueItems = false
  338. return s
  339. }
  340. // AddToAllOf adds a schema to the allOf property
  341. func (s *Schema) AddToAllOf(schemas ...Schema) *Schema {
  342. s.AllOf = append(s.AllOf, schemas...)
  343. return s
  344. }
  345. // WithDiscriminator sets the name of the discriminator field
  346. func (s *Schema) WithDiscriminator(discriminator string) *Schema {
  347. s.Discriminator = discriminator
  348. return s
  349. }
  350. // AsReadOnly flags this schema as readonly
  351. func (s *Schema) AsReadOnly() *Schema {
  352. s.ReadOnly = true
  353. return s
  354. }
  355. // AsWritable flags this schema as writeable (not read-only)
  356. func (s *Schema) AsWritable() *Schema {
  357. s.ReadOnly = false
  358. return s
  359. }
  360. // WithExample sets the example for this schema
  361. func (s *Schema) WithExample(example interface{}) *Schema {
  362. s.Example = example
  363. return s
  364. }
  365. // WithExternalDocs sets/removes the external docs for/from this schema.
  366. // When you pass empty strings as params the external documents will be removed.
  367. // When you pass non-empty string as one value then those values will be used on the external docs object.
  368. // So when you pass a non-empty description, you should also pass the url and vice versa.
  369. func (s *Schema) WithExternalDocs(description, url string) *Schema {
  370. if description == "" && url == "" {
  371. s.ExternalDocs = nil
  372. return s
  373. }
  374. if s.ExternalDocs == nil {
  375. s.ExternalDocs = &ExternalDocumentation{}
  376. }
  377. s.ExternalDocs.Description = description
  378. s.ExternalDocs.URL = url
  379. return s
  380. }
  381. // WithXMLName sets the xml name for the object
  382. func (s *Schema) WithXMLName(name string) *Schema {
  383. if s.XML == nil {
  384. s.XML = new(XMLObject)
  385. }
  386. s.XML.Name = name
  387. return s
  388. }
  389. // WithXMLNamespace sets the xml namespace for the object
  390. func (s *Schema) WithXMLNamespace(namespace string) *Schema {
  391. if s.XML == nil {
  392. s.XML = new(XMLObject)
  393. }
  394. s.XML.Namespace = namespace
  395. return s
  396. }
  397. // WithXMLPrefix sets the xml prefix for the object
  398. func (s *Schema) WithXMLPrefix(prefix string) *Schema {
  399. if s.XML == nil {
  400. s.XML = new(XMLObject)
  401. }
  402. s.XML.Prefix = prefix
  403. return s
  404. }
  405. // AsXMLAttribute flags this object as xml attribute
  406. func (s *Schema) AsXMLAttribute() *Schema {
  407. if s.XML == nil {
  408. s.XML = new(XMLObject)
  409. }
  410. s.XML.Attribute = true
  411. return s
  412. }
  413. // AsXMLElement flags this object as an xml node
  414. func (s *Schema) AsXMLElement() *Schema {
  415. if s.XML == nil {
  416. s.XML = new(XMLObject)
  417. }
  418. s.XML.Attribute = false
  419. return s
  420. }
  421. // AsWrappedXML flags this object as wrapped, this is mostly useful for array types
  422. func (s *Schema) AsWrappedXML() *Schema {
  423. if s.XML == nil {
  424. s.XML = new(XMLObject)
  425. }
  426. s.XML.Wrapped = true
  427. return s
  428. }
  429. // AsUnwrappedXML flags this object as an xml node
  430. func (s *Schema) AsUnwrappedXML() *Schema {
  431. if s.XML == nil {
  432. s.XML = new(XMLObject)
  433. }
  434. s.XML.Wrapped = false
  435. return s
  436. }
  437. // MarshalJSON marshal this to JSON
  438. func (s Schema) MarshalJSON() ([]byte, error) {
  439. b1, err := json.Marshal(s.SchemaProps)
  440. if err != nil {
  441. return nil, fmt.Errorf("schema props %v", err)
  442. }
  443. b2, err := json.Marshal(s.VendorExtensible)
  444. if err != nil {
  445. return nil, fmt.Errorf("vendor props %v", err)
  446. }
  447. b3, err := s.Ref.MarshalJSON()
  448. if err != nil {
  449. return nil, fmt.Errorf("ref prop %v", err)
  450. }
  451. b4, err := s.Schema.MarshalJSON()
  452. if err != nil {
  453. return nil, fmt.Errorf("schema prop %v", err)
  454. }
  455. b5, err := json.Marshal(s.SwaggerSchemaProps)
  456. if err != nil {
  457. return nil, fmt.Errorf("common validations %v", err)
  458. }
  459. var b6 []byte
  460. if s.ExtraProps != nil {
  461. jj, err := json.Marshal(s.ExtraProps)
  462. if err != nil {
  463. return nil, fmt.Errorf("extra props %v", err)
  464. }
  465. b6 = jj
  466. }
  467. return swag.ConcatJSON(b1, b2, b3, b4, b5, b6), nil
  468. }
  469. // UnmarshalJSON marshal this from JSON
  470. func (s *Schema) UnmarshalJSON(data []byte) error {
  471. props := struct {
  472. SchemaProps
  473. SwaggerSchemaProps
  474. }{}
  475. if err := json.Unmarshal(data, &props); err != nil {
  476. return err
  477. }
  478. sch := Schema{
  479. SchemaProps: props.SchemaProps,
  480. SwaggerSchemaProps: props.SwaggerSchemaProps,
  481. }
  482. var d map[string]interface{}
  483. if err := json.Unmarshal(data, &d); err != nil {
  484. return err
  485. }
  486. _ = sch.Ref.fromMap(d)
  487. _ = sch.Schema.fromMap(d)
  488. delete(d, "$ref")
  489. delete(d, "$schema")
  490. for _, pn := range swag.DefaultJSONNameProvider.GetJSONNames(s) {
  491. delete(d, pn)
  492. }
  493. for k, vv := range d {
  494. lk := strings.ToLower(k)
  495. if strings.HasPrefix(lk, "x-") {
  496. if sch.Extensions == nil {
  497. sch.Extensions = map[string]interface{}{}
  498. }
  499. sch.Extensions[k] = vv
  500. continue
  501. }
  502. if sch.ExtraProps == nil {
  503. sch.ExtraProps = map[string]interface{}{}
  504. }
  505. sch.ExtraProps[k] = vv
  506. }
  507. *s = sch
  508. return nil
  509. }