60 lines
1.6 KiB
Go
60 lines
1.6 KiB
Go
package grpc
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
|
|
hav1 "gitea.nik4nao.com/nik/home-services/gen/ha/v1"
|
|
"gitea.nik4nao.com/nik/home-services/ha-gateway/internal/core/domain"
|
|
"gitea.nik4nao.com/nik/home-services/ha-gateway/internal/core/ports/driving"
|
|
)
|
|
|
|
type EntityGRPC struct {
|
|
hav1.UnimplementedEntityServiceServer
|
|
svc driving.EntityService
|
|
}
|
|
|
|
func NewEntityGRPC(svc driving.EntityService) *EntityGRPC {
|
|
return &EntityGRPC{svc: svc}
|
|
}
|
|
|
|
func (h *EntityGRPC) GetState(ctx context.Context, req *hav1.GetStateRequest) (*hav1.GetStateResponse, error) {
|
|
s, err := h.svc.GetState(ctx, domain.EntityID(req.EntityId))
|
|
if err != nil {
|
|
return nil, grpcError(err)
|
|
}
|
|
return &hav1.GetStateResponse{State: domainStateToProto(s)}, nil
|
|
}
|
|
|
|
func (h *EntityGRPC) ListStates(ctx context.Context, req *hav1.ListStatesRequest) (*hav1.ListStatesResponse, error) {
|
|
ids := make([]domain.EntityID, len(req.EntityIds))
|
|
for i, id := range req.EntityIds {
|
|
ids[i] = domain.EntityID(id)
|
|
}
|
|
|
|
states, err := h.svc.ListStates(ctx, ids, req.Domain)
|
|
if err != nil {
|
|
return nil, grpcError(err)
|
|
}
|
|
|
|
proto := make([]*hav1.EntityState, len(states))
|
|
for i, s := range states {
|
|
proto[i] = domainStateToProto(s)
|
|
}
|
|
return &hav1.ListStatesResponse{States: proto}, nil
|
|
}
|
|
|
|
// grpcError maps domain errors to appropriate gRPC status codes.
|
|
func grpcError(err error) error {
|
|
if errors.Is(err, ErrNotFound) {
|
|
return status.Errorf(codes.NotFound, "%v", err)
|
|
}
|
|
return status.Errorf(codes.Internal, "%v", err)
|
|
}
|
|
|
|
// ErrNotFound is returned by the app layer when an entity does not exist.
|
|
var ErrNotFound = errors.New("not found")
|