Skip to content

Commit

Permalink
chore(gomall/tutorial):ch11
Browse files Browse the repository at this point in the history
  • Loading branch information
baiyutang committed Jun 4, 2024
1 parent 7bf3344 commit f2d05af
Show file tree
Hide file tree
Showing 151 changed files with 2,672 additions and 2,332 deletions.
3 changes: 3 additions & 0 deletions gomall/tutorial/ch11/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
app/*/tmp
app/*/.env
app/*/log
9 changes: 3 additions & 6 deletions gomall/tutorial/ch11/Makefile
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
export ROOT_MOD=github.com/cloudwego/biz-demo/gomall
.PHONY: gen-demo-proto
gen-demo-proto:
@cd demo/demo_proto && cwgo server -I ../../idl --module github.com/cloudwego/biz-demo/gomall/demo/demo_proto --service demo_proto --idl ../../idl/echo.proto
@cd demo/demo_proto && cwgo server -I ../../idl --module ${ROOT_MOD}/demo/demo_proto --service demo_proto --idl ../../idl/echo.proto

.PHONY: gen-demo-thrift
gen-demo-thrift:
@cd demo/demo_thrift && cwgo server --module github.com/cloudwego/biz-demo/gomall/demo/demo_thrift --service demo_thrift --idl ../../idl/echo.thrift
@cd demo/demo_thrift && cwgo server --module ${ROOT_MOD}/demo/demo_thrift --service demo_thrift --idl ../../idl/echo.thrift

.PHONY: demo-link-fix
demo-link-fix:
cd demo/demo_proto && golangci-lint run -E gofumpt --path-prefix=. --fix --timeout=5m

.PHONY: gen-frontend
gen-frontend:
@cd app/frontend && cwgo server -I ../../idl --type HTTP --service frontend --module github.com/cloudwego/biz-demo/gomall/app/frontend --idl ../../idl/frontend/cart_page.proto
@cd app/frontend && cwgo server -I ../../idl --type HTTP --service frontend --module ${ROOT_MOD}/app/frontend --idl ../../idl/frontend/cart_page.proto

.PHONY: gen-user
gen-user:
Expand All @@ -25,10 +25,7 @@ gen-product:
@cd rpc_gen && cwgo client --type RPC --service product --module ${ROOT_MOD}/rpc_gen -I ../idl --idl ../idl/product.proto
@cd app/product && cwgo server --type RPC --service product --module ${ROOT_MOD}/app/product --pass "-use ${ROOT_MOD}/rpc_gen/kitex_gen" -I ../../idl --idl ../../idl/product.proto


.PHONY: gen-cart
gen-cart:
@cd rpc_gen && cwgo client --type RPC --service cart --module ${ROOT_MOD}/rpc_gen -I ../idl --idl ../idl/cart.proto
@cd app/cart && cwgo server --type RPC --service cart --module ${ROOT_MOD}/app/cart --pass "-use ${ROOT_MOD}/rpc_gen/kitex_gen" -I ../../idl --idl ../../idl/cart.proto


8 changes: 3 additions & 5 deletions gomall/tutorial/ch11/app/cart/.env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
MYSQL_USER=root
MYSQL_PASSWORD=root
MYSQL_HOST=127.0.0.1
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://127.0.0.1:4317
OTEL_EXPORTER_OTLP_INSECURE=true
MYSQL_USER="root"
MYSQL_PASSWORD="root"
MYSQL_HOST="127.0.0.1"
2 changes: 1 addition & 1 deletion gomall/tutorial/ch11/app/cart/biz/dal/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ import (
)

func Init() {
// redis.Init()
//redis.Init()
mysql.Init()
}
11 changes: 4 additions & 7 deletions gomall/tutorial/ch11/app/cart/biz/dal/mysql/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (

"github.com/cloudwego/biz-demo/gomall/app/cart/biz/model"
"github.com/cloudwego/biz-demo/gomall/app/cart/conf"

"gorm.io/driver/mysql"
"gorm.io/gorm"
)
Expand All @@ -30,19 +31,15 @@ var (
)

func Init() {
DB, err = gorm.Open(mysql.Open(fmt.Sprintf(conf.GetConf().MySQL.DSN, os.Getenv("MYSQL_USER"), os.Getenv("MYSQL_PASSWORD"), os.Getenv("MYSQL_HOST"))),
dsn := fmt.Sprintf(conf.GetConf().MySQL.DSN, os.Getenv("MYSQL_USER"), os.Getenv("MYSQL_PASSWORD"), os.Getenv("MYSQL_HOST"))
DB, err = gorm.Open(mysql.Open(dsn),
&gorm.Config{
PrepareStmt: true,
SkipDefaultTransaction: true,
},
)
DB.AutoMigrate(&model.Cart{})
if err != nil {
panic(err)
}
if os.Getenv("GO_ENV") != "online" {
//nolint:errcheck
DB.AutoMigrate(
&model.Cart{},
)
}
}
4 changes: 3 additions & 1 deletion gomall/tutorial/ch11/app/cart/biz/dal/redis/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ import (
"github.com/redis/go-redis/v9"
)

var RedisClient *redis.Client
var (
RedisClient *redis.Client
)

func Init() {
RedisClient = redis.NewClient(&redis.Options{
Expand Down
23 changes: 0 additions & 23 deletions gomall/tutorial/ch11/app/cart/biz/model/base.go

This file was deleted.

49 changes: 29 additions & 20 deletions gomall/tutorial/ch11/app/cart/biz/model/cart.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,38 +22,47 @@ import (
)

type Cart struct {
Base
UserId uint32 `json:"user_id"`
ProductId uint32 `json:"product_id"`
Qty uint32 `json:"qty"`
gorm.Model
UserId uint32 `gorm:"type:int(11);not null;index:idx_user_id"`
ProductId uint32 `gorm:"type:int(11);not null;"`
Qty uint32 `gorm:"type:int(11);not null;"`
}

func (c Cart) TableName() string {
func (Cart) TableName() string {
return "cart"
}

func GetCartByUserId(db *gorm.DB, ctx context.Context, userId uint32) (cartList []*Cart, err error) {
err = db.Debug().WithContext(ctx).Model(&Cart{}).Find(&cartList, "user_id = ?", userId).Error
return cartList, err
}

func AddCart(db *gorm.DB, ctx context.Context, c *Cart) error {
var find Cart
err := db.WithContext(ctx).Model(&Cart{}).Where(&Cart{UserId: c.UserId, ProductId: c.ProductId}).First(&find).Error
func AddItem(ctx context.Context, db *gorm.DB, item *Cart) error {
var row Cart
err := db.WithContext(ctx).
Model(&Cart{}).
Where(&Cart{UserId: item.UserId, ProductId: item.ProductId}).
First(&row).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return err
}
if find.ID != 0 {
err = db.WithContext(ctx).Model(&Cart{}).Where(&Cart{UserId: c.UserId, ProductId: c.ProductId}).UpdateColumn("qty", gorm.Expr("qty+?", c.Qty)).Error
} else {
err = db.WithContext(ctx).Model(&Cart{}).Create(c).Error
if row.ID > 0 {
return db.WithContext(ctx).
Model(&Cart{}).
Where(&Cart{UserId: item.UserId, ProductId: item.ProductId}).
UpdateColumn("qty", gorm.Expr("qty+?", item.Qty)).Error
}
return err

return db.WithContext(ctx).Create(item).Error
}

func EmptyCart(db *gorm.DB, ctx context.Context, userId uint32) error {
func EmptyCart(ctx context.Context, db *gorm.DB, userId uint32) error {
if userId == 0 {
return errors.New("user_is is required")
return errors.New("user id is required")
}
return db.WithContext(ctx).Delete(&Cart{}, "user_id = ?", userId).Error
}

func GetCartByUserId(ctx context.Context, db *gorm.DB, userId uint32) ([]*Cart, error) {
var rows []*Cart
err := db.WithContext(ctx).
Model(&Cart{}).
Where(&Cart{UserId: userId}).
Find(&rows).Error
return rows, err
}
15 changes: 0 additions & 15 deletions gomall/tutorial/ch11/app/cart/biz/model/cart_test.go

This file was deleted.

15 changes: 7 additions & 8 deletions gomall/tutorial/ch11/app/cart/biz/service/add_item.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"github.com/cloudwego/biz-demo/gomall/app/cart/biz/dal/mysql"
"github.com/cloudwego/biz-demo/gomall/app/cart/biz/model"
"github.com/cloudwego/biz-demo/gomall/app/cart/infra/rpc"

cart "github.com/cloudwego/biz-demo/gomall/rpc_gen/kitex_gen/cart"
"github.com/cloudwego/biz-demo/gomall/rpc_gen/kitex_gen/product"
"github.com/cloudwego/kitex/pkg/kerrors"
Expand All @@ -36,21 +35,21 @@ func NewAddItemService(ctx context.Context) *AddItemService {
// Run create note info
func (s *AddItemService) Run(req *cart.AddItemReq) (resp *cart.AddItemResp, err error) {
// Finish your business logic.
getProduct, err := rpc.ProductClient.GetProduct(s.ctx, &product.GetProductReq{Id: req.Item.GetProductId()})
productResp, err := rpc.ProductClient.GetProduct(s.ctx, &product.GetProductReq{Id: req.Item.ProductId})
if err != nil {
return nil, err
}

if getProduct.Product == nil || getProduct.Product.Id == 0 {
return nil, kerrors.NewBizStatusError(40004, "product not exist")
if productResp == nil || productResp.Product.Id == 0 {
return nil, kerrors.NewBizStatusError(40004, "product not found")
}

err = model.AddCart(mysql.DB, s.ctx, &model.Cart{
cartItem := &model.Cart{
UserId: req.UserId,
ProductId: req.Item.ProductId,
Qty: uint32(req.Item.Quantity),
})
Qty: req.Item.Quantity,
}

err = model.AddItem(s.ctx, mysql.DB, cartItem)
if err != nil {
return nil, kerrors.NewBizStatusError(50000, err.Error())
}
Expand Down
14 changes: 14 additions & 0 deletions gomall/tutorial/ch11/app/cart/biz/service/add_item_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,22 @@
package service

import (
"context"
"testing"

cart "github.com/cloudwego/biz-demo/gomall/rpc_gen/kitex_gen/cart"
)

func TestAddItem_Run(t *testing.T) {
ctx := context.Background()
s := NewAddItemService(ctx)
// init req and assert value

req := &cart.AddItemReq{}
resp, err := s.Run(req)
t.Logf("err: %v", err)
t.Logf("resp: %v", resp)

// todo: edit your unit test

}
5 changes: 2 additions & 3 deletions gomall/tutorial/ch11/app/cart/biz/service/empty_cart.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,9 @@ func NewEmptyCartService(ctx context.Context) *EmptyCartService {
// Run create note info
func (s *EmptyCartService) Run(req *cart.EmptyCartReq) (resp *cart.EmptyCartResp, err error) {
// Finish your business logic.
err = model.EmptyCart(mysql.DB, s.ctx, req.GetUserId())
err = model.EmptyCart(s.ctx, mysql.DB, req.UserId)
if err != nil {
return &cart.EmptyCartResp{}, kerrors.NewBizStatusError(50001, "empty cart error")
return nil, kerrors.NewBizStatusError(50001, err.Error())
}

return &cart.EmptyCartResp{}, nil
}
14 changes: 14 additions & 0 deletions gomall/tutorial/ch11/app/cart/biz/service/empty_cart_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,22 @@
package service

import (
"context"
"testing"

cart "github.com/cloudwego/biz-demo/gomall/rpc_gen/kitex_gen/cart"
)

func TestEmptyCart_Run(t *testing.T) {
ctx := context.Background()
s := NewEmptyCartService(ctx)
// init req and assert value

req := &cart.EmptyCartReq{}
resp, err := s.Run(req)
t.Logf("err: %v", err)
t.Logf("resp: %v", resp)

// todo: edit your unit test

}
15 changes: 8 additions & 7 deletions gomall/tutorial/ch11/app/cart/biz/service/get_cart.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,17 @@ func NewGetCartService(ctx context.Context) *GetCartService {

// Run create note info
func (s *GetCartService) Run(req *cart.GetCartReq) (resp *cart.GetCartResp, err error) {
// resp = &cart.Cart{}
// Finish your business logic.
carts, err := model.GetCartByUserId(mysql.DB, s.ctx, req.GetUserId())
list, err := model.GetCartByUserId(s.ctx, mysql.DB, req.UserId)
if err != nil {
return nil, kerrors.NewBizStatusError(50000, err.Error())
return nil, kerrors.NewBizStatusError(50002, err.Error())
}
var items []*cart.CartItem
for _, v := range carts {
items = append(items, &cart.CartItem{ProductId: v.ProductId, Quantity: int32(v.Qty)})
for _, item := range list {
items = append(items, &cart.CartItem{
ProductId: item.ProductId,
Quantity: item.Qty,
})
}

return &cart.GetCartResp{Cart: &cart.Cart{UserId: req.GetUserId(), Items: items}}, nil
return &cart.GetCartResp{Items: items}, nil
}
14 changes: 14 additions & 0 deletions gomall/tutorial/ch11/app/cart/biz/service/get_cart_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,22 @@
package service

import (
"context"
"testing"

cart "github.com/cloudwego/biz-demo/gomall/rpc_gen/kitex_gen/cart"
)

func TestGetCart_Run(t *testing.T) {
ctx := context.Background()
s := NewGetCartService(ctx)
// init req and assert value

req := &cart.GetCartReq{}
resp, err := s.Run(req)
t.Logf("err: %v", err)
t.Logf("resp: %v", resp)

// todo: edit your unit test

}
4 changes: 2 additions & 2 deletions gomall/tutorial/ch11/app/cart/conf/conf.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package conf

import (
"io/ioutil"
"os"
"path/filepath"
"sync"
Expand Down Expand Up @@ -52,7 +53,6 @@ type Redis struct {
type Kitex struct {
Service string `yaml:"service"`
Address string `yaml:"address"`
MetricsPort string `yaml:"metrics_port"`
EnablePprof bool `yaml:"enable_pprof"`
EnableGzip bool `yaml:"enable_gzip"`
EnableAccessLog bool `yaml:"enable_access_log"`
Expand All @@ -78,7 +78,7 @@ func GetConf() *Config {
func initConf() {
prefix := "conf"
confFileRelPath := filepath.Join(prefix, filepath.Join(GetEnv(), "conf.yaml"))
content, err := os.ReadFile(confFileRelPath)
content, err := ioutil.ReadFile(confFileRelPath)
if err != nil {
panic(err)
}
Expand Down
3 changes: 1 addition & 2 deletions gomall/tutorial/ch11/app/cart/conf/dev/conf.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
kitex:
service: "cart"
address: ":8883"
metrics_port: ":9993"
log_level: info
log_file_name: "log/kitex.log"
log_max_size: 10
Expand All @@ -15,7 +14,7 @@ registry:
password: ""

mysql:
dsn: "%s:%s@tcp(%s:3306)/product?charset=utf8mb4&parseTime=True&loc=Local"
dsn: "%s:%s@tcp(%s:3306)/cart?charset=utf8mb4&parseTime=True&loc=Local"

redis:
address: "127.0.0.1:6379"
Expand Down
Loading

0 comments on commit f2d05af

Please sign in to comment.