- Added the new post frontend - Hooked up publishing of posts to the site publisher - Added an site exporter as a publishing target
79 lines
1.6 KiB
Go
79 lines
1.6 KiB
Go
package posts
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"lmika.dev/lmika/weiro/models"
|
|
"lmika.dev/lmika/weiro/providers/db"
|
|
"lmika.dev/lmika/weiro/services/publisher"
|
|
)
|
|
|
|
type Service struct {
|
|
db *db.Provider
|
|
publisher *publisher.Publisher
|
|
}
|
|
|
|
func New(db *db.Provider, publisher *publisher.Publisher) *Service {
|
|
return &Service{
|
|
db: db,
|
|
publisher: publisher,
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|