aboutsummaryrefslogtreecommitdiff
path: root/cmd/mi/models/blogpost.go
blob: 553be3b114440ac51092a41d4417f1f8c8666599 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package models

import (
	"context"
	"time"

	"gorm.io/gorm"
	"within.website/x/proto/external/jsonfeed"
)

// Blogpost is a single blogpost from a JSON Feed.
//
// This is tracked in the database so that the Announcer service can avoid double-posting.
type Blogpost struct {
	gorm.Model            // adds CreatedAt, UpdatedAt, DeletedAt
	ID          string    `gorm:"uniqueIndex"` // unique identifier for the blogpost
	URL         string    `gorm:"uniqueIndex"` // URL of the blogpost
	Title       string    // title of the blogpost
	BodyHTML    string    // HTML body of the blogpost
	Image       string    // URL of the image for the blogpost
	PublishedAt time.Time // when the blogpost was published
}

func (d *DAO) HasBlogpost(ctx context.Context, postURL string) (bool, error) {
	var count int64
	if err := d.db.WithContext(ctx).Model(&Blogpost{}).Where("url = ?", postURL).Count(&count).Error; err != nil {
		return false, err
	}

	return count > 0, nil
}

func (d *DAO) InsertBlogpost(ctx context.Context, post *jsonfeed.Item) (*Blogpost, error) {
	bp := &Blogpost{
		ID:          post.GetId(),
		URL:         post.GetUrl(),
		Title:       post.GetTitle(),
		BodyHTML:    post.GetContentHtml(),
		PublishedAt: post.GetDatePublished().AsTime(),
	}

	if err := d.db.WithContext(ctx).Create(bp).Error; err != nil {
		return nil, err
	}

	return bp, nil
}