66 lines
1.3 KiB
Go
66 lines
1.3 KiB
Go
package posts
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"lmika.dev/lmika/weiro/models"
|
|
"lmika.dev/lmika/weiro/providers/db"
|
|
)
|
|
|
|
type CreatePostParams struct {
|
|
GUID string `form:"guid" json:"guid"`
|
|
Title string `form:"title" json:"title"`
|
|
Body string `form:"body" json:"body"`
|
|
}
|
|
|
|
func (s *Service) PublishPost(ctx context.Context, params CreatePostParams) (*models.Post, error) {
|
|
site, ok := models.GetSite(ctx)
|
|
if !ok {
|
|
return nil, models.SiteRequiredError
|
|
}
|
|
|
|
post, err := s.fetchOrCreatePost(ctx, site, params)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
post.Title = params.Title
|
|
post.Body = params.Body
|
|
post.PublishedAt = time.Now()
|
|
post.Slug = post.BestSlug()
|
|
|
|
if err := s.db.SavePost(ctx, post); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// TODO: do on separate thread
|
|
if err := s.publisher.Publish(ctx, site); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return post, nil
|
|
}
|
|
|
|
func (s *Service) fetchOrCreatePost(ctx context.Context, site models.Site, params CreatePostParams) (*models.Post, error) {
|
|
post, err := s.db.SelectPostByGUID(ctx, params.GUID)
|
|
if err == nil {
|
|
if post.SiteID != site.ID {
|
|
return nil, models.NotFoundError
|
|
}
|
|
|
|
return post, nil
|
|
} else if !db.ErrorIsNoRows(err) {
|
|
return nil, err
|
|
}
|
|
|
|
post = &models.Post{
|
|
SiteID: site.ID,
|
|
GUID: params.GUID,
|
|
Title: params.Title,
|
|
Body: params.Body,
|
|
CreatedAt: time.Now(),
|
|
}
|
|
return post, nil
|
|
}
|