Add mechanism for initializing database with produce

This commit is contained in:
2021-06-21 11:47:51 -04:00
parent caa9db586c
commit 6e99e495b3
6 changed files with 47 additions and 4 deletions
BIN
View File
Binary file not shown.
+4 -3
View File
@@ -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
View File
@@ -1,3 +1,4 @@
ENV: dev
APIPORT: 3000
LOGLEVEL: debug
DMLINITFILE: defaultproduce.json
+31
View File
@@ -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")
}
}