playlyfe / go-graphql

A powerful GraphQL server implementation for Golang
248 stars 20 forks source link

Working with nested types #26

Closed unreadable closed 7 years ago

unreadable commented 7 years ago

I've been trying to figure it out for my own, but nothing seems to work since I can't find any documentation... I have the following code where I try to implement a nested type graphql. The schema is working fine, but it returns null..

package main

import ( 
    "net/http"
    "github.com/krypton97/HandleGraphQL"
    "github.com/playlyfe/go-graphql"
)

var Salutations = map[string]string{ 
    "ro": "Salut", 
    "en": "Hello", 
    "fr": "Oui", 
    "it": "Ciao", 
    "de": "Hallo", 
}

var Students = map[string]map[string]interface{}{
     "1": { "typename": "Student", "name": "alex", "age": 18, "id": "1", }, 
     "2": { "typename": "Student", "name": "bob", "age": 19, "id": "2", }, 
     "3": { "__typename": "Student", "name": "john", "age": 20, "id": "3", }, 
}

func main() {
schema := `
type StudentInfo {
    name: String
    age: Int
    id: String
}

type Student{
    student(id: String!) : StudentInfo
}

type QueryRoot {
    hello: String
    salutation(lang: String!): String
    students: Student

}
`

resolvers := map[string]interface{}{}

resolvers["QueryRoot/hello"] = func(params *graphql.ResolveParams) (interface{}, error) {
    return "world", nil
}

resolvers["QueryRoot/salutation"] = func(params *graphql.ResolveParams) (interface{}, error) {
    return Salutations[params.Args["lang"].(string)], nil
}

resolvers["QueryRoot/students"] = func(params *graphql.ResolveParams) (interface{}, error) {
    return Students, nil
}

resolvers["Student"] = func(params *graphql.ResolveParams) (interface{}, error) {
    return Students[params.Args["id"].(string)], nil
}

executor, err := graphql.NewExecutor(schema, "QueryRoot", "", resolvers)

if err != nil {
    panic(err)
}

api := handler.New(&handler.Config{
    Executor: executor,
    Context:  "",
    Pretty:   true,
})

http.Handle("/graphql", api)
http.ListenAndServe(":3000", nil)
}

Looking to get this working out, but can't find out anything. I'd really appreciate if you guys could help me out :)

unreadable commented 7 years ago

Had to make a resolver for every sub field, that's it

kumarharsh commented 7 years ago

Had to make a resolver for every sub field, that's it

@krypton97 that is the correct way to do it.