feat: inserts last 10 articles into DB on feed add
This commit is contained in:
parent
0fc94606d6
commit
13ba132159
5 changed files with 84 additions and 23 deletions
61
internal/database/article.go
Normal file
61
internal/database/article.go
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Article struct {
|
||||
Name string
|
||||
Url string
|
||||
ReadAt *time.Time
|
||||
FeedId int64
|
||||
}
|
||||
|
||||
func (a Article) Insert() (int64, error) {
|
||||
result, err := db.Exec("INSERT INTO article (name, url, readAt, feedId) VALUES (?, ?, ?, ?)", a.Name, a.Url, a.ReadAt, a.FeedId)
|
||||
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
id, err := result.LastInsertId()
|
||||
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func InsertMultipleArticles(articles []Article) error {
|
||||
if len(articles) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
tx, err := db.Begin()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer tx.Rollback()
|
||||
|
||||
stmt, err := tx.Prepare("INSERT INTO article (name, url, readAt, feedId) VALUES (?, ?, ?, ?)")
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer stmt.Close()
|
||||
|
||||
for _, article := range articles {
|
||||
fmt.Printf("article %+v", article)
|
||||
_, err := stmt.Exec(article.Name, article.Url, article.ReadAt, article.FeedId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
|
@ -3,7 +3,6 @@ CREATE table article (
|
|||
id INTEGER PRIMARY KEY,
|
||||
name text NOT NULL,
|
||||
url text NOT NULL UNIQUE,
|
||||
read INTEGER DEFAULT 0,
|
||||
readAt text,
|
||||
feedId INTEGER,
|
||||
FOREIGN KEY (feedId) REFERENCES feed(id)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue