handler.go 1.32 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
package server

import (
	"context"
	"github.com/spf13/cast"
	"gomicro-base/api/demo"
	"gomicro-base/service/demo/internal/model"
	"gomicro-base/service/demo/internal/service"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// 检查接口实现
var _ demo.DemoHandler = &handler{}

// handler类似控制器
type handler struct {
	svc *service.DemoService
}

func (h *handler) GetDemo(ctx context.Context, req *demo.DemoReq, resp *demo.DemoResp) error {
	getDemo, err := h.svc.GetDemo(ctx, req)
	if err != nil {
		return err
	}
	*resp = h.convertUserModel(getDemo)
	return nil
}

func (h *handler) ListDemo(ctx context.Context, req *demo.ListDemoReq, resp *demo.ListDemoResp) error {
	if req.Limit <= 0 {
		req.Limit = 15
	}
	
	listDemo, err := h.svc.ListDemo(ctx, req)
	if err != nil {
		return err
	}

	list := make([]*demo.DemoResp, 0)
	for _, v := range listDemo {
		c := h.convertUserModel(v)
		list = append(list, &c)
	}
	resp.List = list
	resp.Limit = req.Limit
	return nil
}

func (h *handler) convertUserModel(users *model.User) (resp demo.DemoResp) {
	return demo.DemoResp{
		Id:        cast.ToString(users.Id),
		Username:  users.Username,
		Email:     users.Email,
		Avatar:    users.Avatar,
		Status:    int32(users.Status),
		CreatedAt: timestamppb.New(users.CreatedAt),
		UpdatedAt: timestamppb.New(users.UpdatedAt),
	}
}