2024-08-04 20:18:54 +07:00
|
|
|
package handlers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"connectrpc.com/connect"
|
2024-08-04 20:53:51 +07:00
|
|
|
"github.com/bufbuild/protovalidate-go"
|
2024-08-04 20:18:54 +07:00
|
|
|
"github.com/tigorlazuardi/redmage/api"
|
2024-08-04 20:53:51 +07:00
|
|
|
"github.com/tigorlazuardi/redmage/gen/converter"
|
2024-08-04 20:18:54 +07:00
|
|
|
device "github.com/tigorlazuardi/redmage/gen/proto/device/v1"
|
|
|
|
deviceConnect "github.com/tigorlazuardi/redmage/gen/proto/device/v1/v1connect"
|
2024-08-04 20:53:51 +07:00
|
|
|
"github.com/tigorlazuardi/redmage/pkg/errs"
|
2024-08-04 20:18:54 +07:00
|
|
|
)
|
|
|
|
|
2024-08-04 20:53:51 +07:00
|
|
|
var (
|
|
|
|
_ deviceConnect.DeviceServiceHandler = (*Device)(nil)
|
|
|
|
convert converter.ConverterImpl
|
|
|
|
validator = func() *protovalidate.Validator {
|
|
|
|
v, err := protovalidate.New()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return v
|
|
|
|
}()
|
|
|
|
)
|
2024-08-04 20:18:54 +07:00
|
|
|
|
|
|
|
type Device struct {
|
|
|
|
deviceConnect.UnimplementedDeviceServiceHandler
|
|
|
|
|
|
|
|
API *api.API
|
|
|
|
}
|
|
|
|
|
|
|
|
func (de *Device) CreateDevice(ctx context.Context, req *connect.Request[device.CreateDeviceRequest]) (*connect.Response[device.CreateDeviceResponse], error) {
|
|
|
|
ctx, span := tracer.Start(ctx, "Device.CreateDevice")
|
|
|
|
defer span.End()
|
|
|
|
|
2024-08-04 20:53:51 +07:00
|
|
|
if err := validator.Validate(req.Msg); err != nil {
|
|
|
|
return nil, connect.NewError(connect.CodeInvalidArgument, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
requestDao := convert.CreateDeviceRequestToModelsDevice(req.Msg)
|
|
|
|
|
|
|
|
dev, err := de.API.DevicesCreate(ctx, requestDao)
|
|
|
|
if err != nil {
|
|
|
|
code := errs.ExtractConnectCode(err)
|
|
|
|
return nil, connect.NewError(code, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
createResponse := convert.ModelsDeviceToCreateDeviceResponse(dev)
|
|
|
|
return connect.NewResponse(createResponse), nil
|
2024-08-04 20:18:54 +07:00
|
|
|
}
|