graphql-go / graphql

An implementation of GraphQL for Go / Golang
MIT License
9.86k stars 838 forks source link

returning a map from resolver of list #609

Open AndrewWPhillips opened 3 years ago

AndrewWPhillips commented 3 years ago

I get an error "User Error: expected iterable, but did not find one for field ..." if I return a map from the resolver. A slice works fine. Why is a map not iterable? Is there a way to do this.? I need a map for efficiency of lookup. I know I can use a slice and create my own index but it would be simpler and less error-prone if the graphql package could iterate a map.

(Sorry if this has been asked before but I have searched for a long time and found nothing)

racesQuery = Field{
    Type: NewList(raceType),
    Resolve: func(params ResolveParams) (interface{}, error) {
        return races, nil  // error if races is a map, no error if races is a slice
    },
}
bhoriuchi commented 3 years ago

if you want to return a map you need to just put the type not a list of the type.

AndrewWPhillips commented 3 years ago

Thanks for your reply. Sorry that I did not explain this properly. I don't want to return a single map - I want the resolver to return a list composed of the elements of the map. I created a workaround using a slice of pointers to my map elements but this is ugly and inefficient.

It seems to me that it is just as easy to iterate a map as a slice when a resolver returns a list. But if there is a technical reason for it then no worries - I don't need this now as I have created my own (simple) gql handler.

AndrewWPhillips commented 2 years ago

I tried to modify the code to allow this but had trouble doing that so I decided to write my own GraphQL package - see https://github.com/AndrewWPhillips/eggql. If you supply a map (or slice/array) as a "resolver" it automatically returns a JSON list. Moreover, you have the option of the map key being added as the "ID" field (if the key is an int or string).