46 lines
1.4 KiB
Go
46 lines
1.4 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
type NewService struct {
|
|
ParentID int64
|
|
Slug string
|
|
Name string
|
|
Lead string
|
|
}
|
|
|
|
// AdminCreateService заводит услугу внутри направления, скрытой. Адрес — адрес направления
|
|
// плюс slug: /services/<направление>/<slug>/. Вложенность — только один уровень.
|
|
func (s *Storage) AdminCreateService(ctx context.Context, in NewService) (int64, error) {
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer tx.Rollback(ctx) //nolint:errcheck // после Commit откат ничего не делает
|
|
var parentPath string
|
|
if err := tx.QueryRow(ctx, `
|
|
SELECT path FROM services WHERE id=$1 AND parent_id IS NULL AND deleted_at IS NULL`,
|
|
in.ParentID).Scan(&parentPath); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return 0, ErrBadReference
|
|
}
|
|
return 0, err
|
|
}
|
|
var id int64
|
|
if err := tx.QueryRow(ctx, `
|
|
INSERT INTO services (parent_id, slug, path, name, lead, published,
|
|
sort)
|
|
VALUES ($1, $2, $3, $4, $5, false,
|
|
COALESCE((SELECT max(sort) + 10 FROM services WHERE parent_id = $1 AND deleted_at IS NULL), 100))
|
|
RETURNING id`,
|
|
in.ParentID, in.Slug, parentPath+"/"+in.Slug, in.Name, in.Lead).Scan(&id); err != nil {
|
|
return 0, wrapConflict(err)
|
|
}
|
|
return id, tx.Commit(ctx)
|
|
}
|