-
Notifications
You must be signed in to change notification settings - Fork 1
/
create_job_by_etherum_address.go
71 lines (56 loc) · 2.08 KB
/
create_job_by_etherum_address.go
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
package commands
import (
"context"
"fmt"
"github.com/DIMO-Network/vehicle-signal-decoding/internal/core/common"
pgrpc "github.com/DIMO-Network/vehicle-signal-decoding/pkg/grpc"
"github.com/segmentio/ksuid"
"github.com/volatiletech/sqlboiler/v4/boil"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/DIMO-Network/vehicle-signal-decoding/internal/infrastructure/exceptions"
"github.com/pkg/errors"
"github.com/DIMO-Network/shared/db"
"github.com/DIMO-Network/vehicle-signal-decoding/internal/infrastructure/db/models"
)
type CreateJobByEtherumAddressCommandHandler struct {
DBS func() *db.ReaderWriter
}
func NewCreateJobByEtherumAddressCommandHandler(dbs func() *db.ReaderWriter) CreateJobByEtherumAddressCommandHandler {
return CreateJobByEtherumAddressCommandHandler{DBS: dbs}
}
type CreateJobCommandRequest struct {
Command string
EtherumAddress string
}
func (h CreateJobByEtherumAddressCommandHandler) Execute(ctx context.Context, command *CreateJobCommandRequest) (*pgrpc.GetJobsByEtherumAddressItemResponse, error) {
ethAddrBytes, err := common.ResolveEtherumAddressFromString(command.EtherumAddress)
if err != nil {
return nil, &exceptions.ValidationError{
Err: fmt.Errorf("invalid ethereum address: %w", err),
}
}
job := &models.Job{}
job.ID = ksuid.New().String()
job.Command = command.Command
job.DeviceEthereumAddress = ethAddrBytes
err = job.Insert(ctx, h.DBS().Writer, boil.Infer())
if err != nil {
return nil, &exceptions.InternalError{Err: errors.Wrapf(err, "error inserting job: %s", command.Command)}
}
jobItem, err := models.Jobs(models.JobWhere.DeviceEthereumAddress.EQ(ethAddrBytes)).One(ctx, h.DBS().Reader)
if err != nil {
return nil, &exceptions.InternalError{
Err: fmt.Errorf("failed to get job"),
}
}
result := &pgrpc.GetJobsByEtherumAddressItemResponse{
Id: jobItem.ID,
Command: jobItem.Command,
Status: jobItem.Status,
CreatedAt: timestamppb.New(jobItem.CreatedAt),
}
if jobItem.LastExecution.Valid {
result.LastExecution = timestamppb.New(jobItem.LastExecution.Time)
}
return result, nil
}