Skip to content

Commit

Permalink
added example generation
Browse files Browse the repository at this point in the history
  • Loading branch information
matryer committed Aug 7, 2021
1 parent e54b746 commit 55c8963
Show file tree
Hide file tree
Showing 2 changed files with 117 additions and 0 deletions.
48 changes: 48 additions & 0 deletions parser/example.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package parser

import "encoding/json"

// Example generates an object that is a realistic example
// of this object.
// Examples are read from the docs.
// This is experimental.
func (d *Definition) Example(o Object) (map[string]interface{}, error) {
obj := make(map[string]interface{})
for _, field := range o.Fields {
if field.Type.IsObject {
subobj, err := d.Object(field.Type.TypeName)
if err != nil {
return nil, err
}
example, err := d.Example(*subobj)
if err != nil {
return nil, err
}
obj[field.Name] = example
if field.Type.Multiple {
// turn it into an array
obj[field.Name] = []interface{}{obj[field.Name]}
}
continue
}
obj[field.Name] = field.Example
if field.Type.Multiple {
// turn it into an array
obj[field.Name] = []interface{}{obj[field.Name], obj[field.Name], obj[field.Name]}
}
}
return obj, nil
}

// ExampleJSON is like Example, but returns a JSON string.
func (d *Definition) ExampleJSON(o Object) (string, error) {
example, err := d.Example(o)
if err != nil {
return "", err
}
exampleBytes, err := json.MarshalIndent(example, "", "\t")
if err != nil {
return "", err
}
return string(exampleBytes), nil
}
69 changes: 69 additions & 0 deletions parser/example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package parser

import (
"encoding/json"
"fmt"
"testing"

"github.com/matryer/is"
)

func TestObjectExample(t *testing.T) {
is := is.New(t)

obj1 := Object{
Name: "obj1",
Fields: []Field{
{
Name: "Name",
Example: "Mat",
},
{
Name: "Project",
Example: "Respond",
},
{
Name: "SinceYear",
Example: 2021,
},
{
Name: "Favourites",
Type: FieldType{
TypeName: "obj2",
IsObject: true,
},
},
},
}
obj2 := Object{
Name: "obj2",
Fields: []Field{
{
Type: FieldType{TypeName: "string", Multiple: true},
Name: "Languages",
Example: "Go",
},
},
}
def := &Definition{
Objects: []Object{obj1, obj2},
}
example, err := def.Example(obj1)
is.NoErr(err)
is.True(example != nil)

b, err := json.MarshalIndent(example, "", "\t")
is.NoErr(err)
fmt.Println(string(b))

is.Equal(example["Name"], "Mat")
is.Equal(example["Project"], "Respond")
is.Equal(example["SinceYear"], 2021)
is.True(example["Favourites"] != nil)
favourites, ok := example["Favourites"].(map[string]interface{})
is.True(ok) // Favourites map[string]interface{}
languages, ok := favourites["Languages"].([]interface{})
is.True(ok) // Languages []interface{}
is.Equal(len(languages), 3)

}

0 comments on commit 55c8963

Please sign in to comment.