schema.go 17 KB

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