Skip to content

Instantly share code, notes, and snippets.

@M0nteCarl0
Created February 12, 2024 10:34
Show Gist options
  • Save M0nteCarl0/a923694388db27ca95b87914cecbc66e to your computer and use it in GitHub Desktop.
Save M0nteCarl0/a923694388db27ca95b87914cecbc66e to your computer and use it in GitHub Desktop.
GraphQL CRM base
package main
import (
"context"
"database/sql"
"log"
"net/http"
"github.com/graphql-go/graphql"
"github.com/graphql-go/handler"
_ "github.com/lib/pq"
)
type Customer struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
type Order struct {
ID int `json:"id"`
Customer Customer `json:"customer"`
Amount float64 `json:"amount"`
}
var (
customerType = graphql.NewObject(
graphql.ObjectConfig{
Name: "Customer",
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.Int},
"name": &graphql.Field{Type: graphql.String},
"email": &graphql.Field{Type: graphql.String},
},
},
)
orderType = graphql.NewObject(
graphql.ObjectConfig{
Name: "Order",
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.Int},
"customer": &graphql.Field{
Type: customerType,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
order := p.Source.(Order)
return order.Customer, nil
},
},
"amount": &graphql.Field{Type: graphql.Float},
},
},
)
rootQuery = graphql.NewObject(
graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"customers": &graphql.Field{
Type: graphql.NewList(customerType),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
db := p.Context.Value("db").(*sql.DB)
rows, err := db.Query("SELECT id, name, email FROM customers")
if err != nil {
return nil, err
}
defer rows.Close()
var customers []Customer
for rows.Next() {
var customer Customer
err := rows.Scan(&customer.ID, &customer.Name, &customer.Email)
if err != nil {
return nil, err
}
customers = append(customers, customer)
}
return customers, nil
},
},
"orders": &graphql.Field{
Type: graphql.NewList(orderType),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
db := p.Context.Value("db").(*sql.DB)
rows, err := db.Query("SELECT id, customer_id, amount FROM orders")
if err != nil {
return nil, err
}
defer rows.Close()
var orders []Order
for rows.Next() {
var order Order
err := rows.Scan(&order.ID, &order.Customer.ID, &order.Amount)
if err != nil {
return nil, err
}
orders = append(orders, order)
}
return orders, nil
},
},
},
},
)
schema, _ = graphql.NewSchema(
graphql.SchemaConfig{
Query: rootQuery,
},
)
)
func main() {
db, err := sql.Open("postgres", "postgres://user:password@localhost/crm")
if err != nil {
log.Fatal(err)
}
defer db.Close()
http.Handle("/graphql", &handler.Handler{
Schema: &schema,
Pretty: true,
GraphiQL: true,
ContextFunc: func(r *http.Request) context.Context {
ctx := context.WithValue(r.Context(), "db", db)
return ctx
},
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment