Skip to content

Commit 7aa2eb7

Browse files
committed
encoding/jsonschema: add support for OpenAPI nullable
Change-Id: I5f7346e08933fc9ac1896765f99070bf0868d359 Reviewed-on: https://cue-review.googlesource.com/c/cue/+/6321 Reviewed-by: Marcel van Lohuizen <[email protected]> Reviewed-by: Johan Euphrosine <[email protected]> Reviewed-by: CUE cueckoo <[email protected]>
1 parent a91b869 commit 7aa2eb7

File tree

3 files changed

+24
-6
lines changed

3 files changed

+24
-6
lines changed

encoding/jsonschema/constraints.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,13 @@ var constraints = []*constraint{
213213
s.all.add(n, ast.NewBinExpr(token.OR, a...))
214214
}),
215215

216+
// TODO: only allow for OpenAPI.
217+
p1("nullable", func(n cue.Value, s *state) {
218+
null := ast.NewNull()
219+
setPos(null, n)
220+
s.nullable = null
221+
}),
222+
216223
p1d("const", 6, func(n cue.Value, s *state) {
217224
s.all.add(n, s.value(n))
218225
}),

encoding/jsonschema/decode.go

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -320,8 +320,9 @@ type state struct {
320320
pos cue.Value
321321

322322
// The constraints in types represent disjunctions per type.
323-
types [numCoreTypes]constraintInfo
324-
all constraintInfo // values and oneOf etc.
323+
types [numCoreTypes]constraintInfo
324+
all constraintInfo // values and oneOf etc.
325+
nullable *ast.BasicLit // nullable
325326

326327
usedTypes cue.Kind
327328
allowedTypes cue.Kind
@@ -463,17 +464,26 @@ func (s *state) finalize() (e ast.Expr) {
463464
e = ast.NewBinExpr(token.AND, conjuncts...)
464465
}
465466

466-
if s.default_ != nil {
467+
a := []ast.Expr{e}
468+
if s.nullable != nil {
469+
a = []ast.Expr{s.nullable, e}
470+
}
471+
472+
outer:
473+
switch {
474+
case s.default_ != nil:
467475
// check conditions where default can be skipped.
468476
switch x := s.default_.(type) {
469477
case *ast.ListLit:
470478
if s.usedTypes == cue.ListKind && len(x.Elts) == 0 {
471-
return e
479+
break outer
472480
}
473481
}
474-
e = ast.NewBinExpr(token.OR, e, &ast.UnaryExpr{Op: token.MUL, X: s.default_})
482+
a = append(a, &ast.UnaryExpr{Op: token.MUL, X: s.default_})
475483
}
476484

485+
e = ast.NewBinExpr(token.OR, a...)
486+
477487
if len(s.definitions) > 0 {
478488
if st, ok := e.(*ast.StructLit); ok {
479489
st.Elts = append(st.Elts, s.definitions...)

encoding/jsonschema/testdata/openapi.txtar

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ components:
1313
type: string
1414
address:
1515
$ref: "#/components/schemas/PhoneNumber"
16+
nullable: true
1617
PhoneNumber:
1718
description: "The number to dial."
1819
type: string
@@ -22,7 +23,7 @@ components:
2223
#User: {
2324
name?: string
2425
id?: int
25-
address?: #PhoneNumber
26+
address?: null | #PhoneNumber
2627
...
2728
}
2829

0 commit comments

Comments
 (0)