Files
codit/backend/internal/handlers/graphql.go
2026-02-05 03:03:16 +09:00

109 lines
2.9 KiB
Go

package handlers
import "encoding/json"
import "net/http"
import "codit/internal/db"
import "github.com/graphql-go/graphql"
type GraphQL struct {
Schema graphql.Schema
Store *db.Store
}
type graphQLRequest struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables"`
}
func NewGraphQL(store *db.Store) (*GraphQL, error) {
var userType *graphql.Object
userType = graphql.NewObject(graphql.ObjectConfig{
Name: "User",
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.String},
"username": &graphql.Field{Type: graphql.String},
"display_name": &graphql.Field{Type: graphql.String},
"email": &graphql.Field{Type: graphql.String},
"is_admin": &graphql.Field{Type: graphql.Boolean},
},
})
var projectType *graphql.Object
projectType = graphql.NewObject(graphql.ObjectConfig{
Name: "Project",
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.String},
"slug": &graphql.Field{Type: graphql.String},
"name": &graphql.Field{Type: graphql.String},
"description": &graphql.Field{Type: graphql.String},
},
})
var repoType *graphql.Object
repoType = graphql.NewObject(graphql.ObjectConfig{
Name: "Repo",
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.String},
"project_id": &graphql.Field{Type: graphql.String},
"name": &graphql.Field{Type: graphql.String},
},
})
var rootQuery *graphql.Object
rootQuery = graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"users": &graphql.Field{
Type: graphql.NewList(userType),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return store.ListUsers()
},
},
"projects": &graphql.Field{
Type: graphql.NewList(projectType),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return store.ListProjects()
},
},
"repos": &graphql.Field{
Type: graphql.NewList(repoType),
Args: graphql.FieldConfigArgument{
"project_id": &graphql.ArgumentConfig{Type: graphql.NewNonNull(graphql.String)},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var projectID string
var ok bool
projectID, ok = p.Args["project_id"].(string)
if !ok {
return store.ListRepos("")
}
return store.ListRepos(projectID)
},
},
},
})
var schema graphql.Schema
var err error
schema, err = graphql.NewSchema(graphql.SchemaConfig{Query: rootQuery})
if err != nil {
return nil, err
}
return &GraphQL{Schema: schema, Store: store}, nil
}
func (g *GraphQL) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var req graphQLRequest
var err error
err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
WriteJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
return
}
var result *graphql.Result
result = graphql.Do(graphql.Params{Schema: g.Schema, RequestString: req.Query, VariableValues: req.Variables})
WriteJSON(w, http.StatusOK, result)
}