-
Notifications
You must be signed in to change notification settings - Fork 20
Open
Description
Was wondering if there is any appetite for enhancing the resolver api by enabling dynamic argument parsing for faster/safer coding.
Below is a rough (but working) example of how it could work...aided by some minimal external packages I quickly pulled together...
Any comments? Takers?
package main
import (
"errors"
"net/http"
handler "github.com/krypton97/HandleGraphQL"
router "github.com/luisjakon/playlyfe-router"
graphiql "github.com/luisjakon/graphiql"
graphql "github.com/playlyfe/go-graphql"
)
var (
Salutations = map[string]string{
"ro": "Salut",
"en": "Hello",
"fr": "Oui",
"it": "Ciao",
"de": "Hallo",
}
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 Student {
name: String
age: Int
}
type Query {
hello: String
salutation(lang: String!): String
student(id: String!): Student
}
`
router := router.NewRouter()
router.Register("Query/hello", QueryResolver.Hello)
router.Register("Query/salutation", QueryResolver.Salutation)
router.Register("Query/student", QueryResolver.StudentById)
router.Register("Student/age", StudentResolver.Age)
executor, err := graphql.NewExecutor(schema, "Query", "", router)
if err != nil {
panic(err)
}
api := handler.New(&handler.Config{
Executor: executor,
Context: "",
Pretty: true,
})
http.Handle("/graphql", graphiql.Handler(api))
http.ListenAndServe("localhost:3000", nil)
}resolvers.go
// Resolvers
var (
QueryResolver = queryRes{}
StudentResolver = studentRes{}
)
// Query Resolver
type queryRes struct{}
func (r queryRes) Hello(params *graphql.ResolveParams) (interface{}, error) {
return "world", nil
}
func (r queryRes) Salutation(params *graphql.ResolveParams, args struct { Lang string }) (interface{}, error) {
s := Salutations[args.Lang]
if s == "" {
return nil, errors.New("Unknown Language: " + args.Lang)
}
return s, nil
}
func (r queryRes) StudentById(params *graphql.ResolveParams, args struct { Id string }) (interface{}, error) {
return Students[args.Id], nil
}
// Student Resolver
type studentRes struct{}
func (r studentRes) Age(params *graphql.ResolveParams) (interface{}, error) {
if v, ok := params.Source.(int); ok {
return v, nil
}
source := params.Source.(map[string]interface{})
id := source["id"].(string)
return Students[id]["age"].(int), nil
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels