-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
177 lines (143 loc) · 3.42 KB
/
main.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"github.com/calvinmclean/babyapi"
"github.com/calvinmclean/babyapi/examples/sql/db"
"github.com/rs/xid"
"github.com/spf13/cobra"
_ "embed"
_ "github.com/tursodatabase/go-libsql"
)
//go:embed schema.sql
var ddl string
type Author struct {
db.Author
}
func (a Author) GetID() string {
return fmt.Sprint(a.Author.ID)
}
func (a *Author) Bind(r *http.Request) error {
if r.Method == http.MethodPost {
a.ID = xid.New().String()
}
return nil
}
func (a Author) Render(w http.ResponseWriter, r *http.Request) error {
return nil
}
// Storage implements the babyapi.Storage interface with the sqlc-generated queries
type Storage struct {
dbMode string
*db.Queries
}
func (s Storage) Get(ctx context.Context, id string) (*Author, error) {
a, err := s.Queries.GetAuthor(ctx, id)
if err != nil {
return nil, err
}
return &Author{a}, nil
}
func (s Storage) GetAll(ctx context.Context, query url.Values) ([]*Author, error) {
var authors []db.Author
var err error
genre := query.Get("genre")
if genre != "" {
authors, err = s.Queries.SearchAuthors(ctx, genre)
} else {
authors, err = s.Queries.ListAuthors(ctx)
}
if err != nil {
return nil, err
}
var result []*Author
for _, a := range authors {
result = append(result, &Author{a})
}
return result, nil
}
func (s Storage) Set(ctx context.Context, a *Author) error {
return s.Queries.UpsertAuthor(ctx, db.UpsertAuthorParams{
ID: a.ID,
Name: a.Name,
Bio: a.Bio,
Genre: a.Genre,
})
}
func (s Storage) Delete(ctx context.Context, id string) error {
return s.Queries.DeleteAuthor(ctx, id)
}
func (s *Storage) Apply(api *babyapi.API[*Author]) error {
database, err := setupDatabaseConnection(s.dbMode)
if err != nil {
return err
}
go func() {
<-api.Done()
database.Close()
}()
// create tables
_, err = database.ExecContext(context.Background(), ddl)
if err != nil {
return fmt.Errorf("error creating table: %w", err)
}
s.Queries = db.New(database)
api.SetStorage(s)
return nil
}
func setupDatabaseConnection(dbMode string) (*sql.DB, error) {
var dbName string
switch dbMode {
case "memory":
dbName = ":memory:"
case "file":
dbName = os.Getenv("SQLITE_FILE")
if dbName == "" {
dbName = "local.db"
}
dbName = fmt.Sprintf("file:%s", dbName)
case "turso":
dbURL, ok := os.LookupEnv("TURSO_DATABASE_URL")
if !ok {
return nil, errors.New("missing TURSO_DATABASE_URL env var")
}
dbAuth, ok := os.LookupEnv("TURSO_AUTH_TOKEN")
if !ok {
return nil, errors.New("missing TURSO_DATABASE_URL env var")
}
dbName = fmt.Sprintf("%s?authToken=%s", dbURL, dbAuth)
default:
return nil, fmt.Errorf("invalid database option: %q", dbMode)
}
database, err := sql.Open("libsql", dbName)
if err != nil {
return nil, fmt.Errorf("error opening database: %w", err)
}
return database, nil
}
func main() {
api := babyapi.NewAPI(
"Authors", "/authors",
func() *Author { return &Author{} },
)
cmd := api.Command()
var dbMode string
cmd.PersistentFlags().StringVar(&dbMode, "db", "memory", "set database mode: memory, file, turos")
cmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
// Only setup DB for the serve command
if cmd.Name() != "serve" {
return nil
}
storage := &Storage{dbMode: dbMode}
return storage.Apply(api)
}
err := cmd.Execute()
if err != nil {
fmt.Printf("error: %v\n", err)
}
}