Skip to content

Commit

Permalink
add default args
Browse files Browse the repository at this point in the history
  • Loading branch information
vektah committed Feb 25, 2018
1 parent d63128f commit 68c54a1
Show file tree
Hide file tree
Showing 13 changed files with 136 additions and 16 deletions.
5 changes: 3 additions & 2 deletions codegen/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ type Field struct {
type FieldArgument struct {
*Type

GQLName string // The name of the argument in graphql
Object *Object // A link back to the parent object
GQLName string // The name of the argument in graphql
Object *Object // A link back to the parent object
Default interface{} // The default value
}

type Objects []*Object
Expand Down
10 changes: 8 additions & 2 deletions codegen/object_build.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,17 @@ func buildObject(types NamedTypes, typ *schema.Object) *Object {
for _, field := range typ.Fields {
var args []FieldArgument
for _, arg := range field.Args {
args = append(args, FieldArgument{
newArg := FieldArgument{
GQLName: arg.Name.Name,
Type: types.getType(arg.Type),
Object: obj,
})
}

if arg.Default != nil {
newArg.Default = arg.Default.Value(nil)
newArg.StripPtr()
}
args = append(args, newArg)
}

obj.Fields = append(obj.Fields, Field{
Expand Down
13 changes: 13 additions & 0 deletions codegen/templates/args.gotpl
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,18 @@
return graphql.Null
{{- end }}
}
} {{ if $arg.Default }} else {
tmp := {{ $arg.Default | dump }}
var err error
{{$arg.Unmarshal (print "arg" $i) "tmp" }}
if err != nil {
ec.Error(err)
{{- if $arg.Object.Stream }}
return nil
{{- else }}
return graphql.Null
{{- end }}
}
}
{{end }}
{{- end -}}
2 changes: 1 addition & 1 deletion codegen/templates/data.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 36 additions & 0 deletions codegen/templates/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ package templates

import (
"bytes"
"fmt"
"strconv"
"strings"
"text/template"
"unicode"

Expand All @@ -16,6 +18,7 @@ func Run(e *codegen.Build) (*bytes.Buffer, error) {
"ucFirst": ucFirst,
"lcFirst": lcFirst,
"quote": strconv.Quote,
"dump": dump,
})

for filename, data := range data {
Expand Down Expand Up @@ -52,3 +55,36 @@ func lcFirst(s string) string {
r[0] = unicode.ToLower(r[0])
return string(r)
}

func dump(val interface{}) string {
switch val := val.(type) {
case int:
return strconv.Itoa(val)
case float64:
return fmt.Sprintf("%f", val)
case string:
return strconv.Quote(val)
case bool:
return strconv.FormatBool(val)
case nil:
return "nil"
case []interface{}:
var parts []string
for _, part := range val {
parts = append(parts, dump(part))
}
return "[]interface{}{" + strings.Join(parts, ",") + "}"
case map[string]interface{}:
buf := bytes.Buffer{}
buf.WriteString("map[string]interface{}{")
for key, data := range val {
buf.WriteString(strconv.Quote(key))
buf.WriteString(":")
buf.WriteString(dump(data))
}
buf.WriteString("}")
return buf.String()
default:
panic(fmt.Errorf("unsupported type %T", val))
}
}
7 changes: 7 additions & 0 deletions codegen/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,13 @@ func (t Type) IsPtr() bool {
return len(t.Modifiers) > 0 && t.Modifiers[0] == modPtr
}

func (t *Type) StripPtr() {
if !t.IsPtr() {
return
}
t.Modifiers = t.Modifiers[0 : len(t.Modifiers)-1]
}

func (t Type) IsSlice() bool {
return len(t.Modifiers) > 0 && t.Modifiers[0] == modList
}
Expand Down
4 changes: 2 additions & 2 deletions codegen/type_build.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,8 @@ func (n NamedTypes) getType(t common.Type) *Type {
Modifiers: modifiers,
}

if t.IsInterface && t.Modifiers[len(t.Modifiers)-1] == modPtr {
t.Modifiers = t.Modifiers[0 : len(t.Modifiers)-1]
if t.IsInterface {
t.StripPtr()
}

return t
Expand Down
12 changes: 11 additions & 1 deletion example/scalars/generated.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,22 @@ func (ec *executionContext) _Query_search(field graphql.CollectedField) graphql.
if tmp, ok := field.Args["input"]; ok {
var err error

arg0, err = UnmarshalSearchArgs(tmp)
if err != nil {
ec.Error(err)
return graphql.Null
}
} else {
tmp := map[string]interface{}{"location": "37,144"}
var err error

arg0, err = UnmarshalSearchArgs(tmp)
if err != nil {
ec.Error(err)
return graphql.Null
}
}

return graphql.Defer(func() graphql.Marshaler {
res, err := ec.resolvers.Query_search(ec.ctx, arg0)
if err != nil {
Expand Down Expand Up @@ -751,7 +761,7 @@ func UnmarshalSearchArgs(v interface{}) (SearchArgs, error) {
return it, nil
}

var parsedSchema = schema.MustParse("schema {\n query: Query\n}\n\ntype Query {\n user(id: ID!): User\n search(input: SearchArgs!): [User!]!\n}\n\ntype User {\n id: ID!\n name: String!\n created: Timestamp\n location: Point\n isBanned: Boolean!\n}\n\ninput SearchArgs {\n location: Point\n createdAfter: Timestamp\n isBanned: Boolean\n}\n\nscalar Timestamp\nscalar Point\n")
var parsedSchema = schema.MustParse("schema {\n query: Query\n}\n\ntype Query {\n user(id: ID!): User\n search(input: SearchArgs = {location: \"37,144\"}): [User!]!\n}\n\ntype User {\n id: ID!\n name: String!\n created: Timestamp\n location: Point\n isBanned: Boolean!\n}\n\ninput SearchArgs {\n location: Point\n createdAfter: Timestamp\n isBanned: Boolean\n}\n\nscalar Timestamp\nscalar Point\n")

func (ec *executionContext) introspectSchema() *introspection.Schema {
return introspection.WrapSchema(parsedSchema)
Expand Down
8 changes: 8 additions & 0 deletions example/scalars/scalar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ func TestScalars(t *testing.T) {
require.Equal(t, int64(666), resp.Search[0].Created)
})

t.Run("default search location", func(t *testing.T) {
var resp struct{ Search []RawUser }

err := c.Post(`{ search { location } }`, &resp)
require.NoError(t, err)
require.Equal(t, "37,144", resp.Search[0].Location)
})

t.Run("test custom error messages", func(t *testing.T) {
var resp struct{ Search []RawUser }

Expand Down
2 changes: 1 addition & 1 deletion example/scalars/schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ schema {

type Query {
user(id: ID!): User
search(input: SearchArgs!): [User!]!
search(input: SearchArgs = {location: "37,144"}): [User!]!
}

type User {
Expand Down
38 changes: 33 additions & 5 deletions example/starwars/generated.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ type Resolvers interface {
Human_starships(ctx context.Context, obj *Human) ([]Starship, error)
Mutation_createReview(ctx context.Context, episode string, review Review) (*Review, error)

Query_hero(ctx context.Context, episode *string) (Character, error)
Query_hero(ctx context.Context, episode string) (Character, error)
Query_reviews(ctx context.Context, episode string, since *time.Time) ([]Review, error)
Query_search(ctx context.Context, text string) ([]SearchResult, error)
Query_character(ctx context.Context, id string) (Character, error)
Expand Down Expand Up @@ -347,12 +347,22 @@ func (ec *executionContext) _Human_height(field graphql.CollectedField, obj *Hum
if tmp, ok := field.Args["unit"]; ok {
var err error

arg0, err = graphql.UnmarshalString(tmp)
if err != nil {
ec.Error(err)
return graphql.Null
}
} else {
tmp := "METER"
var err error

arg0, err = graphql.UnmarshalString(tmp)
if err != nil {
ec.Error(err)
return graphql.Null
}
}

res := obj.Height(arg0)
return graphql.MarshalFloat(res)
}
Expand Down Expand Up @@ -570,18 +580,26 @@ func (ec *executionContext) _Query(sel []query.Selection) graphql.Marshaler {
}

func (ec *executionContext) _Query_hero(field graphql.CollectedField) graphql.Marshaler {
var arg0 *string
var arg0 string
if tmp, ok := field.Args["episode"]; ok {
var err error
var ptr1 string

ptr1, err = graphql.UnmarshalString(tmp)
arg0 = &ptr1
arg0, err = graphql.UnmarshalString(tmp)
if err != nil {
ec.Error(err)
return graphql.Null
}
} else {
tmp := "NEWHOPE"
var err error

arg0, err = graphql.UnmarshalString(tmp)
if err != nil {
ec.Error(err)
return graphql.Null
}
}

return graphql.Defer(func() graphql.Marshaler {
res, err := ec.resolvers.Query_hero(ec.ctx, arg0)
if err != nil {
Expand Down Expand Up @@ -860,12 +878,22 @@ func (ec *executionContext) _Starship_length(field graphql.CollectedField, obj *
if tmp, ok := field.Args["unit"]; ok {
var err error

arg0, err = graphql.UnmarshalString(tmp)
if err != nil {
ec.Error(err)
return graphql.Null
}
} else {
tmp := "METER"
var err error

arg0, err = graphql.UnmarshalString(tmp)
if err != nil {
ec.Error(err)
return graphql.Null
}
}

res := obj.Length(arg0)
return graphql.MarshalFloat(res)
}
Expand Down
4 changes: 2 additions & 2 deletions example/starwars/resolvers.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ func (r *Resolver) Mutation_createReview(ctx context.Context, episode string, re
return &review, nil
}

func (r *Resolver) Query_hero(ctx context.Context, episode *string) (Character, error) {
if episode != nil && *episode == "EMPIRE" {
func (r *Resolver) Query_hero(ctx context.Context, episode string) (Character, error) {
if episode == "EMPIRE" {
return r.humans["1000"], nil
}
return r.droid["2001"], nil
Expand Down
11 changes: 11 additions & 0 deletions example/starwars/starwars_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,17 @@ func TestStarwars(t *testing.T) {
require.Equal(t, 1.72, resp.Hero.Height)
})

t.Run("default hero episode", func(t *testing.T) {
var resp struct {
Hero struct {
Name string
}
}
c.MustPost(`{ hero { ... on Droid { name } } }`, &resp)

require.Equal(t, "R2-D2", resp.Hero.Name)
})

t.Run("friends", func(t *testing.T) {
var resp struct {
Human struct {
Expand Down

0 comments on commit 68c54a1

Please sign in to comment.