Bluemage/go/api/subreddits_create.go

32 lines
794 B
Go

package api
import (
"context"
"errors"
"connectrpc.com/connect"
"github.com/mattn/go-sqlite3"
"github.com/tigorlazuardi/bluemage/go/gen/models"
"github.com/tigorlazuardi/bluemage/go/pkg/errs"
)
func (api *API) SubredditCreate(ctx context.Context, subreddit *models.SubredditSetter) (err error) {
// TODO: add check to Reddit API to see if subreddit exists.
api.lockf(func() {
_, err = models.Subreddits.Insert(ctx, api.Executor, subreddit)
})
if err != nil {
if sqlite3err := new(sqlite3.Error); errors.As(err, &sqlite3err) {
if sqlite3err.Code == sqlite3.ErrConstraint {
return errs.
Wrapw(err, "subreddit already exists", "input", subreddit).
Code(connect.CodeAlreadyExists)
}
}
return errs.Wrap(err, "failed to insert subreddit")
}
return nil
}