-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
90 lines (74 loc) · 1.9 KB
/
app.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
package main
import (
"context"
"database/sql"
"fmt"
"os"
"path/filepath"
"vasumatika/backend/product"
_ "github.com/mattn/go-sqlite3"
)
// App struct
type App struct {
Title string
AppDir string
ctx context.Context
productService product.Service
}
// NewApp creates a new App application struct
func NewApp() *App {
return &App{
Title: "vasumatika",
}
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
userDir, _ := os.UserHomeDir()
a.AppDir = filepath.Join(userDir, a.Title)
fmt.Println("app dir:", a.AppDir)
_ = os.MkdirAll(a.AppDir, os.ModePerm)
db := a.initDB()
productRepo := product.NewProductRepository(db)
a.productService = product.NewService(productRepo)
}
func (a *App) initDB() *sql.DB {
path := filepath.Join(a.AppDir, "data.db")
db, err := sql.Open("sqlite3", path)
if err != nil {
panic(err)
}
tableQueries := []string{
`CREATE TABLE IF NOT EXISTS categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE
);`,
`CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category_id INTEGER,
price INTEGER,
stock INTEGER,
barcode TEXT,
name TEXT NOT NULL,
description TEXT,
FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE SET NULL
);`,
}
for _, query := range tableQueries {
_, _ = db.Exec(query)
}
return db
}
func (a *App) GetProductById(id int, name string) (product.ProductResponse, error) {
return a.productService.GetProductByID(id)
}
func (a *App) GetProducts() ([]product.ProductResponse, error) {
return a.productService.ListProducts()
}
func (a *App) DeleteProductById(id int) error {
return a.productService.DeleteProduct(id)
}
func (a *App) GetCategories() ([]product.CategoryResponse, error) {
return a.productService.ListCategories()
}