forked from buidl-labs/celo-voting-validator-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
116 lines (96 loc) · 2.37 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"context"
"log"
"net/http"
"os"
"github.com/99designs/gqlgen/graphql/handler"
"github.com/99designs/gqlgen/graphql/playground"
"github.com/buidl-labs/celo-voting-validator-backend/graph"
"github.com/buidl-labs/celo-voting-validator-backend/graph/database"
"github.com/buidl-labs/celo-voting-validator-backend/graph/generated"
"github.com/buidl-labs/celo-voting-validator-backend/graph/model"
"github.com/go-chi/chi"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
"github.com/joho/godotenv"
"github.com/rs/cors"
)
const defaultPort = "8080"
func main() {
if err := godotenv.Load(); err != nil {
log.Println(err)
}
port := os.Getenv("PORT")
if port == "" {
port = defaultPort
}
DB_URL := os.Getenv("DB_URL")
log.Println(DB_URL)
if DB_URL == "" {
log.Fatal("Please provide a DB url.")
}
opts, err := pg.ParseURL(DB_URL)
if err != nil {
log.Fatal(err)
}
DB := database.New(opts)
defer DB.Close()
// DB.AddQueryHook(pgdebug.DebugHook{
// Verbose: true,
// })
ctx := context.Background()
if err := DB.Ping(ctx); err != nil {
log.Println(err)
}
// DropAllTables(DB)
CreateAllTables(DB)
router := chi.NewRouter()
router.Use(cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowCredentials: true,
Debug: false,
}).Handler)
config := generated.Config{Resolvers: &graph.Resolver{
DB: DB,
}}
srv := handler.NewDefaultServer(generated.NewExecutableSchema(config))
router.Handle("/", playground.Handler("CVVT", "/query"))
router.Handle("/query", srv)
log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
log.Fatal(http.ListenAndServe(":"+port, router))
}
func DropAllTables(DB *pg.DB) {
qs := []string{
"drop table epochs",
"drop table validators",
"drop table validator_stats",
"drop table validator_groups",
"drop table validator_group_stats",
}
for _, q := range qs {
_, err := DB.Exec(q)
if err != nil {
panic(err)
}
}
}
func CreateAllTables(DB *pg.DB) {
models := []interface{}{
(*model.Epoch)(nil),
(*model.ValidatorGroup)(nil),
(*model.ValidatorGroupStats)(nil),
(*model.Validator)(nil),
(*model.ValidatorStats)(nil),
}
for _, model := range models {
err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
IfNotExists: true,
Temp: false,
FKConstraints: true,
})
if err != nil {
log.Print(err)
}
}
}