2024-04-24 21:57:13 +07:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
|
|
|
|
"github.com/mattn/go-sqlite3"
|
|
|
|
"github.com/tigorlazuardi/redmage/models"
|
|
|
|
"github.com/tigorlazuardi/redmage/pkg/errs"
|
|
|
|
)
|
|
|
|
|
2024-04-30 14:12:33 +07:00
|
|
|
func (api *API) DevicesUpdate(ctx context.Context, slug string, update *models.DeviceSetter) (device *models.Device, err error) {
|
2024-04-24 21:57:13 +07:00
|
|
|
ctx, span := tracer.Start(ctx, "*API.DevicesUpdate")
|
|
|
|
defer span.End()
|
|
|
|
|
2024-04-30 14:12:33 +07:00
|
|
|
device = &models.Device{Slug: slug}
|
2024-04-30 11:34:30 +07:00
|
|
|
|
2024-05-23 13:49:37 +07:00
|
|
|
api.lockf(func() {
|
|
|
|
err = models.Devices.Update(ctx, api.db, update, device)
|
|
|
|
})
|
2024-04-24 21:57:13 +07:00
|
|
|
if err != nil {
|
|
|
|
var sqliteErr sqlite3.Error
|
|
|
|
if errors.As(err, &sqliteErr) {
|
2024-04-24 22:00:15 +07:00
|
|
|
if sqliteErr.Code == sqlite3.ErrConstraint {
|
2024-04-30 11:34:30 +07:00
|
|
|
return device, errs.Wrapw(err, "a device with the same slug id already exists").Code(409)
|
2024-04-24 21:57:13 +07:00
|
|
|
}
|
|
|
|
}
|
2024-04-30 14:12:33 +07:00
|
|
|
return device, errs.Wrapw(err, "failed to update device", "slug", slug, "values", update)
|
2024-04-30 11:34:30 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := device.Reload(ctx, api.db); err != nil {
|
2024-04-30 21:39:53 +07:00
|
|
|
if err.Error() == "sql: no rows in result set" {
|
|
|
|
return device, errs.Wrapw(err, "device not found", "slug", slug).Code(404)
|
|
|
|
}
|
2024-04-30 14:12:33 +07:00
|
|
|
return device, errs.Wrapw(err, "failed to reload device", "slug", slug)
|
2024-04-24 21:57:13 +07:00
|
|
|
}
|
|
|
|
|
2024-04-30 11:34:30 +07:00
|
|
|
return device, nil
|
2024-04-24 21:57:13 +07:00
|
|
|
}
|