Skip to content

Commit

Permalink
refactor: use 'any' instead of 'interface{}' for consistency (#3090)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandear committed May 23, 2024
1 parent d5c9f89 commit a9965fb
Show file tree
Hide file tree
Showing 126 changed files with 474 additions and 466 deletions.
8 changes: 8 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ linters-settings:
enable-all-rules: false
rules:
- name: empty-lines
- name: use-any
testifylint:
disable-all: true
enable:
Expand Down Expand Up @@ -52,3 +53,10 @@ issues:
linters:
- dupl
- errcheck
# Disable revive.use-any for backwards compatibility
- path: graphql/map.go
text: "use-any: since GO 1.18 'interface{}' can be replaced by 'any'"
- path: codegen/testserver/followschema/resolver.go
text: "use-any: since GO 1.18 'interface{}' can be replaced by 'any'"
- path: codegen/testserver/singlefile/resolver.go
text: "use-any: since GO 1.18 'interface{}' can be replaced by 'any'"
2 changes: 1 addition & 1 deletion _examples/chat/chat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func TestChatSubscriptions(t *testing.T) {
require.Equal(t, "system", msg.resp.MessageAdded.CreatedBy)

go func() {
var resp interface{}
var resp any
err := c.Post(fmt.Sprintf(`mutation {
a:post(text:"Hello!", roomName:"#gophers%d", username:"vektah") { id }
b:post(text:"Hello Vektah!", roomName:"#gophers%d", username:"andrey") { id }
Expand Down
4 changes: 2 additions & 2 deletions _examples/chat/resolvers.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func New() Config {
Rooms: sync.Map{},
},
Directives: DirectiveRoot{
User: func(ctx context.Context, obj interface{}, next graphql.Resolver, username string) (res interface{}, err error) {
User: func(ctx context.Context, obj any, next graphql.Resolver, username string) (res any, err error) {
return next(context.WithValue(ctx, ckey("username"), username))
},
},
Expand Down Expand Up @@ -73,7 +73,7 @@ func (r *mutationResolver) Post(ctx context.Context, text string, username strin
}

room.Messages = append(room.Messages, *message)
room.Observers.Range(func(_, v interface{}) bool {
room.Observers.Range(func(_, v any) bool {
observer := v.(*Observer)
if observer.Username == "" || observer.Username == message.CreatedBy {
observer.Message <- message
Expand Down
4 changes: 2 additions & 2 deletions _examples/dataloader/dataloader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func TestTodo(t *testing.T) {
c := client.New(LoaderMiddleware(handler.NewDefaultServer(NewExecutableSchema(Config{Resolvers: &Resolver{}}))))

t.Run("create a new todo", func(t *testing.T) {
var resp interface{}
var resp any
c.MustPost(`{
customers {
name
Expand Down Expand Up @@ -73,7 +73,7 @@ func TestTodo(t *testing.T) {

t.Run("introspection", func(t *testing.T) {
// Make sure we can run the graphiql introspection query without errors
var resp interface{}
var resp any
c.MustPost(introspection.Query, &resp)
})

Expand Down
6 changes: 3 additions & 3 deletions _examples/fileupload/fileupload_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func TestFileUpload(t *testing.T) {
SingleUploadWithPayload *model.File
}

err := gql.Post(mutation, &result, gqlclient.Var("req", map[string]interface{}{"id": 1, "file": aTxtFile}), gqlclient.WithFiles())
err := gql.Post(mutation, &result, gqlclient.Var("req", map[string]any{"id": 1, "file": aTxtFile}), gqlclient.WithFiles())
require.NoError(t, err)
require.Equal(t, 1, result.SingleUploadWithPayload.ID)
require.Contains(t, result.SingleUploadWithPayload.Name, "a.txt")
Expand Down Expand Up @@ -192,7 +192,7 @@ func TestFileUpload(t *testing.T) {
MultipleUploadWithPayload []*model.File
}

err := gql.Post(mutation, &result, gqlclient.Var("req", []map[string]interface{}{
err := gql.Post(mutation, &result, gqlclient.Var("req", []map[string]any{
{"id": 1, "file": a1TxtFile},
{"id": 2, "file": b1TxtFile},
}), gqlclient.WithFiles())
Expand Down Expand Up @@ -267,7 +267,7 @@ func TestFileUpload(t *testing.T) {
MultipleUploadWithPayload []*model.File
}

err := gql.Post(mutation, &result, gqlclient.Var("req", []map[string]interface{}{
err := gql.Post(mutation, &result, gqlclient.Var("req", []map[string]any{
{"id": 1, "file": a1TxtFile},
{"id": 2, "file": a1TxtFile},
}), gqlclient.WithFiles())
Expand Down
12 changes: 6 additions & 6 deletions _examples/scalars/model/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func (b Banned) MarshalGQL(w io.Writer) {
}
}

func (b *Banned) UnmarshalGQL(v interface{}) error {
func (b *Banned) UnmarshalGQL(v any) error {
switch v := v.(type) {
case string:
*b = strings.ToLower(v) == "true"
Expand Down Expand Up @@ -53,7 +53,7 @@ type Point struct {
Y int
}

func (p *Point) UnmarshalGQL(v interface{}) error {
func (p *Point) UnmarshalGQL(v any) error {
pointStr, ok := v.(string)
if !ok {
return fmt.Errorf("points must be strings")
Expand Down Expand Up @@ -90,7 +90,7 @@ func MarshalTimestamp(t time.Time) graphql.Marshaler {

// Unmarshal{Typename} is only required if the scalar appears as an input. The raw values have already been decoded
// from json into int/float64/bool/nil/map[string]interface/[]interface
func UnmarshalTimestamp(v interface{}) (time.Time, error) {
func UnmarshalTimestamp(v any) (time.Time, error) {
if tmpStr, ok := v.(int64); ok {
return time.Unix(tmpStr, 0), nil
}
Expand All @@ -105,7 +105,7 @@ func MarshalID(id external.ObjectID) graphql.Marshaler {
}

// And the same for the unmarshaler
func UnmarshalID(v interface{}) (external.ObjectID, error) {
func UnmarshalID(v any) (external.ObjectID, error) {
str, ok := v.(string)
if !ok {
return 0, fmt.Errorf("ids must be strings")
Expand Down Expand Up @@ -163,7 +163,7 @@ func (e Tier) String() string {
}
}

func (e *Tier) UnmarshalGQL(v interface{}) error {
func (e *Tier) UnmarshalGQL(v any) error {
str, ok := v.(string)
if !ok {
return fmt.Errorf("enums must be strings")
Expand All @@ -186,7 +186,7 @@ func MarshalPreferences(p *Prefs) graphql.Marshaler {
return graphql.MarshalBoolean(p.DarkMode)
}

func UnmarshalPreferences(v interface{}) (*Prefs, error) {
func UnmarshalPreferences(v any) (*Prefs, error) {
tmp, err := graphql.UnmarshalBoolean(v)
if err != nil {
return nil, err
Expand Down
2 changes: 1 addition & 1 deletion _examples/scalars/scalar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func TestScalars(t *testing.T) {

t.Run("introspection", func(t *testing.T) {
// Make sure we can run the graphiql introspection query without errors
var resp interface{}
var resp any
c.MustPost(introspection.Query, &resp)
})
}
2 changes: 1 addition & 1 deletion _examples/starwars/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (

func main() {
srv := handler.NewDefaultServer(generated.NewExecutableSchema(starwars.NewResolver()))
srv.AroundFields(func(ctx context.Context, next graphql.Resolver) (res interface{}, err error) {
srv.AroundFields(func(ctx context.Context, next graphql.Resolver) (res any, err error) {
rc := graphql.GetFieldContext(ctx)
fmt.Println("Entered", rc.Object, rc.Field.Name)
res, err = next(ctx)
Expand Down
2 changes: 1 addition & 1 deletion _examples/starwars/starwars_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ func TestStarwars(t *testing.T) {

t.Run("introspection", func(t *testing.T) {
// Make sure we can run the graphiql introspection query without errors
var resp interface{}
var resp any
c.MustPost(introspection.Query, &resp)
})

Expand Down
2 changes: 1 addition & 1 deletion _examples/todo/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (

func main() {
srv := handler.NewDefaultServer(todo.NewExecutableSchema(todo.New()))
srv.SetRecoverFunc(func(ctx context.Context, err interface{}) (userMessage error) {
srv.SetRecoverFunc(func(ctx context.Context, err any) (userMessage error) {
// send this panic somewhere
log.Print(err)
debug.PrintStack()
Expand Down
6 changes: 3 additions & 3 deletions _examples/todo/todo.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func New() Config {
lastID: 4,
},
}
c.Directives.HasRole = func(ctx context.Context, obj interface{}, next graphql.Resolver, role Role) (interface{}, error) {
c.Directives.HasRole = func(ctx context.Context, obj any, next graphql.Resolver, role Role) (any, error) {
switch role {
case RoleAdmin:
// No admin for you!
Expand All @@ -57,7 +57,7 @@ func New() Config {

return next(ctx)
}
c.Directives.User = func(ctx context.Context, obj interface{}, next graphql.Resolver, id int) (interface{}, error) {
c.Directives.User = func(ctx context.Context, obj any, next graphql.Resolver, id int) (any, error) {
return next(context.WithValue(ctx, ckey("userId"), id))
}
return c
Expand Down Expand Up @@ -124,7 +124,7 @@ func (r *MutationResolver) CreateTodo(ctx context.Context, todo TodoInput) (*Tod
return newTodo, nil
}

func (r *MutationResolver) UpdateTodo(ctx context.Context, id int, changes map[string]interface{}) (*Todo, error) {
func (r *MutationResolver) UpdateTodo(ctx context.Context, id int, changes map[string]any) (*Todo, error) {
var affectedTodo *Todo

for i := 0; i < len(r.todos); i++ {
Expand Down
12 changes: 6 additions & 6 deletions _examples/todo/todo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ func TestTodo(t *testing.T) {

t.Run("introspection", func(t *testing.T) {
// Make sure we can run the graphiql introspection query without errors
var resp interface{}
var resp any
c.MustPost(introspection.Query, &resp)
})

Expand All @@ -184,15 +184,15 @@ func TestSkipAndIncludeDirectives(t *testing.T) {
c := client.New(handler.NewDefaultServer(NewExecutableSchema(New())))

t.Run("skip on field", func(t *testing.T) {
var resp map[string]interface{}
var resp map[string]any
c.MustPost(`{ todo(id: 1) @skip(if:true) { __typename } }`, &resp)
_, ok := resp["todo"]
require.False(t, ok)
})

t.Run("skip on variable", func(t *testing.T) {
q := `query Test($cond: Boolean!) { todo(id: 1) @skip(if: $cond) { __typename } }`
var resp map[string]interface{}
var resp map[string]any

c.MustPost(q, &resp, client.Var("cond", true))
_, ok := resp["todo"]
Expand Down Expand Up @@ -239,7 +239,7 @@ func TestSkipAndIncludeDirectives(t *testing.T) {

t.Run("include on field", func(t *testing.T) {
q := `query Test($cond: Boolean!) { todo(id: 1) @include(if: $cond) { __typename } }`
var resp map[string]interface{}
var resp map[string]any

c.MustPost(q, &resp, client.Var("cond", true))
_, ok := resp["todo"]
Expand All @@ -264,15 +264,15 @@ func TestSkipAndIncludeDirectives(t *testing.T) {
}
q := `query Test($skip: Boolean!, $include: Boolean!) { todo(id: 1) @skip(if: $skip) @include(if: $include) { __typename } }`
for _, tc := range table {
var resp map[string]interface{}
var resp map[string]any
c.MustPost(q, &resp, client.Var("skip", tc.Skip), client.Var("include", tc.Include))
_, ok := resp["todo"]
require.Equal(t, tc.Expected, ok)
}
})

t.Run("skip with default query argument", func(t *testing.T) {
var resp map[string]interface{}
var resp map[string]any
c.MustPost(`query Test($skip: Boolean = true) { todo(id: 1) @skip(if: $skip) { __typename } }`, &resp)
_, ok := resp["todo"]
require.False(t, ok)
Expand Down
12 changes: 6 additions & 6 deletions _examples/type-system-extension/directive.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,37 +7,37 @@ import (
"github.com/99designs/gqlgen/graphql"
)

func EnumLogging(ctx context.Context, obj interface{}, next graphql.Resolver) (res interface{}, err error) {
func EnumLogging(ctx context.Context, obj any, next graphql.Resolver) (res any, err error) {
rc := graphql.GetFieldContext(ctx)
log.Printf("enum logging: %v, %s, %T, %+v", rc.Path(), rc.Field.Name, obj, obj)
return next(ctx)
}

func FieldLogging(ctx context.Context, obj interface{}, next graphql.Resolver) (res interface{}, err error) {
func FieldLogging(ctx context.Context, obj any, next graphql.Resolver) (res any, err error) {
rc := graphql.GetFieldContext(ctx)
log.Printf("field logging: %v, %s, %T, %+v", rc.Path(), rc.Field.Name, obj, obj)
return next(ctx)
}

func InputLogging(ctx context.Context, obj interface{}, next graphql.Resolver) (res interface{}, err error) {
func InputLogging(ctx context.Context, obj any, next graphql.Resolver) (res any, err error) {
rc := graphql.GetFieldContext(ctx)
log.Printf("input object logging: %v, %s, %T, %+v", rc.Path(), rc.Field.Name, obj, obj)
return next(ctx)
}

func ObjectLogging(ctx context.Context, obj interface{}, next graphql.Resolver) (res interface{}, err error) {
func ObjectLogging(ctx context.Context, obj any, next graphql.Resolver) (res any, err error) {
rc := graphql.GetFieldContext(ctx)
log.Printf("object logging: %v, %s, %T, %+v", rc.Path(), rc.Field.Name, obj, obj)
return next(ctx)
}

func ScalarLogging(ctx context.Context, obj interface{}, next graphql.Resolver) (res interface{}, err error) {
func ScalarLogging(ctx context.Context, obj any, next graphql.Resolver) (res any, err error) {
rc := graphql.GetFieldContext(ctx)
log.Printf("scalar logging: %v, %s, %T, %+v", rc.Path(), rc.Field.Name, obj, obj)
return next(ctx)
}

func UnionLogging(ctx context.Context, obj interface{}, next graphql.Resolver) (res interface{}, err error) {
func UnionLogging(ctx context.Context, obj any, next graphql.Resolver) (res any, err error) {
rc := graphql.GetFieldContext(ctx)
log.Printf("union logging: %v, %s, %T, %+v", rc.Path(), rc.Field.Name, obj, obj)
return next(ctx)
Expand Down
2 changes: 1 addition & 1 deletion api/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func Generate(cfg *config.Config, option ...Option) error {
}
}
// Merge again now that the generated models have been injected into the typemap
data_plugins := make([]interface{}, len(plugins))
data_plugins := make([]any, len(plugins))
for index := range plugins {
data_plugins[index] = plugins[index]
}
Expand Down
20 changes: 10 additions & 10 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,18 @@ type (

// Request represents an outgoing GraphQL request
Request struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
OperationName string `json:"operationName,omitempty"`
Extensions map[string]interface{} `json:"extensions,omitempty"`
HTTP *http.Request `json:"-"`
Query string `json:"query"`
Variables map[string]any `json:"variables,omitempty"`
OperationName string `json:"operationName,omitempty"`
Extensions map[string]any `json:"extensions,omitempty"`
HTTP *http.Request `json:"-"`
}

// Response is a GraphQL layer response from a handler.
Response struct {
Data interface{}
Data any
Errors json.RawMessage
Extensions map[string]interface{}
Extensions map[string]any
}
)

Expand All @@ -56,15 +56,15 @@ func New(h http.Handler, opts ...Option) *Client {
}

// MustPost is a convenience wrapper around Post that automatically panics on error
func (p *Client) MustPost(query string, response interface{}, options ...Option) {
func (p *Client) MustPost(query string, response any, options ...Option) {
if err := p.Post(query, response, options...); err != nil {
panic(err)
}
}

// Post sends a http POST request to the graphql endpoint with the given query then unpacks
// the response into the given object.
func (p *Client) Post(query string, response interface{}, options ...Option) error {
func (p *Client) Post(query string, response any, options ...Option) error {
respDataRaw, err := p.RawPost(query, options...)
if err != nil {
return err
Expand Down Expand Up @@ -146,7 +146,7 @@ func (p *Client) SetCustomDecodeConfig(dc *mapstructure.DecoderConfig) {
p.dc = dc
}

func unpack(data interface{}, into interface{}, customDc *mapstructure.DecoderConfig) error {
func unpack(data any, into any, customDc *mapstructure.DecoderConfig) error {
dc := &mapstructure.DecoderConfig{
TagName: "json",
ErrorUnused: true,
Expand Down
Loading

0 comments on commit a9965fb

Please sign in to comment.