105 lines
2.4 KiB
Go
105 lines
2.4 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"lmika.dev/lmika/weiro/models"
|
|
"lmika.dev/lmika/weiro/providers/db/gen/sqlgen"
|
|
)
|
|
|
|
func (db *Provider) SelectPostsOfSite(ctx context.Context, siteID int64, showDeleted bool) ([]*models.Post, error) {
|
|
var filter = ""
|
|
if showDeleted {
|
|
filter = "deleted"
|
|
}
|
|
|
|
rows, err := db.queries.SelectPostsOfSite(ctx, sqlgen.SelectPostsOfSiteParams{
|
|
SiteID: siteID,
|
|
PostFilter: filter,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
posts := make([]*models.Post, len(rows))
|
|
for i, row := range rows {
|
|
posts[i] = dbPostToPost(row)
|
|
}
|
|
return posts, nil
|
|
}
|
|
|
|
func (db *Provider) SelectPost(ctx context.Context, postID int64) (*models.Post, error) {
|
|
row, err := db.queries.SelectPost(ctx, postID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return dbPostToPost(row), nil
|
|
}
|
|
|
|
func (db *Provider) SelectPostByGUID(ctx context.Context, guid string) (*models.Post, error) {
|
|
row, err := db.queries.SelectPostByGUID(ctx, guid)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return dbPostToPost(row), nil
|
|
}
|
|
|
|
func (db *Provider) SavePost(ctx context.Context, post *models.Post) error {
|
|
if post.ID == 0 {
|
|
newID, err := db.queries.InsertPost(ctx, sqlgen.InsertPostParams{
|
|
SiteID: post.SiteID,
|
|
State: int64(post.State),
|
|
Guid: post.GUID,
|
|
Title: post.Title,
|
|
Body: post.Body,
|
|
Slug: post.Slug,
|
|
CreatedAt: timeToInt(post.CreatedAt),
|
|
UpdatedAt: timeToInt(post.UpdatedAt),
|
|
PublishedAt: timeToInt(post.PublishedAt),
|
|
DeletedAt: timeToInt(post.DeletedAt),
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
post.ID = newID
|
|
return nil
|
|
}
|
|
|
|
return db.queries.UpdatePost(ctx, sqlgen.UpdatePostParams{
|
|
ID: post.ID,
|
|
State: int64(post.State),
|
|
Title: post.Title,
|
|
Body: post.Body,
|
|
Slug: post.Slug,
|
|
UpdatedAt: timeToInt(post.UpdatedAt),
|
|
PublishedAt: timeToInt(post.PublishedAt),
|
|
DeletedAt: timeToInt(post.DeletedAt),
|
|
})
|
|
}
|
|
|
|
func dbPostToPost(row sqlgen.Post) *models.Post {
|
|
return &models.Post{
|
|
ID: row.ID,
|
|
SiteID: row.SiteID,
|
|
State: int(row.State),
|
|
GUID: row.Guid,
|
|
Title: row.Title,
|
|
Body: row.Body,
|
|
Slug: row.Slug,
|
|
CreatedAt: time.Unix(row.CreatedAt, 0).UTC(),
|
|
UpdatedAt: time.Unix(row.UpdatedAt, 0).UTC(),
|
|
PublishedAt: time.Unix(row.PublishedAt, 0).UTC(),
|
|
DeletedAt: time.Unix(row.DeletedAt, 0).UTC(),
|
|
}
|
|
}
|
|
|
|
func timeToInt(t time.Time) int64 {
|
|
if t.IsZero() {
|
|
return 0
|
|
}
|
|
return t.Unix()
|
|
}
|