Skip to content

Commit

Permalink
feat: add cue util to convert jsonschema to cue
Browse files Browse the repository at this point in the history
Signed-off-by: Nithish <nithishkarthik01@gmail.com>
  • Loading branch information
humblenginr committed Aug 8, 2022
1 parent d7f049d commit 2cb1117
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
2 changes: 1 addition & 1 deletion helpers/component_info.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "meshkit",
"type": "library",
"next_error_code": 11087
"next_error_code": 11088
}
30 changes: 30 additions & 0 deletions utils/cue.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package utils
import (
"cuelang.org/go/cue"
"cuelang.org/go/cue/cuecontext"
"cuelang.org/go/cue/format"
"cuelang.org/go/encoding/json"
"cuelang.org/go/encoding/jsonschema"
"cuelang.org/go/encoding/yaml"
)

Expand Down Expand Up @@ -42,3 +44,31 @@ func YamlToCue(value string) (cue.Value, error) {
}
return out, nil
}

func JsonSchemaToCue(value string) (cue.Value, error) {
var out cue.Value
jsonSchema, err := json.Extract("", []byte(value))
if err != nil {
return out, ErrJsonSchemaToCue(err)
}
cueCtx := cuecontext.New()
cueJsonSchemaExpr := cueCtx.BuildExpr(jsonSchema)
if err := cueJsonSchemaExpr.Err(); err != nil {
return out, ErrJsonSchemaToCue(err)
}
extractedSchema, err := jsonschema.Extract(cueJsonSchemaExpr, &jsonschema.Config{
PkgName: "jsonschemeconv",
})
if err != nil {
return out, ErrJsonSchemaToCue(err)
}
src, err := format.Node(extractedSchema)
if err != nil {
return out, ErrJsonSchemaToCue(err)
}
out = cueCtx.CompileString(string(src))
if out.Err() != nil {
return out, ErrJsonSchemaToCue(out.Err())
}
return out, nil
}
5 changes: 5 additions & 0 deletions utils/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,13 @@ var (
ErrExpectedTypeMismatchCode = "11079"
ErrJsonToCueCode = "11085"
ErrYamlToCueCode = "11086"
ErrJsonSchemaToCueCode = "11087"
)

func ErrJsonSchemaToCue(err error) error {
return errors.New(ErrJsonSchemaToCueCode, errors.Alert, []string{"Could not convert given JsonSchema into a CUE Value"}, []string{err.Error()}, []string{"Invalid jsonschema"}, []string{"Make sure that the given value is a valid JSONSCHEMA"})
}

func ErrYamlToCue(err error) error {
return errors.New(ErrYamlToCueCode, errors.Alert, []string{"Could not convert given yaml object into a CUE Value"}, []string{err.Error()}, []string{"Invalid yaml"}, []string{"Make sure that the given value is a valid YAML"})
}
Expand Down

0 comments on commit 2cb1117

Please sign in to comment.