2024-04-14 20:21:45 +07:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-04-24 21:57:13 +07:00
|
|
|
"errors"
|
2024-04-14 20:21:45 +07:00
|
|
|
|
2024-04-24 21:57:13 +07:00
|
|
|
"github.com/mattn/go-sqlite3"
|
|
|
|
"github.com/tigorlazuardi/redmage/models"
|
|
|
|
"github.com/tigorlazuardi/redmage/pkg/errs"
|
2024-04-14 20:21:45 +07:00
|
|
|
)
|
|
|
|
|
2024-04-24 21:57:13 +07:00
|
|
|
type DeviceCreateParams = models.DeviceSetter
|
2024-04-14 20:21:45 +07:00
|
|
|
|
2024-04-24 21:57:13 +07:00
|
|
|
func (api *API) DevicesCreate(ctx context.Context, params *DeviceCreateParams) (*models.Device, error) {
|
2024-04-14 20:21:45 +07:00
|
|
|
ctx, span := tracer.Start(ctx, "*API.DevicesCreate")
|
|
|
|
defer span.End()
|
2024-04-24 21:57:13 +07:00
|
|
|
|
2024-04-25 13:28:35 +07:00
|
|
|
device, err := models.Devices.Insert(ctx, api.db, params)
|
2024-04-24 21:57:13 +07:00
|
|
|
if err != nil {
|
|
|
|
var sqliteErr sqlite3.Error
|
|
|
|
if errors.As(err, &sqliteErr) {
|
|
|
|
if sqliteErr.Code == sqlite3.ErrConstraint {
|
|
|
|
return nil, errs.Wrapw(sqliteErr, "device already exists", "params", params).Code(409)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, errs.Wrapw(err, "failed to create device", "params", params)
|
|
|
|
}
|
|
|
|
return device, nil
|
2024-04-14 20:21:45 +07:00
|
|
|
}
|