2024-08-08 16:13:30 +07:00
|
|
|
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() {
|
2024-08-13 09:40:02 +07:00
|
|
|
err = models.Devices.Update(ctx, api.Executor, update, target)
|
2024-08-08 16:13:30 +07:00
|
|
|
})
|
|
|
|
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
|
|
|
|
}
|