Add mechanism for initializing database with produce
This commit is contained in:
BIN
Binary file not shown.
+4
-3
@@ -6,9 +6,10 @@ import (
|
||||
)
|
||||
|
||||
type config struct {
|
||||
Env string `default:"dev"`
|
||||
APIPort int `default:3000`
|
||||
LogLevel string `default:"debug"`
|
||||
Env string `default:"dev"`
|
||||
APIPort int `default:3000`
|
||||
LogLevel string `default:"debug"`
|
||||
DMLInitFile string
|
||||
}
|
||||
|
||||
func load() (cfg config, err error) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
ENV: dev
|
||||
APIPORT: 3000
|
||||
LOGLEVEL: debug
|
||||
DMLINITFILE: defaultproduce.json
|
||||
|
||||
@@ -2,6 +2,8 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
@@ -43,6 +45,7 @@ func main() {
|
||||
}
|
||||
|
||||
produceSvc := produce.NewService(db.From("produce"))
|
||||
initProduce(produceSvc)
|
||||
|
||||
server := http.NewServer(cfg.APIPort, logger, cfg.Env, produceSvc)
|
||||
|
||||
@@ -70,3 +73,31 @@ func main() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func initProduce(produceSvc http.ProduceService) {
|
||||
if cfg.DMLInitFile == "" {
|
||||
logger.Info("no init file provided, database will be empty")
|
||||
return
|
||||
}
|
||||
|
||||
f, err := os.Open(cfg.DMLInitFile)
|
||||
if err != nil {
|
||||
logger.Fatalf("could not open file: %s", cfg.DMLInitFile)
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadAll(f)
|
||||
if err != nil {
|
||||
logger.Fatal("could not read file: %s", cfg.DMLInitFile)
|
||||
}
|
||||
|
||||
var items []produce.Item
|
||||
err = json.Unmarshal(b, &items)
|
||||
if err != nil {
|
||||
logger.Fatalf("could not unmarshal items: %v", err)
|
||||
}
|
||||
|
||||
err = produceSvc.Add(items)
|
||||
if err != nil {
|
||||
logger.Fatal("failed to add items to produce service")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
[
|
||||
{"code":"A12T-4GH7-QPL9-3N4M","name":"Lettuce","price":{"amount":346,"currency":"USD"}},
|
||||
{"code":"E5T6-9UI3-TH15-QR88","name":"Peach","price":{"amount":299,"currency":"USD"}},
|
||||
{"code":"YRT6-72AS-K736-L4AR","name":"Green Pepper","price":{"amount":79,"currency":"USD"}},
|
||||
{"code":"TQ4C-VV6T-75ZX-1RMR","name":"Gala Apple","price":{"amount":359,"currency":"USD"}}
|
||||
]
|
||||
+5
-1
@@ -1,5 +1,7 @@
|
||||
package ramdb
|
||||
|
||||
import "sync"
|
||||
|
||||
type database struct {
|
||||
tables map[string]*table
|
||||
}
|
||||
@@ -28,7 +30,9 @@ func (db *database) CreateTable(tablename string, indexOnColumns ...string) erro
|
||||
}
|
||||
|
||||
tbl := &table{
|
||||
exists: true,
|
||||
exists: true,
|
||||
mutex: &sync.Mutex{},
|
||||
indexes: make(map[string]*index),
|
||||
}
|
||||
|
||||
for _, onColumn := range indexOnColumns {
|
||||
|
||||
Reference in New Issue
Block a user