schema.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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"}, AdditionalProperties: &SchemaOrBool{Allows: true, Schema: property}}}
  76. }
  77. // RefProperty creates a ref property
  78. func RefProperty(name string) *Schema {
  79. return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}}
  80. }
  81. // RefSchema creates a ref property
  82. func RefSchema(name string) *Schema {
  83. return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}}
  84. }
  85. // ArrayProperty creates an array property
  86. func ArrayProperty(items *Schema) *Schema {
  87. if items == nil {
  88. return &Schema{SchemaProps: SchemaProps{Type: []string{"array"}}}
  89. }
  90. return &Schema{SchemaProps: SchemaProps{Items: &SchemaOrArray{Schema: items}, Type: []string{"array"}}}
  91. }
  92. // ComposedSchema creates a schema with allOf
  93. func ComposedSchema(schemas ...Schema) *Schema {
  94. s := new(Schema)
  95. s.AllOf = schemas
  96. return s
  97. }
  98. // SchemaURL represents a schema url
  99. type SchemaURL string
  100. // MarshalJSON marshal this to JSON
  101. func (r SchemaURL) MarshalJSON() ([]byte, error) {
  102. if r == "" {
  103. return []byte("{}"), nil
  104. }
  105. v := map[string]interface{}{"$schema": string(r)}
  106. return json.Marshal(v)
  107. }
  108. // UnmarshalJSON unmarshal this from JSON
  109. func (r *SchemaURL) UnmarshalJSON(data []byte) error {
  110. var v map[string]interface{}
  111. if err := json.Unmarshal(data, &v); err != nil {
  112. return err
  113. }
  114. if v == nil {
  115. return nil
  116. }
  117. if vv, ok := v["$schema"]; ok {
  118. if str, ok := vv.(string); ok {
  119. u, err := url.Parse(str)
  120. if err != nil {
  121. return err
  122. }
  123. *r = SchemaURL(u.String())
  124. }
  125. }
  126. return nil
  127. }
  128. // type ExtraSchemaProps map[string]interface{}
  129. // // JSONSchema represents a structure that is a json schema draft 04
  130. // type JSONSchema struct {
  131. // SchemaProps
  132. // ExtraSchemaProps
  133. // }
  134. // // MarshalJSON marshal this to JSON
  135. // func (s JSONSchema) MarshalJSON() ([]byte, error) {
  136. // b1, err := json.Marshal(s.SchemaProps)
  137. // if err != nil {
  138. // return nil, err
  139. // }
  140. // b2, err := s.Ref.MarshalJSON()
  141. // if err != nil {
  142. // return nil, err
  143. // }
  144. // b3, err := s.Schema.MarshalJSON()
  145. // if err != nil {
  146. // return nil, err
  147. // }
  148. // b4, err := json.Marshal(s.ExtraSchemaProps)
  149. // if err != nil {
  150. // return nil, err
  151. // }
  152. // return swag.ConcatJSON(b1, b2, b3, b4), nil
  153. // }
  154. // // UnmarshalJSON marshal this from JSON
  155. // func (s *JSONSchema) UnmarshalJSON(data []byte) error {
  156. // var sch JSONSchema
  157. // if err := json.Unmarshal(data, &sch.SchemaProps); err != nil {
  158. // return err
  159. // }
  160. // if err := json.Unmarshal(data, &sch.Ref); err != nil {
  161. // return err
  162. // }
  163. // if err := json.Unmarshal(data, &sch.Schema); err != nil {
  164. // return err
  165. // }
  166. // if err := json.Unmarshal(data, &sch.ExtraSchemaProps); err != nil {
  167. // return err
  168. // }
  169. // *s = sch
  170. // return nil
  171. // }
  172. type SchemaProps struct {
  173. ID string `json:"id,omitempty"`
  174. Ref Ref `json:"-,omitempty"`
  175. Schema SchemaURL `json:"-,omitempty"`
  176. Description string `json:"description,omitempty"`
  177. Type StringOrArray `json:"type,omitempty"`
  178. Format string `json:"format,omitempty"`
  179. Title string `json:"title,omitempty"`
  180. Default interface{} `json:"default,omitempty"`
  181. Maximum *float64 `json:"maximum,omitempty"`
  182. ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"`
  183. Minimum *float64 `json:"minimum,omitempty"`
  184. ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"`
  185. MaxLength *int64 `json:"maxLength,omitempty"`
  186. MinLength *int64 `json:"minLength,omitempty"`
  187. Pattern string `json:"pattern,omitempty"`
  188. MaxItems *int64 `json:"maxItems,omitempty"`
  189. MinItems *int64 `json:"minItems,omitempty"`
  190. UniqueItems bool `json:"uniqueItems,omitempty"`
  191. MultipleOf *float64 `json:"multipleOf,omitempty"`
  192. Enum []interface{} `json:"enum,omitempty"`
  193. MaxProperties *int64 `json:"maxProperties,omitempty"`
  194. MinProperties *int64 `json:"minProperties,omitempty"`
  195. Required []string `json:"required,omitempty"`
  196. Items *SchemaOrArray `json:"items,omitempty"`
  197. AllOf []Schema `json:"allOf,omitempty"`
  198. OneOf []Schema `json:"oneOf,omitempty"`
  199. AnyOf []Schema `json:"anyOf,omitempty"`
  200. Not *Schema `json:"not,omitempty"`
  201. Properties map[string]Schema `json:"properties,omitempty"`
  202. AdditionalProperties *SchemaOrBool `json:"additionalProperties,omitempty"`
  203. PatternProperties map[string]Schema `json:"patternProperties,omitempty"`
  204. Dependencies Dependencies `json:"dependencies,omitempty"`
  205. AdditionalItems *SchemaOrBool `json:"additionalItems,omitempty"`
  206. Definitions Definitions `json:"definitions,omitempty"`
  207. }
  208. type SwaggerSchemaProps struct {
  209. Discriminator string `json:"discriminator,omitempty"`
  210. ReadOnly bool `json:"readOnly,omitempty"`
  211. XML *XMLObject `json:"xml,omitempty"`
  212. ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"`
  213. Example interface{} `json:"example,omitempty"`
  214. }
  215. // Schema the schema object allows the definition of input and output data types.
  216. // These types can be objects, but also primitives and arrays.
  217. // This object is based on the [JSON Schema Specification Draft 4](http://json-schema.org/)
  218. // and uses a predefined subset of it.
  219. // On top of this subset, there are extensions provided by this specification to allow for more complete documentation.
  220. //
  221. // For more information: http://goo.gl/8us55a#schemaObject
  222. type Schema struct {
  223. VendorExtensible
  224. SchemaProps
  225. SwaggerSchemaProps
  226. ExtraProps map[string]interface{} `json:"-"`
  227. }
  228. // JSONLookup implements an interface to customize json pointer lookup
  229. func (s Schema) JSONLookup(token string) (interface{}, error) {
  230. if ex, ok := s.Extensions[token]; ok {
  231. return &ex, nil
  232. }
  233. if ex, ok := s.ExtraProps[token]; ok {
  234. return &ex, nil
  235. }
  236. r, _, err := jsonpointer.GetForToken(s.SchemaProps, token)
  237. if r != nil || err != nil {
  238. return r, err
  239. }
  240. r, _, err = jsonpointer.GetForToken(s.SwaggerSchemaProps, token)
  241. return r, err
  242. }
  243. // WithID sets the id for this schema, allows for chaining
  244. func (s *Schema) WithID(id string) *Schema {
  245. s.ID = id
  246. return s
  247. }
  248. // WithTitle sets the title for this schema, allows for chaining
  249. func (s *Schema) WithTitle(title string) *Schema {
  250. s.Title = title
  251. return s
  252. }
  253. // WithDescription sets the description for this schema, allows for chaining
  254. func (s *Schema) WithDescription(description string) *Schema {
  255. s.Description = description
  256. return s
  257. }
  258. // WithProperties sets the properties for this schema
  259. func (s *Schema) WithProperties(schemas map[string]Schema) *Schema {
  260. s.Properties = schemas
  261. return s
  262. }
  263. // SetProperty sets a property on this schema
  264. func (s *Schema) SetProperty(name string, schema Schema) *Schema {
  265. if s.Properties == nil {
  266. s.Properties = make(map[string]Schema)
  267. }
  268. s.Properties[name] = schema
  269. return s
  270. }
  271. // WithAllOf sets the all of property
  272. func (s *Schema) WithAllOf(schemas ...Schema) *Schema {
  273. s.AllOf = schemas
  274. return s
  275. }
  276. // WithMaxProperties sets the max number of properties an object can have
  277. func (s *Schema) WithMaxProperties(max int64) *Schema {
  278. s.MaxProperties = &max
  279. return s
  280. }
  281. // WithMinProperties sets the min number of properties an object must have
  282. func (s *Schema) WithMinProperties(min int64) *Schema {
  283. s.MinProperties = &min
  284. return s
  285. }
  286. // Typed sets the type of this schema for a single value item
  287. func (s *Schema) Typed(tpe, format string) *Schema {
  288. s.Type = []string{tpe}
  289. s.Format = format
  290. return s
  291. }
  292. // AddType adds a type with potential format to the types for this schema
  293. func (s *Schema) AddType(tpe, format string) *Schema {
  294. s.Type = append(s.Type, tpe)
  295. if format != "" {
  296. s.Format = format
  297. }
  298. return s
  299. }
  300. // CollectionOf a fluent builder method for an array parameter
  301. func (s *Schema) CollectionOf(items Schema) *Schema {
  302. s.Type = []string{"array"}
  303. s.Items = &SchemaOrArray{Schema: &items}
  304. return s
  305. }
  306. // WithDefault sets the default value on this parameter
  307. func (s *Schema) WithDefault(defaultValue interface{}) *Schema {
  308. s.Default = defaultValue
  309. return s
  310. }
  311. // WithRequired flags this parameter as required
  312. func (s *Schema) WithRequired(items ...string) *Schema {
  313. s.Required = items
  314. return s
  315. }
  316. // AddRequired adds field names to the required properties array
  317. func (s *Schema) AddRequired(items ...string) *Schema {
  318. s.Required = append(s.Required, items...)
  319. return s
  320. }
  321. // WithMaxLength sets a max length value
  322. func (s *Schema) WithMaxLength(max int64) *Schema {
  323. s.MaxLength = &max
  324. return s
  325. }
  326. // WithMinLength sets a min length value
  327. func (s *Schema) WithMinLength(min int64) *Schema {
  328. s.MinLength = &min
  329. return s
  330. }
  331. // WithPattern sets a pattern value
  332. func (s *Schema) WithPattern(pattern string) *Schema {
  333. s.Pattern = pattern
  334. return s
  335. }
  336. // WithMultipleOf sets a multiple of value
  337. func (s *Schema) WithMultipleOf(number float64) *Schema {
  338. s.MultipleOf = &number
  339. return s
  340. }
  341. // WithMaximum sets a maximum number value
  342. func (s *Schema) WithMaximum(max float64, exclusive bool) *Schema {
  343. s.Maximum = &max
  344. s.ExclusiveMaximum = exclusive
  345. return s
  346. }
  347. // WithMinimum sets a minimum number value
  348. func (s *Schema) WithMinimum(min float64, exclusive bool) *Schema {
  349. s.Minimum = &min
  350. s.ExclusiveMinimum = exclusive
  351. return s
  352. }
  353. // WithEnum sets a the enum values (replace)
  354. func (s *Schema) WithEnum(values ...interface{}) *Schema {
  355. s.Enum = append([]interface{}{}, values...)
  356. return s
  357. }
  358. // WithMaxItems sets the max items
  359. func (s *Schema) WithMaxItems(size int64) *Schema {
  360. s.MaxItems = &size
  361. return s
  362. }
  363. // WithMinItems sets the min items
  364. func (s *Schema) WithMinItems(size int64) *Schema {
  365. s.MinItems = &size
  366. return s
  367. }
  368. // UniqueValues dictates that this array can only have unique items
  369. func (s *Schema) UniqueValues() *Schema {
  370. s.UniqueItems = true
  371. return s
  372. }
  373. // AllowDuplicates this array can have duplicates
  374. func (s *Schema) AllowDuplicates() *Schema {
  375. s.UniqueItems = false
  376. return s
  377. }
  378. // AddToAllOf adds a schema to the allOf property
  379. func (s *Schema) AddToAllOf(schemas ...Schema) *Schema {
  380. s.AllOf = append(s.AllOf, schemas...)
  381. return s
  382. }
  383. // WithDiscriminator sets the name of the discriminator field
  384. func (s *Schema) WithDiscriminator(discriminator string) *Schema {
  385. s.Discriminator = discriminator
  386. return s
  387. }
  388. // AsReadOnly flags this schema as readonly
  389. func (s *Schema) AsReadOnly() *Schema {
  390. s.ReadOnly = true
  391. return s
  392. }
  393. // AsWritable flags this schema as writeable (not read-only)
  394. func (s *Schema) AsWritable() *Schema {
  395. s.ReadOnly = false
  396. return s
  397. }
  398. // WithExample sets the example for this schema
  399. func (s *Schema) WithExample(example interface{}) *Schema {
  400. s.Example = example
  401. return s
  402. }
  403. // WithExternalDocs sets/removes the external docs for/from this schema.
  404. // When you pass empty strings as params the external documents will be removed.
  405. // When you pass non-empty string as one value then those values will be used on the external docs object.
  406. // So when you pass a non-empty description, you should also pass the url and vice versa.
  407. func (s *Schema) WithExternalDocs(description, url string) *Schema {
  408. if description == "" && url == "" {
  409. s.ExternalDocs = nil
  410. return s
  411. }
  412. if s.ExternalDocs == nil {
  413. s.ExternalDocs = &ExternalDocumentation{}
  414. }
  415. s.ExternalDocs.Description = description
  416. s.ExternalDocs.URL = url
  417. return s
  418. }
  419. // WithXMLName sets the xml name for the object
  420. func (s *Schema) WithXMLName(name string) *Schema {
  421. if s.XML == nil {
  422. s.XML = new(XMLObject)
  423. }
  424. s.XML.Name = name
  425. return s
  426. }
  427. // WithXMLNamespace sets the xml namespace for the object
  428. func (s *Schema) WithXMLNamespace(namespace string) *Schema {
  429. if s.XML == nil {
  430. s.XML = new(XMLObject)
  431. }
  432. s.XML.Namespace = namespace
  433. return s
  434. }
  435. // WithXMLPrefix sets the xml prefix for the object
  436. func (s *Schema) WithXMLPrefix(prefix string) *Schema {
  437. if s.XML == nil {
  438. s.XML = new(XMLObject)
  439. }
  440. s.XML.Prefix = prefix
  441. return s
  442. }
  443. // AsXMLAttribute flags this object as xml attribute
  444. func (s *Schema) AsXMLAttribute() *Schema {
  445. if s.XML == nil {
  446. s.XML = new(XMLObject)
  447. }
  448. s.XML.Attribute = true
  449. return s
  450. }
  451. // AsXMLElement flags this object as an xml node
  452. func (s *Schema) AsXMLElement() *Schema {
  453. if s.XML == nil {
  454. s.XML = new(XMLObject)
  455. }
  456. s.XML.Attribute = false
  457. return s
  458. }
  459. // AsWrappedXML flags this object as wrapped, this is mostly useful for array types
  460. func (s *Schema) AsWrappedXML() *Schema {
  461. if s.XML == nil {
  462. s.XML = new(XMLObject)
  463. }
  464. s.XML.Wrapped = true
  465. return s
  466. }
  467. // AsUnwrappedXML flags this object as an xml node
  468. func (s *Schema) AsUnwrappedXML() *Schema {
  469. if s.XML == nil {
  470. s.XML = new(XMLObject)
  471. }
  472. s.XML.Wrapped = false
  473. return s
  474. }
  475. // MarshalJSON marshal this to JSON
  476. func (s Schema) MarshalJSON() ([]byte, error) {
  477. b1, err := json.Marshal(s.SchemaProps)
  478. if err != nil {
  479. return nil, fmt.Errorf("schema props %v", err)
  480. }
  481. b2, err := json.Marshal(s.VendorExtensible)
  482. if err != nil {
  483. return nil, fmt.Errorf("vendor props %v", err)
  484. }
  485. b3, err := s.Ref.MarshalJSON()
  486. if err != nil {
  487. return nil, fmt.Errorf("ref prop %v", err)
  488. }
  489. b4, err := s.Schema.MarshalJSON()
  490. if err != nil {
  491. return nil, fmt.Errorf("schema prop %v", err)
  492. }
  493. b5, err := json.Marshal(s.SwaggerSchemaProps)
  494. if err != nil {
  495. return nil, fmt.Errorf("common validations %v", err)
  496. }
  497. var b6 []byte
  498. if s.ExtraProps != nil {
  499. jj, err := json.Marshal(s.ExtraProps)
  500. if err != nil {
  501. return nil, fmt.Errorf("extra props %v", err)
  502. }
  503. b6 = jj
  504. }
  505. return swag.ConcatJSON(b1, b2, b3, b4, b5, b6), nil
  506. }
  507. // UnmarshalJSON marshal this from JSON
  508. func (s *Schema) UnmarshalJSON(data []byte) error {
  509. var sch Schema
  510. if err := json.Unmarshal(data, &sch.SchemaProps); err != nil {
  511. return err
  512. }
  513. if err := json.Unmarshal(data, &sch.Ref); err != nil {
  514. return err
  515. }
  516. if err := json.Unmarshal(data, &sch.Schema); err != nil {
  517. return err
  518. }
  519. if err := json.Unmarshal(data, &sch.SwaggerSchemaProps); err != nil {
  520. return err
  521. }
  522. var d map[string]interface{}
  523. if err := json.Unmarshal(data, &d); err != nil {
  524. return err
  525. }
  526. delete(d, "$ref")
  527. delete(d, "$schema")
  528. for _, pn := range swag.DefaultJSONNameProvider.GetJSONNames(s) {
  529. delete(d, pn)
  530. }
  531. for k, vv := range d {
  532. lk := strings.ToLower(k)
  533. if strings.HasPrefix(lk, "x-") {
  534. if sch.Extensions == nil {
  535. sch.Extensions = map[string]interface{}{}
  536. }
  537. sch.Extensions[k] = vv
  538. continue
  539. }
  540. if sch.ExtraProps == nil {
  541. sch.ExtraProps = map[string]interface{}{}
  542. }
  543. sch.ExtraProps[k] = vv
  544. }
  545. *s = sch
  546. return nil
  547. }