demo.go 1.88 KB
Newer Older
kzkzzzz's avatar
kzkzzzz committed
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
package handler

import (
	"context"
	"hilo/api/service/demo"
	"hilo/app/service/demo/internal/model"
	"hilo/app/service/demo/internal/service"
)

// DemoHandler is a demo handler.
type DemoHandler struct {
	demo.UnimplementedDemoServer
	uc *service.DemoUseService
}

// Hello implements DemoServer.
func (h *DemoHandler) Hello(ctx context.Context, req *demo.HelloReq) (*demo.HelloRep, error) {
	return &demo.HelloRep{Message: "Hello " + req.Name}, nil
}
func (h *DemoHandler) Create(ctx context.Context, req *demo.CreateReq) (*demo.OKRep, error) {
	err := h.uc.CreateDemo(ctx, &model.Demo{Name: req.Name, Value: req.Value})
	if err != nil {
		return nil, err
	}
	return nil, nil
}

func (h *DemoHandler) Update(ctx context.Context, req *demo.UpdateReq) (*demo.OKRep, error) {
	err := h.uc.UpdateDemo(ctx, &model.Demo{Id: int(req.Id), Name: req.Name, Value: req.Value})
	if err != nil {
		return nil, err
	}
	return &demo.OKRep{}, nil

}

func (h *DemoHandler) Get(ctx context.Context, req *demo.IdReq) (*demo.DemoModel, error) {
	res, err := h.uc.GetDemo(ctx, int(req.Id))
	if err != nil {
		return nil, err
	}
	return DemoModelToRep(res), nil
}

func (h *DemoHandler) List(ctx context.Context, req *demo.ListReq) (*demo.ListRep, error) {
	list, err := h.uc.ListDemo(ctx, &service.ListReq{
		Page: int(req.Page),
		Size: int(req.Size),
	})

	if err != nil {
		return nil, err
	}

	rep := &demo.ListRep{}
	rep.List = make([]*demo.DemoModel, 0, len(list))

	for _, v := range list {
		rep.List = append(rep.List, DemoModelToRep(v))
	}
	return rep, nil
}

func (h *DemoHandler) Delete(ctx context.Context, req *demo.IdReq) (*demo.OKRep, error) {
	err := h.uc.DeleteDemo(ctx, int(req.Id))
	if err != nil {
		return nil, err
	}
	return &demo.OKRep{}, nil
}

var _ demo.DemoServer = &DemoHandler{}

// NewDemoHandler new a demo handler.
func NewDemoHandler(uc *service.DemoUseService) *DemoHandler {
	return &DemoHandler{uc: uc}
}