Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for decoding string/date-time to time.Time #3

Merged
merged 1 commit into from
May 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,9 @@ func (g *Generator) processObject(name string, schema *Schema, conventions map[s
Description: prop.Description,
Format: prop.Format,
}
if f.Type == "string" && f.Format == "date-time" {
strct.importTypes = append(strct.importTypes, "time")
}
if f.Required {
strct.GenerateCode = true
}
Expand Down Expand Up @@ -324,7 +327,7 @@ func (g *Generator) getSchemaName(keyName string, schema *Schema, conventions ma
return getGolangName(schema.JSONKey, conventions)
}
if schema.Parent != nil && schema.Parent.JSONKey != "" {
return getGolangName(schema.Parent.JSONKey + "Item", conventions)
return getGolangName(schema.Parent.JSONKey+"Item", conventions)
}
g.anonCount++
return fmt.Sprintf("Anonymous%d", g.anonCount)
Expand Down Expand Up @@ -395,6 +398,7 @@ type Struct struct {

GenerateCode bool
AdditionalType string
importTypes []string // addition packages to include when importing
}

// Field defines the data required to generate a field in Go.
Expand Down
57 changes: 57 additions & 0 deletions generator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,63 @@ func TestTypeAliases(t *testing.T) {
}
}

func TestImportTypeDetection(t *testing.T) {
tests := []struct {
name string
input *Schema
expect []string
}{{
name: "no additional types",
input: &Schema{
Title: "example",
TypeValue: "object",
Properties: map[string]*Schema{
"key": {TypeValue: "string"},
},
},
expect: []string{},
}, {
name: "string/date-time imports time",
input: &Schema{
Title: "example",
TypeValue: "object",
Properties: map[string]*Schema{
"key": {
TypeValue: "string",
Format: "date-time",
},
},
},
expect: []string{"time"},
}}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
test.input.Init()
g := New(test.input)
err := g.CreateTypes(conventionStub)

if err != nil {
t.Fatal(err)
}
vals := make([]string, 0)
for _, strct := range g.Structs {
vals = append(vals, strct.importTypes...)
}

if len(vals) != len(test.expect) {
t.Fatalf("Expected %d values in import types, got %d", len(test.expect), len(vals))
}

for i, s := range test.expect {
if vals[i] != s {
t.Errorf("Expected value %d of import types to be %q, got %q", i, s, vals[i])
}
}

})
}
}

// Root is an example of a generated type.
type Root struct {
Name interface{} `json:"name,omitempty"`
Expand Down
9 changes: 7 additions & 2 deletions output.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ func Output(w io.Writer, g *Generator, pkg string, skipCode bool, esdoc bool) {
} else {
imports["encoding/json"] = true
}
for _, str := range s.importTypes {
imports[str] = true
}
}

if len(imports) > 0 {
Expand Down Expand Up @@ -168,6 +171,8 @@ func Output(w io.Writer, g *Generator, pkg string, skipCode bool, esdoc bool) {
ftype := f.Type
if ftype == "int" {
ftype = "int64"
} else if ftype == "string" && f.Format == "date-time" {
ftype = "time.Time"
}
if f.Format == "raw" {
ftype = "json.RawMessage"
Expand Down Expand Up @@ -215,8 +220,8 @@ func (strct *%s) MarshalJSON() ([]byte, error) {

fmt.Fprintf(w,
` // Marshal the "%[1]s" field
if comma {
buf.WriteString(",")
if comma {
buf.WriteString(",")
}
buf.WriteString("\"%[1]s\": ")
if tmp, err := json.Marshal(strct.%[2]s); err != nil {
Expand Down
17 changes: 17 additions & 0 deletions test/calendar.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Calendar",
"description": "A calendar",
"type": "object",
"properties": {
"date": {
"description": "A date",
"type": "string",
"format": "date-time"
}
},
"required": [
"date"
]
}

23 changes: 23 additions & 0 deletions test/calendar_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package test

import (
"encoding/json"
"testing"
"time"

calendar "github.com/elastic/go-json-schema-generate/test/calendar_gen"
)

func TestCalendar(t *testing.T) {
data := []byte(`{
"date": "2022-01-02T12:00:00Z"
}`)
cal := &calendar.Calendar{}
if err := json.Unmarshal(data, &cal); err != nil {
t.Fatal(err)
}
ts := time.Date(2022, 1, 2, 12, 0, 0, 0, time.UTC)
if !cal.Date.Equal(ts) {
t.Errorf("expected date to be %v got %v", ts, cal.Date)
}
}