本站源代码
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

597 lignes
17KB

  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 map[string]Schema `json:"properties,omitempty"`
  164. AdditionalProperties *SchemaOrBool `json:"additionalProperties,omitempty"`
  165. PatternProperties map[string]Schema `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. }
上海开阖软件有限公司 沪ICP备12045867号-1