1package openapi3
2
3import (
4	"context"
5
6	"github.com/getkin/kin-openapi/jsoninfo"
7	"github.com/go-openapi/jsonpointer"
8)
9
10// MediaType is specified by OpenAPI/Swagger 3.0 standard.
11type MediaType struct {
12	ExtensionProps
13
14	Schema   *SchemaRef           `json:"schema,omitempty" yaml:"schema,omitempty"`
15	Example  interface{}          `json:"example,omitempty" yaml:"example,omitempty"`
16	Examples Examples             `json:"examples,omitempty" yaml:"examples,omitempty"`
17	Encoding map[string]*Encoding `json:"encoding,omitempty" yaml:"encoding,omitempty"`
18}
19
20var _ jsonpointer.JSONPointable = (*MediaType)(nil)
21
22func NewMediaType() *MediaType {
23	return &MediaType{}
24}
25
26func (mediaType *MediaType) WithSchema(schema *Schema) *MediaType {
27	if schema == nil {
28		mediaType.Schema = nil
29	} else {
30		mediaType.Schema = &SchemaRef{Value: schema}
31	}
32	return mediaType
33}
34
35func (mediaType *MediaType) WithSchemaRef(schema *SchemaRef) *MediaType {
36	mediaType.Schema = schema
37	return mediaType
38}
39
40func (mediaType *MediaType) WithExample(name string, value interface{}) *MediaType {
41	example := mediaType.Examples
42	if example == nil {
43		example = make(map[string]*ExampleRef)
44		mediaType.Examples = example
45	}
46	example[name] = &ExampleRef{
47		Value: NewExample(value),
48	}
49	return mediaType
50}
51
52func (mediaType *MediaType) WithEncoding(name string, enc *Encoding) *MediaType {
53	encoding := mediaType.Encoding
54	if encoding == nil {
55		encoding = make(map[string]*Encoding)
56		mediaType.Encoding = encoding
57	}
58	encoding[name] = enc
59	return mediaType
60}
61
62func (mediaType *MediaType) MarshalJSON() ([]byte, error) {
63	return jsoninfo.MarshalStrictStruct(mediaType)
64}
65
66func (mediaType *MediaType) UnmarshalJSON(data []byte) error {
67	return jsoninfo.UnmarshalStrictStruct(data, mediaType)
68}
69
70func (value *MediaType) Validate(ctx context.Context) error {
71	if value == nil {
72		return nil
73	}
74	if schema := value.Schema; schema != nil {
75		if err := schema.Validate(ctx); err != nil {
76			return err
77		}
78	}
79	return nil
80}
81
82func (mediaType MediaType) JSONLookup(token string) (interface{}, error) {
83	switch token {
84	case "schema":
85		if mediaType.Schema != nil {
86			if mediaType.Schema.Ref != "" {
87				return &Ref{Ref: mediaType.Schema.Ref}, nil
88			}
89			return mediaType.Schema.Value, nil
90		}
91	case "example":
92		return mediaType.Example, nil
93	case "examples":
94		return mediaType.Examples, nil
95	case "encoding":
96		return mediaType.Encoding, nil
97	}
98	v, _, err := jsonpointer.GetForToken(mediaType.ExtensionProps, token)
99	return v, err
100}
101