Skip to content
This repository was archived by the owner on Sep 2, 2024. It is now read-only.

Commit 92bb5db

Browse files
committed
refactored all services in the backend package
1 parent 4fe5f2a commit 92bb5db

21 files changed

+189
-338
lines changed

account.go

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"strings"
77
"time"
88

9+
"github.com/staticbackendhq/core/backend"
910
"github.com/staticbackendhq/core/config"
1011
emailFuncs "github.com/staticbackendhq/core/email"
1112
"github.com/staticbackendhq/core/internal"
@@ -55,7 +56,7 @@ func (a *accounts) create(w http.ResponseWriter, r *http.Request) {
5556
return
5657
}
5758

58-
exists, err := datastore.EmailExists(email)
59+
exists, err := backend.DB.EmailExists(email)
5960
if err != nil {
6061
http.Error(w, err.Error(), http.StatusInternalServerError)
6162
return
@@ -111,7 +112,7 @@ func (a *accounts) create(w http.ResponseWriter, r *http.Request) {
111112
Created: time.Now(),
112113
}
113114

114-
cust, err = datastore.CreateCustomer(cust)
115+
cust, err = backend.DB.CreateCustomer(cust)
115116
if err != nil {
116117
http.Error(w, err.Error(), http.StatusInternalServerError)
117118
return
@@ -124,7 +125,7 @@ func (a *accounts) create(w http.ResponseWriter, r *http.Request) {
124125
dbName = "dev-memory-pk"
125126
}
126127
for {
127-
exists, err = datastore.DatabaseExists(dbName)
128+
exists, err = backend.DB.DatabaseExists(dbName)
128129
if err != nil {
129130
http.Error(w, err.Error(), http.StatusInternalServerError)
130131
return
@@ -144,7 +145,7 @@ func (a *accounts) create(w http.ResponseWriter, r *http.Request) {
144145
AllowedDomain: []string{"localhost"},
145146
}
146147

147-
bc, err := datastore.CreateBase(base)
148+
bc, err := backend.DB.CreateBase(base)
148149
if err != nil {
149150
http.Error(w, err.Error(), http.StatusInternalServerError)
150151
return
@@ -177,7 +178,7 @@ func (a *accounts) create(w http.ResponseWriter, r *http.Request) {
177178
signUpURL = s.URL
178179
}
179180

180-
token, err := datastore.FindTokenByEmail(dbName, email)
181+
token, err := backend.DB.FindTokenByEmail(dbName, email)
181182
if err != nil {
182183
http.Error(w, err.Error(), http.StatusInternalServerError)
183184
return
@@ -240,9 +241,9 @@ Refer to the documentation at https://staticbackend.com/docs\n
240241
// cache the root token so caller can always use
241242
// "safe-to-use-in-dev-root-token" as root token instead of
242243
// the changing one across CLI start/stop
243-
volatile.Set("dev-root-token", rootToken)
244+
backend.Cache.Set("dev-root-token", rootToken)
244245
} else {
245-
err = emailer.Send(ed)
246+
err = backend.Emailer.Send(ed)
246247
if err != nil {
247248
a.log.Error().Err(err).Msg("error sending email")
248249
http.Error(w, err.Error(), http.StatusInternalServerError)
@@ -292,7 +293,7 @@ func (a *accounts) portal(w http.ResponseWriter, r *http.Request) {
292293
}
293294

294295
func getStripePortalURL(customerID string) (string, error) {
295-
cus, err := datastore.FindAccount(customerID)
296+
cus, err := backend.DB.FindAccount(customerID)
296297
if err != nil {
297298
return "", err
298299
}

backend/backend.go

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,12 @@ import (
2727
)
2828

2929
type Backend struct {
30-
DB database.Persister
3130
User func(baseID string) User
3231
File func(model.Auth, model.BaseConfig) FileStore
3332
}
3433

3534
var (
36-
datastore database.Persister
35+
DB database.Persister
3736

3837
// Emailer sends email
3938
Emailer email.Mailer
@@ -63,20 +62,20 @@ func New(cfg config.AppConfig) Backend {
6362

6463
persister := config.Current.DataStore
6564
if strings.EqualFold(cfg.DatabaseURL, "mem") {
66-
datastore = memory.New(Cache.PublishDocument)
65+
DB = memory.New(Cache.PublishDocument)
6766
} else if strings.EqualFold(persister, "mongo") {
6867
cl, err := openMongoDatabase(cfg.DatabaseURL)
6968
if err != nil {
7069
Log.Fatal().Err(err).Msg("failed to create connection with mongodb")
7170
}
72-
datastore = mongo.New(cl, Cache.PublishDocument, Log)
71+
DB = mongo.New(cl, Cache.PublishDocument, Log)
7372
} else {
7473
cl, err := openPGDatabase(cfg.DatabaseURL)
7574
if err != nil {
7675
Log.Fatal().Err(err).Msg("failed to create connection with postgres")
7776
}
7877

79-
datastore = postgresql.New(cl, Cache.PublishDocument, "./sql/", Log)
78+
DB = postgresql.New(cl, Cache.PublishDocument, "./sql/", Log)
8079
}
8180

8281
mp := cfg.MailProvider
@@ -121,7 +120,7 @@ func New(cfg config.AppConfig) Backend {
121120

122121
exe.Auth = auth
123122
exe.BaseName = conf.Name
124-
exe.DataStore = datastore
123+
exe.DataStore = DB
125124
exe.Volatile = Cache
126125

127126
return exe, nil
@@ -131,7 +130,6 @@ func New(cfg config.AppConfig) Backend {
131130
go sub.Start()
132131

133132
return Backend{
134-
DB: datastore,
135133
User: newUser,
136134
File: newFile,
137135
}
@@ -169,11 +167,11 @@ func openPGDatabase(dbHost string) (*sql.DB, error) {
169167

170168
// NewID generates a new unique identifier
171169
func NewID() string {
172-
return datastore.NewID()
170+
return DB.NewID()
173171
}
174172

175173
func findAuth(token string) model.Auth {
176-
auth, err := middleware.ValidateAuthKey(datastore, Cache, context.Background(), token)
174+
auth, err := middleware.ValidateAuthKey(DB, Cache, context.Background(), token)
177175
if err != nil {
178176
return model.Auth{}
179177
}
@@ -183,7 +181,7 @@ func findAuth(token string) model.Auth {
183181
func findBase(baseID string) model.BaseConfig {
184182
var conf model.BaseConfig
185183
if err := Cache.GetTyped(baseID, &conf); err != nil {
186-
db, err := datastore.FindDatabase(baseID)
184+
db, err := DB.FindDatabase(baseID)
187185
if err != nil {
188186
return conf
189187
}

backend/backend_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ func createTenantAndDatabase() error {
5858
Created: time.Now(),
5959
}
6060

61-
cus, err := bkn.DB.CreateCustomer(cus)
61+
cus, err := backend.DB.CreateCustomer(cus)
6262
if err != nil {
6363
return err
6464
}
@@ -69,7 +69,7 @@ func createTenantAndDatabase() error {
6969
IsActive: true,
7070
}
7171

72-
base, err = bkn.DB.CreateBase(base)
72+
base, err = backend.DB.CreateBase(base)
7373
if err != nil {
7474
return err
7575
}

backend/database.go

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ func (d Database[T]) Create(col string, data T) (inserted T, err error) {
2828
return
2929
}
3030

31-
doc, err = datastore.CreateDocument(d.auth, d.conf.Name, col, doc)
31+
doc, err = DB.CreateDocument(d.auth, d.conf.Name, col, doc)
3232
if err != nil {
3333
return
3434
}
@@ -48,7 +48,7 @@ func (d Database[T]) BulkCreate(col string, entities []T) error {
4848

4949
docs = append(docs, x)
5050
}
51-
return datastore.BulkCreateDocument(d.auth, d.conf.Name, col, docs)
51+
return DB.BulkCreateDocument(d.auth, d.conf.Name, col, docs)
5252
}
5353

5454
// PageResult wraps a slice of type T with paging information
@@ -61,7 +61,7 @@ type PagedResult[T any] struct {
6161

6262
// List returns records from a collection/repository using paging/sorting params
6363
func (d Database[T]) List(col string, lp model.ListParams) (res PagedResult[T], err error) {
64-
r, err := datastore.ListDocuments(d.auth, d.conf.Name, col, lp)
64+
r, err := DB.ListDocuments(d.auth, d.conf.Name, col, lp)
6565
if err != nil {
6666
return
6767
}
@@ -84,12 +84,12 @@ func (d Database[T]) List(col string, lp model.ListParams) (res PagedResult[T],
8484

8585
// Query returns records that match with the provided filters.
8686
func (d Database[T]) Query(col string, filters [][]any, lp model.ListParams) (res PagedResult[T], err error) {
87-
clauses, err := datastore.ParseQuery(filters)
87+
clauses, err := DB.ParseQuery(filters)
8888
if err != nil {
8989
return
9090
}
9191

92-
r, err := datastore.QueryDocuments(d.auth, d.conf.Name, col, clauses, lp)
92+
r, err := DB.QueryDocuments(d.auth, d.conf.Name, col, clauses, lp)
9393
if err != nil {
9494
return
9595
}
@@ -112,7 +112,7 @@ func (d Database[T]) Query(col string, filters [][]any, lp model.ListParams) (re
112112

113113
// GetByID returns a specific record from a collection/repository
114114
func (d Database[T]) GetByID(col, id string) (entity T, err error) {
115-
doc, err := datastore.GetDocumentByID(d.auth, d.conf.Name, col, id)
115+
doc, err := DB.GetDocumentByID(d.auth, d.conf.Name, col, id)
116116
if err != nil {
117117
return
118118
}
@@ -128,7 +128,7 @@ func (d Database[T]) Update(col, id string, v any) (entity T, err error) {
128128
return
129129
}
130130

131-
x, err := datastore.UpdateDocument(d.auth, d.conf.Name, col, id, doc)
131+
x, err := DB.UpdateDocument(d.auth, d.conf.Name, col, id, doc)
132132
if err != nil {
133133
return
134134
}
@@ -139,7 +139,7 @@ func (d Database[T]) Update(col, id string, v any) (entity T, err error) {
139139

140140
// UpdateMany updates multiple records matching filters
141141
func (d Database[T]) UpdateMany(col string, filters [][]any, v any) (int64, error) {
142-
clauses, err := datastore.ParseQuery(filters)
142+
clauses, err := DB.ParseQuery(filters)
143143
if err != nil {
144144
return 0, err
145145
}
@@ -148,17 +148,17 @@ func (d Database[T]) UpdateMany(col string, filters [][]any, v any) (int64, erro
148148
if err != nil {
149149
return 0, err
150150
}
151-
return datastore.UpdateDocuments(d.auth, d.conf.Name, col, clauses, doc)
151+
return DB.UpdateDocuments(d.auth, d.conf.Name, col, clauses, doc)
152152
}
153153

154154
// IncrementValue increments or decrements a specifc field from a collection/repository
155155
func (d Database[T]) IncrementValue(col, id, field string, n int) error {
156-
return datastore.IncrementValue(d.auth, d.conf.Name, col, id, field, n)
156+
return DB.IncrementValue(d.auth, d.conf.Name, col, id, field, n)
157157
}
158158

159159
// Delete removes a record from a collection
160160
func (d Database[T]) Delete(col, id string) (int64, error) {
161-
return datastore.DeleteDocument(d.auth, d.conf.Name, col, id)
161+
return DB.DeleteDocument(d.auth, d.conf.Name, col, id)
162162
}
163163

164164
func toDoc(v any) (doc map[string]any, err error) {

backend/file.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ func (f FileStore) Save(filename, name string, file io.ReadSeeker, size int64) (
5656
Uploaded: time.Now(),
5757
}
5858

59-
newID, err := datastore.AddFile(f.conf.Name, sbFile)
59+
newID, err := DB.AddFile(f.conf.Name, sbFile)
6060
if err != nil {
6161
return
6262
}
@@ -68,7 +68,7 @@ func (f FileStore) Save(filename, name string, file io.ReadSeeker, size int64) (
6868
}
6969

7070
func (f FileStore) Delete(fileID string) error {
71-
file, err := datastore.GetFileByID(f.conf.Name, fileID)
71+
file, err := DB.GetFileByID(f.conf.Name, fileID)
7272
if err != nil {
7373
return err
7474
}
@@ -79,7 +79,7 @@ func (f FileStore) Delete(fileID string) error {
7979
return err
8080
}
8181

82-
if err := datastore.DeleteFile(f.conf.Name, file.ID); err != nil {
82+
if err := DB.DeleteFile(f.conf.Name, file.ID); err != nil {
8383
return err
8484
}
8585
return nil

backend/user.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,13 @@ func newUser(baseID string) User {
2424
// CreateAccount creates a new account in this database
2525
func (u User) CreateAccount(email string) (string, error) {
2626
email = strings.ToLower(email)
27-
if exists, err := datastore.UserEmailExists(u.conf.Name, email); err != nil {
27+
if exists, err := DB.UserEmailExists(u.conf.Name, email); err != nil {
2828
return "", err
2929
} else if exists {
3030
return "", errors.New("email not available")
3131
}
3232

33-
return datastore.CreateUserAccount(u.conf.Name, email)
33+
return DB.CreateUserAccount(u.conf.Name, email)
3434
}
3535

3636
// CreateUserToken creates a user token (login) for a specific account in a database
@@ -44,16 +44,16 @@ func (u User) CreateUserToken(accountID, email, password string, role int) (stri
4444
AccountID: accountID,
4545
Email: email,
4646
Password: string(b),
47-
Token: datastore.NewID(),
47+
Token: DB.NewID(),
4848
Role: role,
4949
Created: time.Now(),
5050
}
51-
return datastore.CreateUserToken(u.conf.Name, tok)
51+
return DB.CreateUserToken(u.conf.Name, tok)
5252
}
5353

5454
// Authenticate tries to authenticate an email/password and return a session token
5555
func (u User) Authenticate(email, password string) (string, error) {
56-
tok, err := datastore.FindTokenByEmail(u.conf.Name, email)
56+
tok, err := DB.FindTokenByEmail(u.conf.Name, email)
5757
if err != nil {
5858
return "", err
5959
}
@@ -91,7 +91,7 @@ func (u User) Authenticate(email, password string) (string, error) {
9191

9292
// SetPasswordResetCode sets the password forget code for a user
9393
func (u User) SetPasswordResetCode(tokenID, code string) error {
94-
return datastore.SetPasswordResetCode(u.conf.Name, tokenID, code)
94+
return DB.SetPasswordResetCode(u.conf.Name, tokenID, code)
9595
}
9696

9797
// ResetPassword resets the password of a matching email/code for a user
@@ -101,12 +101,12 @@ func (u User) ResetPassword(email, code, password string) error {
101101
return err
102102
}
103103

104-
return datastore.ResetPassword(u.conf.Name, email, code, string(b))
104+
return DB.ResetPassword(u.conf.Name, email, code, string(b))
105105
}
106106

107107
// SetUserRole changes the role of a user
108108
func (u User) SetUserRole(email string, role int) error {
109-
return datastore.SetUserRole(u.conf.Name, email, role)
109+
return DB.SetUserRole(u.conf.Name, email, role)
110110
}
111111

112112
// UserSetPassword password changes initiated by the user
@@ -116,7 +116,7 @@ func (u User) UserSetPassword(tokenID, password string) error {
116116
return err
117117
}
118118

119-
return datastore.UserSetPassword(u.conf.Name, tokenID, string(b))
119+
return DB.UserSetPassword(u.conf.Name, tokenID, string(b))
120120
}
121121

122122
func GetJWT(token string) ([]byte, error) {

0 commit comments

Comments
 (0)