Skip to content

Instantly share code, notes, and snippets.

@Code-Hex
Last active March 4, 2021 01:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Code-Hex/5b39ae44b34c53c6c7ba45431cd90bdf to your computer and use it in GitHub Desktop.
Save Code-Hex/5b39ae44b34c53c6c7ba45431cd90bdf to your computer and use it in GitHub Desktop.
module github.com/Code-Hex/gql-filter
go 1.16
require (
github.com/graphql-go/graphql v0.7.9 // indirect
github.com/k0kubun/pp v3.0.1+incompatible // indirect
github.com/mattn/go-colorable v0.1.8 // indirect
)
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"github.com/graphql-go/graphql"
"github.com/k0kubun/pp"
)
func main() {
if err := run(context.Background()); err != nil {
fmt.Fprintf(os.Stderr, "err: %+v", err)
os.Exit(1)
}
}
const j = `{
"title": "example glossary"
}`
func run(ctx context.Context) error {
var a interface{}
if err := json.Unmarshal([]byte(j), &a); err != nil {
return err
}
pp.Println(a)
schemaConfig := graphql.SchemaConfig{
Query: graphql.NewObject(
graphql.ObjectConfig{
Name: "RootQuery",
Fields: traverse(a),
},
),
}
schema, err := graphql.NewSchema(schemaConfig)
if err != nil {
return err
}
query := `
{
title
}
`
params := graphql.Params{
Schema: schema,
RequestString: query,
}
r := graphql.Do(params)
if r.HasErrors() {
return fmt.Errorf("errors: %+v", r.Errors)
}
result, err := json.Marshal(r)
if err != nil {
return err
}
pp.Println(string(result))
return nil
}
func traverse(val interface{}) interface{} {
switch typ := val.(type) {
case map[string]interface{}:
fields := graphql.Fields{}
for k, v := range typ {
tt := traverse(v)
switch c := tt.(type) {
case *graphql.Field:
fields[k] = c
}
}
return fields
case string:
return &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return val, nil
},
}
case int:
return &graphql.Field{
Type: graphql.Int,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return val, nil
},
}
case float32, float64:
return &graphql.Field{
Type: graphql.Float,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return val, nil
},
}
}
return &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return val, nil
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment