mercury/web/api/posts/get_post.go

45 lines
1.1 KiB
Go
Raw Normal View History

package posts
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.Post, error) {
ctx := r.Context()
id, err := ulid.Parse(chi.URLParamFromCtx(ctx, "postID"))
if err != nil {
return api.Post{}, api.Error{Code: api.ErrBlogNotFound}
}
conn, err := app.Database.Acquire(ctx)
if err != nil {
log.Err(err).Msg("acquiring connection")
return api.Post{}, err
}
defer conn.Release()
post, err := app.Post(conn).ByID(ctx, id)
if err != nil {
if err == sql.ErrNotFound {
return api.Post{}, api.Error{Code: api.ErrBlogNotFound}
}
log.Err(err).Str("id", id.String()).Msg("fetching post from database")
return api.Post{}, err
}
blog, err := app.Blog(conn).ByID(ctx, post.BlogID)
if err != nil {
log.Err(err).Str("id", post.BlogID.String()).Msg("fetching blog from database")
return api.Post{}, err
}
return api.DBPostToPost(post, blog), nil
}