Skip to content
This repository has been archived by the owner on Nov 18, 2021. It is now read-only.

Commit

Permalink
encoding/jsonschema: add support for OpenAPI nullable
Browse files Browse the repository at this point in the history
Change-Id: I5f7346e08933fc9ac1896765f99070bf0868d359
Reviewed-on: https://cue-review.googlesource.com/c/cue/+/6321
Reviewed-by: Marcel van Lohuizen <mpvl@golang.org>
Reviewed-by: Johan Euphrosine <proppy@google.com>
Reviewed-by: CUE cueckoo <cueckoo@gmail.com>
  • Loading branch information
mpvl committed Jun 16, 2020
1 parent a91b869 commit 7aa2eb7
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
7 changes: 7 additions & 0 deletions encoding/jsonschema/constraints.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,13 @@ var constraints = []*constraint{
s.all.add(n, ast.NewBinExpr(token.OR, a...))
}),

// TODO: only allow for OpenAPI.
p1("nullable", func(n cue.Value, s *state) {
null := ast.NewNull()
setPos(null, n)
s.nullable = null
}),

p1d("const", 6, func(n cue.Value, s *state) {
s.all.add(n, s.value(n))
}),
Expand Down
20 changes: 15 additions & 5 deletions encoding/jsonschema/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,8 +320,9 @@ type state struct {
pos cue.Value

// The constraints in types represent disjunctions per type.
types [numCoreTypes]constraintInfo
all constraintInfo // values and oneOf etc.
types [numCoreTypes]constraintInfo
all constraintInfo // values and oneOf etc.
nullable *ast.BasicLit // nullable

usedTypes cue.Kind
allowedTypes cue.Kind
Expand Down Expand Up @@ -463,17 +464,26 @@ func (s *state) finalize() (e ast.Expr) {
e = ast.NewBinExpr(token.AND, conjuncts...)
}

if s.default_ != nil {
a := []ast.Expr{e}
if s.nullable != nil {
a = []ast.Expr{s.nullable, e}
}

outer:
switch {
case s.default_ != nil:
// check conditions where default can be skipped.
switch x := s.default_.(type) {
case *ast.ListLit:
if s.usedTypes == cue.ListKind && len(x.Elts) == 0 {
return e
break outer
}
}
e = ast.NewBinExpr(token.OR, e, &ast.UnaryExpr{Op: token.MUL, X: s.default_})
a = append(a, &ast.UnaryExpr{Op: token.MUL, X: s.default_})
}

e = ast.NewBinExpr(token.OR, a...)

if len(s.definitions) > 0 {
if st, ok := e.(*ast.StructLit); ok {
st.Elts = append(st.Elts, s.definitions...)
Expand Down
3 changes: 2 additions & 1 deletion encoding/jsonschema/testdata/openapi.txtar
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ components:
type: string
address:
$ref: "#/components/schemas/PhoneNumber"
nullable: true
PhoneNumber:
description: "The number to dial."
type: string
Expand All @@ -22,7 +23,7 @@ components:
#User: {
name?: string
id?: int
address?: #PhoneNumber
address?: null | #PhoneNumber
...
}

Expand Down

0 comments on commit 7aa2eb7

Please sign in to comment.