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

Commit b1d614f

Browse files
committed
improved go doc on all packages
1 parent c9b1b75 commit b1d614f

File tree

13 files changed

+177
-50
lines changed

13 files changed

+177
-50
lines changed

README.md

Lines changed: 85 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,15 +39,99 @@ vendor lock-in, and your data stays in your control.
3939

4040
## Import as Go package
4141

42-
As of v1.4.1 StaticBackend offer an importable Go package removing the need
42+
As of v1.4.1 StaticBackend offers an importable Go package removing the need
4343
to self-host the backend API while keeping all functionalities from your Go
4444
program.
4545

4646
### Example usage
4747

4848
```go
49+
package main
50+
51+
import (
52+
"fmt"
53+
"log"
54+
"time"
55+
56+
"github.com/staticbackendhq/core/backend"
57+
"github.com/staticbackendhq/core/config"
58+
"github.com/staticbackendhq/core/model"
59+
)
60+
61+
type Task struct {
62+
ID string `json:"id"`
63+
AccountID string `json:"accountId"`
64+
Title string `json:"title"`
65+
Done bool `json:"done"`
66+
}
67+
68+
func main() {
69+
cfg := config.AppConfig{
70+
AppEnv: "dev",
71+
Port: "8099",
72+
DatabaseURL: "mem",
73+
DataStore: "mem",
74+
LocalStorageURL: "http://localhost:8099",
75+
}
76+
// this initialized the backend from config
77+
backend.Setup(cfg)
78+
79+
// You can access most of the raw building blocks directly from the
80+
// package exported variables (which are interface) initialized via the
81+
// config you pass
82+
83+
// Set a value in the cache
84+
backend.Cache.Set("key", "value")
85+
86+
// For strongly-typed database functionalities
87+
88+
// in a real app you'd have a middleware handling identifying and fetching a
89+
// model.DatabaseConfig for the current request. For this README sample
90+
// we're faking a real call which would fail if ran.
91+
base, _ := backend.DB.FindDatabase("current-web-request-db-id")
92+
93+
// let's create a user in this new Database
94+
usr := backend.Membership(base)
95+
sessionToken, user, err := usr.CreateAccountAndUser("[email protected]", "passwd123456", 100)
96+
if err != nil {
97+
log.Fatal(err)
98+
}
99+
100+
// we simulate having authenticating this user (from middleware normally)
101+
// in a real app you'd store the sessionToken in your user's
102+
// app (cookie, local storage, etc)
103+
// You'd need to have a middleware responsible of validating this token
104+
// and have a model.Auth for the rest of your pipeline.
105+
auth := model.Auth{
106+
AccountID: user.AccountID,
107+
UserID: user.ID,
108+
Email: user.Email,
109+
Role: user.Role,
110+
Token: user.Token,
111+
}
49112

113+
// we create a strongly-typed instance of the "tasks" collection
114+
// so we have full CRUD / Queries functions for your Task type
115+
tasks := backend.Collection[Task](auth, base, "tasks")
116+
117+
newTask := Task{Title: "my task", Done: false}
118+
119+
newTask, err = tasks.Create(newTask)
120+
if err != nil {
121+
log.Fatal(err)
122+
}
123+
}
50124
```
125+
126+
### Documentation for the `backend` Go package
127+
128+
Refer to the
129+
[Go documentation](https://pkg.go.dev/github.com/staticbackendhq/core/backend)
130+
to know about all functions and examples.
131+
132+
133+
134+
51135
## What can you build
52136

53137
I built StaticBackend with the mindset of someone tired of writing the same code

backend/backend.go

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,6 @@ import (
5656
"github.com/staticbackendhq/core/email"
5757
"github.com/staticbackendhq/core/function"
5858
"github.com/staticbackendhq/core/logger"
59-
"github.com/staticbackendhq/core/middleware"
6059
"github.com/staticbackendhq/core/model"
6160
"github.com/staticbackendhq/core/storage"
6261
mongodrv "go.mongodb.org/mongo-driver/mongo"
@@ -208,23 +207,3 @@ func openPGDatabase(dbHost string) (*sql.DB, error) {
208207

209208
return dbConn, nil
210209
}
211-
212-
func findAuthz(token string) model.Auth {
213-
auth, err := middleware.ValidateAuthKey(DB, Cache, context.Background(), token)
214-
if err != nil {
215-
return model.Auth{}
216-
}
217-
return auth
218-
}
219-
220-
func findBasez(baseID string) model.DatabaseConfig {
221-
var conf model.DatabaseConfig
222-
if err := Cache.GetTyped(baseID, &conf); err != nil {
223-
db, err := DB.FindDatabase(baseID)
224-
if err != nil {
225-
return conf
226-
}
227-
conf = db
228-
}
229-
return conf
230-
}

backend/database.go

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -11,24 +11,26 @@ import (
1111
type Database[T any] struct {
1212
auth model.Auth
1313
conf model.DatabaseConfig
14+
col string
1415
}
1516

1617
// Collection returns a ready to use Database to perform operations on a specific type
17-
func Collection[T any](auth model.Auth, base model.DatabaseConfig) Database[T] {
18+
func Collection[T any](auth model.Auth, base model.DatabaseConfig, col string) Database[T] {
1819
return Database[T]{
1920
auth: auth,
2021
conf: base,
22+
col: col,
2123
}
2224
}
2325

2426
// Create creates a record in the collection/repository
25-
func (d Database[T]) Create(col string, data T) (inserted T, err error) {
27+
func (d Database[T]) Create(data T) (inserted T, err error) {
2628
doc, err := toDoc(data)
2729
if err != nil {
2830
return
2931
}
3032

31-
doc, err = DB.CreateDocument(d.auth, d.conf.Name, col, doc)
33+
doc, err = DB.CreateDocument(d.auth, d.conf.Name, d.col, doc)
3234
if err != nil {
3335
return
3436
}
@@ -37,7 +39,7 @@ func (d Database[T]) Create(col string, data T) (inserted T, err error) {
3739
}
3840

3941
// BulkCreate creates multiple records in the collection/repository
40-
func (d Database[T]) BulkCreate(col string, entities []T) error {
42+
func (d Database[T]) BulkCreate(entities []T) error {
4143
docs := make([]interface{}, 0)
4244

4345
for _, doc := range entities {
@@ -48,7 +50,7 @@ func (d Database[T]) BulkCreate(col string, entities []T) error {
4850

4951
docs = append(docs, x)
5052
}
51-
return DB.BulkCreateDocument(d.auth, d.conf.Name, col, docs)
53+
return DB.BulkCreateDocument(d.auth, d.conf.Name, d.col, docs)
5254
}
5355

5456
// PageResult wraps a slice of type T with paging information
@@ -60,8 +62,8 @@ type PagedResult[T any] struct {
6062
}
6163

6264
// List returns records from a collection/repository using paging/sorting params
63-
func (d Database[T]) List(col string, lp model.ListParams) (res PagedResult[T], err error) {
64-
r, err := DB.ListDocuments(d.auth, d.conf.Name, col, lp)
65+
func (d Database[T]) List(lp model.ListParams) (res PagedResult[T], err error) {
66+
r, err := DB.ListDocuments(d.auth, d.conf.Name, d.col, lp)
6567
if err != nil {
6668
return
6769
}
@@ -83,13 +85,13 @@ func (d Database[T]) List(col string, lp model.ListParams) (res PagedResult[T],
8385
}
8486

8587
// Query returns records that match with the provided filters.
86-
func (d Database[T]) Query(col string, filters [][]any, lp model.ListParams) (res PagedResult[T], err error) {
88+
func (d Database[T]) Query(filters [][]any, lp model.ListParams) (res PagedResult[T], err error) {
8789
clauses, err := DB.ParseQuery(filters)
8890
if err != nil {
8991
return
9092
}
9193

92-
r, err := DB.QueryDocuments(d.auth, d.conf.Name, col, clauses, lp)
94+
r, err := DB.QueryDocuments(d.auth, d.conf.Name, d.col, clauses, lp)
9395
if err != nil {
9496
return
9597
}
@@ -111,8 +113,8 @@ func (d Database[T]) Query(col string, filters [][]any, lp model.ListParams) (re
111113
}
112114

113115
// GetByID returns a specific record from a collection/repository
114-
func (d Database[T]) GetByID(col, id string) (entity T, err error) {
115-
doc, err := DB.GetDocumentByID(d.auth, d.conf.Name, col, id)
116+
func (d Database[T]) GetByID(id string) (entity T, err error) {
117+
doc, err := DB.GetDocumentByID(d.auth, d.conf.Name, d.col, id)
116118
if err != nil {
117119
return
118120
}
@@ -122,13 +124,13 @@ func (d Database[T]) GetByID(col, id string) (entity T, err error) {
122124
}
123125

124126
// Update updates some fields of a record
125-
func (d Database[T]) Update(col, id string, v any) (entity T, err error) {
127+
func (d Database[T]) Update(id string, v any) (entity T, err error) {
126128
doc, err := toDoc(v)
127129
if err != nil {
128130
return
129131
}
130132

131-
x, err := DB.UpdateDocument(d.auth, d.conf.Name, col, id, doc)
133+
x, err := DB.UpdateDocument(d.auth, d.conf.Name, d.col, id, doc)
132134
if err != nil {
133135
return
134136
}
@@ -138,7 +140,7 @@ func (d Database[T]) Update(col, id string, v any) (entity T, err error) {
138140
}
139141

140142
// UpdateMany updates multiple records matching filters
141-
func (d Database[T]) UpdateMany(col string, filters [][]any, v any) (int64, error) {
143+
func (d Database[T]) UpdateMany(filters [][]any, v any) (int64, error) {
142144
clauses, err := DB.ParseQuery(filters)
143145
if err != nil {
144146
return 0, err
@@ -148,17 +150,17 @@ func (d Database[T]) UpdateMany(col string, filters [][]any, v any) (int64, erro
148150
if err != nil {
149151
return 0, err
150152
}
151-
return DB.UpdateDocuments(d.auth, d.conf.Name, col, clauses, doc)
153+
return DB.UpdateDocuments(d.auth, d.conf.Name, d.col, clauses, doc)
152154
}
153155

154156
// IncrementValue increments or decrements a specifc field from a collection/repository
155-
func (d Database[T]) IncrementValue(col, id, field string, n int) error {
156-
return DB.IncrementValue(d.auth, d.conf.Name, col, id, field, n)
157+
func (d Database[T]) IncrementValue(id, field string, n int) error {
158+
return DB.IncrementValue(d.auth, d.conf.Name, d.col, id, field, n)
157159
}
158160

159161
// Delete removes a record from a collection
160-
func (d Database[T]) Delete(col, id string) (int64, error) {
161-
return DB.DeleteDocument(d.auth, d.conf.Name, col, id)
162+
func (d Database[T]) Delete(id string) (int64, error) {
163+
return DB.DeleteDocument(d.auth, d.conf.Name, d.col, id)
162164
}
163165

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

backend/database_test.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,17 +32,17 @@ func newTask(title string, done bool) Task {
3232
}
3333

3434
func TestDatabaseCreate(t *testing.T) {
35-
db := backend.Collection[Task](adminAuth, base)
35+
db := backend.Collection[Task](adminAuth, base, "tasks")
3636

3737
task := newTask("db create", false)
38-
task, err := db.Create("tasks", task)
38+
task, err := db.Create(task)
3939
if err != nil {
4040
t.Fatal(err)
4141
} else if len(task.ID) == 0 {
4242
t.Error("expected task id length to be > 0")
4343
}
4444

45-
check, err := db.GetByID("tasks", task.ID)
45+
check, err := db.GetByID(task.ID)
4646
if err != nil {
4747
t.Fatal(err)
4848
} else if task.Title != check.Title {
@@ -51,19 +51,19 @@ func TestDatabaseCreate(t *testing.T) {
5151
}
5252

5353
func TestDatabaseList(t *testing.T) {
54-
db := backend.Collection[Task](adminAuth, base)
54+
db := backend.Collection[Task](adminAuth, base, "tasks")
5555

5656
tasks := []Task{
5757
newTask("t1", false),
5858
newTask("t2", true),
5959
}
6060

61-
if err := db.BulkCreate("tasks", tasks); err != nil {
61+
if err := db.BulkCreate(tasks); err != nil {
6262
t.Fatal(err)
6363
}
6464

6565
lp := model.ListParams{Page: 1, Size: 50}
66-
res, err := db.List("tasks", lp)
66+
res, err := db.List(lp)
6767
if err != nil {
6868
t.Fatal(err)
6969
} else if len(res.Results) < 2 {
@@ -72,15 +72,15 @@ func TestDatabaseList(t *testing.T) {
7272
}
7373

7474
func TestDatabaseQuery(t *testing.T) {
75-
db := backend.Collection[Task](adminAuth, base)
75+
db := backend.Collection[Task](adminAuth, base, "tasks")
7676

7777
tasks := []Task{
7878
newTask("qry1", false),
7979
newTask("qry2", true),
8080
newTask("qry2", false),
8181
}
8282

83-
if err := db.BulkCreate("tasks", tasks); err != nil {
83+
if err := db.BulkCreate(tasks); err != nil {
8484
t.Fatal(err)
8585
}
8686

@@ -93,7 +93,7 @@ func TestDatabaseQuery(t *testing.T) {
9393
}
9494

9595
lp := model.ListParams{Page: 1, Size: 50}
96-
res, err := db.Query("tasks", filters, lp)
96+
res, err := db.Query(filters, lp)
9797
if err != nil {
9898
t.Fatal(err)
9999
} else if res.Total != 1 {

0 commit comments

Comments
 (0)