2
votes

Basically what im trying to do is send a list of string ex: ["aa","bb","vv"] into a graphql Mutation field, currently this is my Mutation Schema

"listTest": &graphql.Field{
            Type: QueryMessageType,
            Args: graphql.FieldConfigArgument{
                "listNew": &graphql.ArgumentConfig{
                    Description: "Example List of Json String",
                    Type:        graphql.NewList(graphql.NewNonNull(graphql.String)),
                },
            },
            Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                list := p.Args["listTest"].([]string)
                return listTest(list)
            },
        },

and the Method listTest

func listTest(testing[]string) (*QueryMessage, error) {
    fmt.Println(testing)
    return &QueryMessage{
        QueryBody: "nothing to do here",
    }, nil
}

However when i do the request in INSOMNIA the response is:

{
    "data": {
        "listTest": null
    },
    "errors": [
        {
            "message": "interface conversion: interface {} is []interface {}, not []string",
            "locations": []
        }
    ]
}

and the request is this:

mutation{
    listTest(listNew: ["aa","bb","vv"]){
        querybody
    }
}

can anyone tell me how to receive a List of String in my Go Server. Thanks! :)

UPDATE When i call a fmt.Println(p.Args["listTest"])

the result is: [aa bb vv]

SOLVED

Following the instructions of the voted answer, the script now do his job. This is the final result:

Resolve: func(p graphql.ResolveParams) (interface{}, error) {
                var groupIDs []string
                for _, gid := range p.Args["list"].([]interface{}) {
                    groupIDs = append(groupIDs, gid.(string))
                }

                for _, final := range groupIDs {
                    fmt.Println(final)
                }
                return listTest(groupIDs)
            },

and in the console i got this:

aa
bb
vv
1

1 Answers

3
votes

Your problem, according to the error message, is with this line:

 list := p.Args["listTest"].([]string)

p.Args["listTest"] is returning []interface{}.

interface{} can store any other type. If you are familiar with java it's a little bit like Object.

The problem here is that you have your field from p.Args["listTest"] and you are trying to type assert it to []string. This would work if the value stored in args were interface{} (any). But it's not, p.Args (according to the error) holds []interface{}. This is a slice of interface values, where each of those can be anything (rather than a single interface value holding a slice of strings.)

Instead try ranging over that list of interfaces, and type asserting each value.

var strs []string
for _, v := range p.Args["list"].([]interface{}) {
    strs = append(strs, v.(string))
}

Or investigate another way to set up the graphQL types so that you get the values back in a more useable way.