zrok/controller/store/service.go

80 lines
2.4 KiB
Go
Raw Normal View History

2022-07-29 19:27:00 +02:00
package store
import (
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
type Service struct {
Model
2022-08-03 21:48:04 +02:00
EnvironmentId int
2022-08-03 19:43:54 +02:00
ZitiServiceId string
Endpoint string
Active bool
2022-07-29 19:27:00 +02:00
}
2022-08-03 20:58:11 +02:00
func (self *Store) CreateService(envId int, svc *Service, tx *sqlx.Tx) (int, error) {
stmt, err := tx.Prepare("insert into services (environment_id, ziti_service_id, endpoint, active) values (?, ?, ?, true)")
2022-07-29 19:27:00 +02:00
if err != nil {
return 0, errors.Wrap(err, "error preparing services insert statement")
}
2022-08-03 20:58:11 +02:00
res, err := stmt.Exec(envId, svc.ZitiServiceId, svc.Endpoint)
2022-07-29 19:27:00 +02:00
if err != nil {
return 0, errors.Wrap(err, "error executing services insert statement")
}
id, err := res.LastInsertId()
if err != nil {
return 0, errors.Wrap(err, "error retrieving last services insert id")
}
return int(id), nil
}
func (self *Store) GetService(id int, tx *sqlx.Tx) (*Service, error) {
svc := &Service{}
if err := tx.QueryRowx("select * from services where id = ?", id).StructScan(svc); err != nil {
return nil, errors.Wrap(err, "error selecting service by id")
}
return svc, nil
}
2022-08-03 20:58:11 +02:00
func (self *Store) FindServicesForEnvironment(envId int, tx *sqlx.Tx) ([]*Service, error) {
rows, err := tx.Queryx("select services.* from services where environment_id = ?", envId)
2022-07-29 19:27:00 +02:00
if err != nil {
2022-08-03 20:58:11 +02:00
return nil, errors.Wrap(err, "error selecting services by environment id")
2022-07-29 19:27:00 +02:00
}
var svcs []*Service
for rows.Next() {
svc := &Service{}
if err := rows.StructScan(svc); err != nil {
return nil, errors.Wrap(err, "error scanning service")
}
svcs = append(svcs, svc)
}
return svcs, nil
}
2022-07-29 22:27:03 +02:00
func (self *Store) UpdateService(svc *Service, tx *sqlx.Tx) error {
2022-08-03 19:43:54 +02:00
sql := "update services set ziti_service_id = ?, endpoint = ?, active = ?, updated_at = strftime('%Y-%m-%d %H:%M:%f', 'now') where id = ?"
2022-07-29 22:27:03 +02:00
stmt, err := tx.Prepare(sql)
if err != nil {
2022-07-29 22:27:03 +02:00
return errors.Wrap(err, "error preparing services update statement")
}
2022-08-03 19:43:54 +02:00
_, err = stmt.Exec(svc.ZitiServiceId, svc.Endpoint, svc.Active, svc.Id)
if err != nil {
2022-07-29 22:27:03 +02:00
return errors.Wrap(err, "error executing services update statement")
}
return nil
}
2022-07-29 19:27:00 +02:00
func (self *Store) DeleteService(id int, tx *sqlx.Tx) error {
stmt, err := tx.Prepare("delete from services where id = ?")
if err != nil {
return errors.Wrap(err, "error preparing services delete statement")
}
_, err = stmt.Exec(id)
if err != nil {
return errors.Wrap(err, "error executing services delete statement")
}
return nil
}