141 lines
2.4 KiB
Go
141 lines
2.4 KiB
Go
package services
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"math/big"
|
|
)
|
|
|
|
type SensorsService struct {
|
|
ctx *Context
|
|
}
|
|
|
|
type SensorItem struct {
|
|
Id int64 `json:"id"`
|
|
Name string `json:"name"`
|
|
AuthKey string `json:"authKey"`
|
|
}
|
|
|
|
func (s *SensorsService) GetList() ([]SensorItem, error) {
|
|
sensors := make([]SensorItem, 0)
|
|
|
|
rows, err := s.ctx.DB.Query("SELECT id, name, auth_key FROM sensors")
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
for rows.Next() {
|
|
item := SensorItem{}
|
|
|
|
err := rows.Scan(&item.Id, &item.Name, &item.AuthKey)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
sensors = append(sensors, item)
|
|
}
|
|
|
|
err = rows.Err()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return sensors, nil
|
|
}
|
|
|
|
func (s *SensorsService) Create(name string) (*SensorItem, error) {
|
|
authKey, err := generateRandomString(32)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
item := SensorItem{
|
|
Name: name,
|
|
AuthKey: authKey,
|
|
}
|
|
|
|
res, err := s.ctx.DB.Exec("INSERT INTO sensors (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
|
|
}
|
|
|
|
func (s *SensorsService) DeleteById(id int64) error {
|
|
item, err := s.GetById(id)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = s.ctx.DB.Exec("DELETE FROM sensor_values WHERE sensor_id = ?", item.Id)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = s.ctx.DB.Exec("DELETE FROM sensors WHERE id = ?", item.Id)
|
|
|
|
return err
|
|
}
|
|
|
|
var randomKeySource = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
|
|
|
|
func generateRandomString(length int) (string, error) {
|
|
key := make([]byte, length)
|
|
|
|
for i := range key {
|
|
value, err := rand.Int(rand.Reader, big.NewInt(int64(len(randomKeySource))))
|
|
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
key[i] = randomKeySource[value.Int64()]
|
|
}
|
|
|
|
return string(key), nil
|
|
}
|