Bluemage/go/api/devices_update.go

47 lines
1.1 KiB
Go
Raw Normal View History

package api
import (
"context"
"errors"
"github.com/mattn/go-sqlite3"
"github.com/tigorlazuardi/bluemage/go/gen/models"
"github.com/tigorlazuardi/bluemage/go/pkg/errs"
"github.com/tigorlazuardi/bluemage/go/pkg/log"
)
func (api *API) DevicesUpdate(ctx context.Context, slug string, update *models.DeviceSetter) (err error) {
exist, err := api.DevicesExist(ctx, slug)
if err != nil {
return err
}
if !exist {
return errs.Failf("device with slug %q does not exist", slug)
}
ctx, coll := log.WithQueryCollector(ctx)
target := &models.Device{Slug: slug}
api.lockf(func() {
err = models.Devices.Update(ctx, api.Executor, update, target)
})
if err != nil {
if sqlite3Err := new(sqlite3.Error); errors.As(err, &sqlite3Err) {
if sqlite3Err.Code == sqlite3.ErrConstraint {
return errs.
Wrapw(
err, "a device with the same slug already exists",
"slug", slug,
"update", update,
"query", coll,
)
}
}
return errs.Wrapw(err, "failed to update device", "slug", slug, "update", update, "query", coll)
}
return nil
}