2022-08-13 23:33:50 +02:00
|
|
|
package services
|
|
|
|
|
|
2022-08-28 11:56:03 +02:00
|
|
|
import "encoding/hex"
|
|
|
|
|
|
2022-08-13 23:33:50 +02:00
|
|
|
type SensorsService struct {
|
|
|
|
|
ctx *Context
|
|
|
|
|
}
|
|
|
|
|
|
2022-08-28 11:56:03 +02:00
|
|
|
type SensorItem struct {
|
|
|
|
|
Id int64 `json:"id"`
|
|
|
|
|
Name string `json:"name"`
|
|
|
|
|
AuthKey string `json:"authKey"`
|
2022-08-13 23:33:50 +02:00
|
|
|
}
|
|
|
|
|
|
2022-08-28 11:56:03 +02:00
|
|
|
func (s *SensorsService) GetList() ([]SensorItem, error) {
|
|
|
|
|
sensors := make([]SensorItem, 0)
|
2022-08-13 23:33:50 +02:00
|
|
|
|
2022-08-28 11:56:03 +02:00
|
|
|
rows, err := s.ctx.DB.Query("SELECT id, name, auth_key FROM sensors")
|
2022-08-13 23:33:50 +02:00
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
defer rows.Close()
|
|
|
|
|
|
|
|
|
|
for rows.Next() {
|
2022-08-28 11:56:03 +02:00
|
|
|
item := SensorItem{}
|
2022-08-13 23:33:50 +02:00
|
|
|
|
2022-08-28 11:56:03 +02:00
|
|
|
err := rows.Scan(&item.Id, &item.Name, &item.AuthKey)
|
2022-08-13 23:33:50 +02:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
2022-08-28 11:56:03 +02:00
|
|
|
sensors = append(sensors, item)
|
2022-08-13 23:33:50 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
err = rows.Err()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return sensors, nil
|
|
|
|
|
}
|
2022-08-28 11:56:03 +02:00
|
|
|
|
|
|
|
|
func (s *SensorsService) Create(name string) (*SensorItem, error) {
|
|
|
|
|
item := SensorItem{
|
|
|
|
|
Name: name,
|
|
|
|
|
AuthKey: hex.EncodeToString(generateRandomKey(32)),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
res, err := s.ctx.DB.Exec("INSERT INTO sensors (id, name, auth_key) VALUES (?, ?)", item.Name, item.AuthKey)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
item.Id, err = res.LastInsertId()
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return &item, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *SensorsService) GetById(id int64) (*SensorItem, error) {
|
|
|
|
|
item := SensorItem{}
|
|
|
|
|
|
|
|
|
|
row := s.ctx.DB.QueryRow("SELECT id, name, auth_key FROM sensors WHERE id = ?", id)
|
|
|
|
|
|
|
|
|
|
err := row.Scan(&item.Id, &item.Name, &item.AuthKey)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return &item, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *SensorsService) Update(id int64, name string) (*SensorItem, error) {
|
|
|
|
|
item, err := s.GetById(id)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
item.Name = name
|
|
|
|
|
|
|
|
|
|
_, err = s.ctx.DB.Exec("UPDATE sensors SET name = ? WHERE id = ?", item.Name, item.Id)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return item, nil
|
|
|
|
|
}
|