-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·107 lines (83 loc) · 2.29 KB
/
main.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"context"
"fmt"
"log"
"time"
firebase "firebase.google.com/go"
"google.golang.org/api/option"
"github.com/micro/go-micro"
"github.com/spf13/viper"
discountProto "github.com/sisimogangg/supermarket.discount.api/proto"
pb "github.com/sisimogangg/supermarket.products.api/proto"
_repo "github.com/sisimogangg/supermarket.products.api/repository"
"github.com/sisimogangg/supermarket.products.api/service"
"github.com/sisimogangg/supermarket.products.api/utils"
_ "github.com/micro/go-micro/registry/mdns"
)
func init() {
viper.SetConfigFile("config.json")
err := viper.ReadInConfig()
if err != nil {
panic(err)
}
if viper.GetBool("debug") {
fmt.Println("Service RUN on DEBUG mode")
}
}
func seeding(app *firebase.App) {
ctx := context.Background()
client, err := app.Database(ctx)
if err != nil {
log.Fatal(err)
}
var rawProducts map[string]pb.Product
err = client.NewRef("products").Get(ctx, &rawProducts)
if err != nil {
log.Fatal(err)
}
if len(rawProducts) == 0 {
for _, p := range utils.Products {
if err := client.NewRef(fmt.Sprintf("products/%s", p.Id)).Set(ctx, p); err != nil {
log.Fatal(err)
}
}
for _, d := range utils.Details {
if err := client.NewRef(fmt.Sprintf("details/%s", d.Product.Id)).Set(ctx, d); err != nil {
log.Fatal(err)
}
}
}
}
func initializeFirebase() *firebase.App {
opt := option.WithCredentialsFile("firebaseServiceAccount.json")
ctx := context.Background()
config := &firebase.Config{
DatabaseURL: "https://supermarket-8aee3.firebaseio.com",
}
app, err := firebase.NewApp(ctx, config, opt)
if err != nil {
log.Fatal(err)
}
return app
}
func main() {
srv := micro.NewService(
micro.Name("supermarket.product"),
micro.Version("latest"),
)
srv.Init()
app := initializeFirebase()
repo := _repo.NewFirebaseRepo(app)
if viper.GetBool("debug") {
seeding(app)
}
timeContext := time.Duration(viper.GetInt("context.timeout")) * time.Second
discountClient := discountProto.NewDiscountServiceClient("supermarket.discount.client", srv.Client()) //shippy.service.client
productService := service.NewProductService(repo, discountClient, timeContext)
pb.RegisterProductServiceHandler(srv.Server(), productService)
// Run the server
if err := srv.Run(); err != nil {
fmt.Println(err)
}
}