Skip to content

Instantly share code, notes, and snippets.

@batwicket
Created March 20, 2016 13:56
Show Gist options
  • Save batwicket/37f913624e31aed25aad to your computer and use it in GitHub Desktop.
Save batwicket/37f913624e31aed25aad to your computer and use it in GitHub Desktop.
simple example showing multi-parameter graphql-go mutation
package main
import (
"encoding/json"
"fmt"
"math/rand"
"net/http"
"github.com/astaxie/beego"
"github.com/graphql-go/graphql"
)
// User is used to encode user fields into JSON for transfer via HTTP
type User struct {
ID string `json:"id"`
Username string `json:"username"`
Gender string `json:"gender"`
Age int `json:"age"`
}
func init() {
}
var userType = graphql.NewObject(graphql.ObjectConfig{
Name: "User",
Fields: graphql.Fields{
"id": &graphql.Field{
Type: graphql.String,
},
"username": &graphql.Field{
Type: graphql.String,
},
"gender": &graphql.Field{
Type: graphql.String,
},
"age": &graphql.Field{
Type: graphql.Int,
},
},
})
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
// RandStringRunes ...
func RandStringRunes(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
// root mutation
var rootMutation = graphql.NewObject(graphql.ObjectConfig{
Name: "RootMutation",
Fields: graphql.Fields{
/*
curl -g 'http://localhost:8080/graphql?query=mutation+_{createUser(text:"My+new+user"){id,text,done}}'
*/
"createUser": &graphql.Field{
Type: userType, // the return type for this field
Args: graphql.FieldConfigArgument{
"username": &graphql.ArgumentConfig{
Type: graphql.NewNonNull(graphql.String),
},
"gender": &graphql.ArgumentConfig{
Type: graphql.NewNonNull(graphql.String),
},
"age": &graphql.ArgumentConfig{
Type: graphql.NewNonNull(graphql.Int),
},
},
Resolve: func(params graphql.ResolveParams) (interface{}, error) {
newID := RandStringRunes(8)
username, isOK := params.Args["username"].(string)
if !isOK {
beego.Error("username missing")
}
gender, isOK := params.Args["gender"].(string)
if !isOK {
beego.Error("gender missing")
}
age, isOK := params.Args["age"].(int)
if !isOK {
beego.Error("age missing")
}
newUser := User{
ID: newID,
Username: username,
Gender: gender,
Age: age,
}
return newUser, nil
},
},
},
})
// root query
// we just define a trivial example here, since root query is required.
// Test with curl
// curl -g 'http://localhost:8080/graphql?query={lastUser{id,text,done}}'
var rootQuery = graphql.NewObject(graphql.ObjectConfig{
Name: "RootQuery",
Fields: graphql.Fields{
/*
curl -g 'http://localhost:8080/graphql?query={user(id:"b"){id,text,done}}'
*/
"user": &graphql.Field{
Type: userType,
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{
Type: graphql.String,
},
"username": &graphql.ArgumentConfig{
Type: graphql.String,
},
"gender": &graphql.ArgumentConfig{
Type: graphql.String,
},
"age": &graphql.ArgumentConfig{
Type: graphql.String,
},
},
Resolve: func(params graphql.ResolveParams) (interface{}, error) {
idQuery, isOK := params.Args["id"].(string)
if !isOK {
beego.Error("no id")
}
usernameQuery, isOK := params.Args["username"].(string)
if !isOK {
beego.Error("no id")
}
genderQuery, isOK := params.Args["gender"].(string)
if !isOK {
beego.Error("no gender")
}
ageQuery, isOK := params.Args["age"].(int)
if !isOK {
beego.Error("no age")
}
return User{ID: idQuery, Username: usernameQuery, Gender: genderQuery, Age: ageQuery}, nil
},
},
},
})
// define schema, with our rootQuery and rootMutation
var schema, _ = graphql.NewSchema(graphql.SchemaConfig{
Query: rootQuery,
Mutation: rootMutation,
})
func executeQuery(query string, schema graphql.Schema) *graphql.Result {
fmt.Println("query: '", query, "'")
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: query,
})
if len(result.Errors) > 0 {
fmt.Printf("wrong result, unexpected errors: %v", result.Errors)
}
return result
}
func main() {
http.HandleFunc("/graphql", func(w http.ResponseWriter, r *http.Request) {
result := executeQuery(r.URL.Query()["query"][0], schema)
json.NewEncoder(w).Encode(result)
})
fmt.Println("Now server is running on port 8080")
fmt.Println("Get single user: curl -g 'http://localhost:8080/graphql?query={user(id:\"b\"){id,username,gender}}'")
fmt.Println("Create new user: curl -g 'http://localhost:8080/graphql?query=mutation+_{createUser(username:\"My+new+user\",gender:\"male\",age:12){id,username,gender,age}}'")
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment