-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_dt.go
50 lines (37 loc) · 1.41 KB
/
create_dt.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
package commands
import (
"context"
"github.com/DIMO-Network/device-definitions-api/internal/core/common"
"github.com/DIMO-Network/device-definitions-api/internal/infrastructure/db/models"
"github.com/DIMO-Network/device-definitions-api/internal/infrastructure/exceptions"
"github.com/DIMO-Network/shared/db"
"github.com/TheFellow/go-mediator/mediator"
"github.com/pkg/errors"
"github.com/volatiletech/sqlboiler/v4/boil"
)
type CreateDeviceTypeCommand struct {
ID string `json:"id"`
Name string `json:"name"`
}
type CreateDeviceTypeCommandResult struct {
ID string `json:"id"`
}
func (*CreateDeviceTypeCommand) Key() string { return "CreateDeviceTypeCommand" }
type CreateDeviceTypeCommandHandler struct {
DBS func() *db.ReaderWriter
}
func NewCreateDeviceTypeCommandHandler(dbs func() *db.ReaderWriter) CreateDeviceTypeCommandHandler {
return CreateDeviceTypeCommandHandler{DBS: dbs}
}
func (ch CreateDeviceTypeCommandHandler) Handle(ctx context.Context, query mediator.Message) (interface{}, error) {
command := query.(*CreateDeviceTypeCommand)
dt := models.DeviceType{}
dt.ID = command.ID
dt.Name = command.Name
dt.Metadatakey = common.SlugString(command.Name)
err := dt.Insert(ctx, ch.DBS().Writer, boil.Infer())
if err != nil {
return nil, &exceptions.InternalError{Err: errors.Wrapf(err, "error inserting device type: %s", command.Name)}
}
return CreateDeviceTypeCommandResult{ID: dt.ID}, nil
}