/
get_dt_by_id.go
61 lines (48 loc) · 1.72 KB
/
get_dt_by_id.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
//nolint:tagliatelle
package queries
import (
"context"
"database/sql"
"fmt"
"github.com/DIMO-Network/device-definitions-api/internal/core/mediator"
coremodels "github.com/DIMO-Network/device-definitions-api/internal/core/models"
"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/pkg/errors"
)
type GetDeviceTypeByIDQuery struct {
DeviceTypeID string `json:"device_type_id"`
}
func (*GetDeviceTypeByIDQuery) Key() string { return "GetDeviceTypeByIDQuery" }
type GetDeviceTypeByIDQueryHandler struct {
DBS func() *db.ReaderWriter
}
func NewGetDeviceTypeByIDQueryHandler(dbs func() *db.ReaderWriter) GetDeviceTypeByIDQueryHandler {
return GetDeviceTypeByIDQueryHandler{DBS: dbs}
}
func (ch GetDeviceTypeByIDQueryHandler) Handle(ctx context.Context, query mediator.Message) (interface{}, error) {
qry := query.(*GetDeviceTypeByIDQuery)
v, err := models.DeviceTypes(models.DeviceTypeWhere.ID.EQ(qry.DeviceTypeID)).One(ctx, ch.DBS().Reader)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, &exceptions.NotFoundError{
Err: fmt.Errorf("could not find device type id: %s", qry.DeviceTypeID),
}
}
return nil, &exceptions.InternalError{
Err: fmt.Errorf("failed to get device types"),
}
}
result := coremodels.GetDeviceTypeQueryResult{
ID: v.ID,
Name: v.Name,
Metadatakey: v.Metadatakey,
}
// attribute info
var ai map[string][]coremodels.GetDeviceTypeAttributeQueryResult
if err := v.Properties.Unmarshal(&ai); err == nil {
result.Attributes = append(result.Attributes, ai["properties"]...)
}
return result, nil
}