schema.go

 1package graphql
 2
 3import (
 4	"github.com/MichaelMure/git-bug/bug"
 5	"github.com/MichaelMure/git-bug/repository"
 6	"github.com/graphql-go/graphql"
 7)
 8
 9func graphqlSchema() (graphql.Schema, error) {
10	fields := graphql.Fields{
11		"bug": &graphql.Field{
12			Type: bugType,
13			Args: graphql.FieldConfigArgument{
14				"id": &graphql.ArgumentConfig{
15					Type: bugIdScalar,
16				},
17			},
18			Resolve: func(p graphql.ResolveParams) (interface{}, error) {
19				repo := p.Context.Value("repo").(repository.Repo)
20				id, _ := p.Args["id"].(string)
21				bug, err := bug.FindBug(repo, id)
22				if err != nil {
23					return nil, err
24				}
25
26				snapshot := bug.Compile()
27
28				return snapshot, nil
29			},
30		},
31		// TODO: provide a relay-like schema with pagination
32		"allBugs": &graphql.Field{
33			Type: graphql.NewList(bugType),
34			Resolve: func(p graphql.ResolveParams) (interface{}, error) {
35				repo := p.Context.Value("repo").(repository.Repo)
36				ids, err := repo.ListRefs(bug.BugsRefPattern)
37
38				if err != nil {
39					return nil, err
40				}
41
42				var snapshots []bug.Snapshot
43
44				for _, ref := range ids {
45					bug, err := bug.ReadBug(repo, bug.BugsRefPattern+ref)
46
47					if err != nil {
48						return nil, err
49					}
50
51					snapshots = append(snapshots, bug.Compile())
52				}
53
54				return snapshots, nil
55			},
56		},
57	}
58	rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: fields}
59	schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)}
60	return graphql.NewSchema(schemaConfig)
61}