init
This commit is contained in:
commit
aee8bcc886
18 files changed
+960
No files matched your search
@@ -0,0 +1,60 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"example.com/layout/proto/micro_layout/proto/user"
|
||||
"gin_layout/enum"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
var ErrUserNotFound = errors.New("user not found")
|
||||
|
||||
type User struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Status enum.UserStatus `json:"status"`
|
||||
}
|
||||
|
||||
type UserService struct {
|
||||
client user.UserClient
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func NewUserService(client user.UserClient, timeout time.Duration) *UserService {
|
||||
return &UserService{client: client, timeout: timeout}
|
||||
}
|
||||
|
||||
func (service *UserService) GetByID(ctx context.Context, id int64) (User, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, service.timeout)
|
||||
defer cancel()
|
||||
response, err := service.client.QueryInfo(ctx, &user.QueryInfoRequest{Id: id})
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if !response.GetExists() {
|
||||
return User{}, ErrUserNotFound
|
||||
}
|
||||
return fromProto(response.GetItem())
|
||||
}
|
||||
|
||||
func (service *UserService) Create(ctx context.Context, name string) (User, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, service.timeout)
|
||||
defer cancel()
|
||||
response, err := service.client.Create(ctx, &user.CreateRequest{Name: name})
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
return fromProto(response.GetItem())
|
||||
}
|
||||
|
||||
func fromProto(item *user.UserItem) (User, error) {
|
||||
if item == nil {
|
||||
return User{}, status.Error(codes.Internal, "invalid user response")
|
||||
}
|
||||
return User{ID: item.GetId(), Name: item.GetName(), Status: enum.UserStatus(item.GetStatus())}, nil
|
||||
}
|
||||
Reference in new issue
Block a user