120 lines
2.5 KiB
Go
120 lines
2.5 KiB
Go
package services
|
|
|
|
import (
|
|
"basic-sensor-receiver/models"
|
|
"time"
|
|
)
|
|
|
|
type AlertsService struct {
|
|
ctx *Context
|
|
}
|
|
|
|
func (s *AlertsService) GetList() ([]models.AlertItem, error) {
|
|
alerts := []models.AlertItem{}
|
|
|
|
err := s.ctx.DB.Select(&alerts, `
|
|
SELECT id, contact_point_id, name, custom_message, condition, trigger_interval, last_status, last_status_at
|
|
FROM alerts
|
|
ORDER BY name ASC
|
|
`)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return alerts, nil
|
|
}
|
|
|
|
func (s *AlertsService) GetById(id int64) (*models.AlertItem, error) {
|
|
alert := models.AlertItem{}
|
|
|
|
err := s.ctx.DB.Get(&alert,
|
|
`
|
|
SELECT id, contact_point_id, name, custom_message, condition, trigger_interval, last_status, last_status_at
|
|
FROM alerts
|
|
WHERE id = $1
|
|
`,
|
|
id,
|
|
)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &alert, nil
|
|
}
|
|
|
|
func (s *AlertsService) Create(contactPointId int64, name string, condition string, triggerInterval int64, customMessage string) (*models.AlertItem, error) {
|
|
alert := models.AlertItem{
|
|
ContactPointId: contactPointId,
|
|
Name: name,
|
|
Condition: condition,
|
|
TriggerInterval: triggerInterval,
|
|
CustomMessage: customMessage,
|
|
LastStatus: models.AlertStatusOk,
|
|
LastStatusAt: time.Now().Unix(),
|
|
}
|
|
|
|
res, err := s.ctx.DB.NamedExec(
|
|
`
|
|
INSERT INTO alerts
|
|
(contact_point_id, name, condition, trigger_interval, last_status, last_status_at, custom_message) VALUES
|
|
(:contact_point_id, :name, :condition, :trigger_interval, :last_status, :last_status_at, :custom_message)
|
|
`,
|
|
alert,
|
|
)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
alert.Id, err = res.LastInsertId()
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &alert, nil
|
|
}
|
|
|
|
func (s *AlertsService) Update(id int64, contactPointId int64, name string, condition string, triggerInterval int64, customMessage string) (*models.AlertItem, error) {
|
|
alert := models.AlertItem{
|
|
Id: id,
|
|
ContactPointId: contactPointId,
|
|
Name: name,
|
|
Condition: condition,
|
|
TriggerInterval: triggerInterval,
|
|
CustomMessage: customMessage,
|
|
}
|
|
|
|
_, err := s.ctx.DB.NamedExec(
|
|
`
|
|
UPDATE alerts
|
|
SET
|
|
name = :name,
|
|
contact_point_id = :contact_point_id,
|
|
condition = :condition,
|
|
trigger_interval = :trigger_interval,
|
|
custom_message = :custom_message
|
|
WHERE id = :id
|
|
`,
|
|
alert,
|
|
)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &alert, nil
|
|
}
|
|
|
|
func (s *AlertsService) DeleteById(id int64) error {
|
|
_, err := s.ctx.DB.Exec("DELETE FROM alerts WHERE id = ?", id)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|