74 lines
1.9 KiB
Go
74 lines
1.9 KiB
Go
package blogs
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"git.sleepycat.moe/sam/mercury/internal/database/sql"
|
|
"git.sleepycat.moe/sam/mercury/web/api"
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/oklog/ulid/v2"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
func (app *App) GetID(w http.ResponseWriter, r *http.Request) (api.Blog, error) {
|
|
ctx := r.Context()
|
|
id, err := ulid.Parse(chi.URLParamFromCtx(ctx, "blogID"))
|
|
if err != nil {
|
|
return api.Blog{}, api.Error{Code: api.ErrBlogNotFound}
|
|
}
|
|
|
|
conn, err := app.Database.Acquire(ctx)
|
|
if err != nil {
|
|
log.Err(err).Msg("acquiring connection")
|
|
return api.Blog{}, err
|
|
}
|
|
defer conn.Release()
|
|
|
|
blog, err := app.Blog(conn).ByID(ctx, id)
|
|
if err != nil {
|
|
if err == sql.ErrNotFound {
|
|
return api.Blog{}, api.Error{Code: api.ErrBlogNotFound}
|
|
}
|
|
|
|
log.Err(err).Str("id", id.String()).Msg("fetching blog from database")
|
|
return api.Blog{}, err
|
|
}
|
|
|
|
acct, err := app.Account(conn).ByID(ctx, blog.AccountID)
|
|
if err != nil {
|
|
log.Err(err).Str("id", blog.AccountID.String()).Msg("fetching account from database")
|
|
return api.Blog{}, err
|
|
}
|
|
|
|
return api.DBBlogToBlog(blog, acct), nil
|
|
}
|
|
|
|
func (app *App) LookupName(w http.ResponseWriter, r *http.Request) (api.Blog, error) {
|
|
ctx := r.Context()
|
|
name := chi.URLParamFromCtx(ctx, "blogName")
|
|
|
|
conn, err := app.Database.Acquire(ctx)
|
|
if err != nil {
|
|
log.Err(err).Msg("acquiring connection")
|
|
return api.Blog{}, err
|
|
}
|
|
defer conn.Release()
|
|
|
|
blog, err := app.Blog(conn).ByName(ctx, name, "")
|
|
if err != nil {
|
|
if err == sql.ErrNotFound {
|
|
return api.Blog{}, api.Error{Code: api.ErrBlogNotFound}
|
|
}
|
|
|
|
log.Err(err).Str("name", name).Msg("fetching blog from database")
|
|
return api.Blog{}, err
|
|
}
|
|
|
|
acct, err := app.Account(conn).ByID(ctx, blog.AccountID)
|
|
if err != nil {
|
|
log.Err(err).Str("id", blog.AccountID.String()).Msg("fetching account from database")
|
|
return api.Blog{}, err
|
|
}
|
|
|
|
return api.DBBlogToBlog(blog, acct), nil
|
|
}
|