-
Notifications
You must be signed in to change notification settings - Fork 0
/
swagdef.go
57 lines (47 loc) · 1.53 KB
/
swagdef.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* package swagdef provides methods to operate json data and swag definition */
package swagdef
import (
"encoding/json"
"fmt"
"github.com/go-openapi/spec"
modelcollections "github.com/footprintai/restcol/pkg/models/collections"
jsruntime "github.com/footprintai/restcol/pkg/runtime/js"
)
// swagJsonMessageToSwagDef returns *spec.Definition by giving swag definition in json, ex:
//
// {
// "definitions": {
// "foo": {}
// }
func swagJsonMessageToSwagDef(j json.RawMessage) (*spec.Definitions, error) {
swagSpec := &spec.Swagger{}
if err := swagSpec.UnmarshalJSON([]byte(j)); err != nil {
return nil, err
}
return &swagSpec.SwaggerProps.Definitions, nil
}
func RawJsonMessageToSwagDef(rawJson []byte) (*spec.Definitions, error) {
rt := jsruntime.NewJSRuntime("swag")
defer rt.Close()
if err := rt.Load("swagdef.js"); err != nil {
return nil, err
}
scriptInRaw := fmt.Sprintf(`doconvert('%s')`, string(rawJson))
swagJson, err := rt.Run(scriptInRaw)
if err != nil {
return nil, err
}
return swagJsonMessageToSwagDef(json.RawMessage(fmt.Sprintf("{%s}", swagJson)))
}
// ModelFieldsSchemaToSwagDef converts from dot-notation json structure
// into swag.Definitions
func ModelFieldsSchemaToSwagDef(fields []*modelcollections.ModelFieldSchema, withPrefixs ...string) (*spec.Definitions, error) {
if len(fields) > 0 {
fieldsWithJson, err := modelcollections.ModelFieldsSchema(fields).ToJSON(withPrefixs...)
if err != nil {
return nil, err
}
return RawJsonMessageToSwagDef(fieldsWithJson)
}
return &spec.Definitions{}, nil
}