-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler_agg.go
More file actions
87 lines (75 loc) · 1.94 KB
/
Copy pathhandler_agg.go
File metadata and controls
87 lines (75 loc) · 1.94 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"context"
"database/sql"
"fmt"
"log"
"strings"
"time"
"github.com/VoluteTech/gator/internal/database"
"github.com/google/uuid"
)
func handlerAgg(s *state, cmd command) error {
if len(cmd.Args) < 1 || len(cmd.Args) > 2 {
return fmt.Errorf("usage: %v <time_between_reqs>", cmd.Name)
}
timeBetweenReqs, err := time.ParseDuration(cmd.Args[0])
if err != nil {
return fmt.Errorf("invalid duration: %w", err)
}
log.Printf("Collecting feeds every %v", timeBetweenReqs)
ticker := time.NewTicker(timeBetweenReqs)
for ; ; <-ticker.C {
scrapeFeeds(s)
}
}
func scrapeFeeds(s *state) {
feed, err := s.db.GetNextFeedToFetch(context.Background())
if err != nil {
log.Println("couldn't get next feeds to fetch")
return
}
log.Println("Found a feed to fetch !")
scrapeFeed(s.db, feed)
}
func scrapeFeed(db *database.Queries, feed database.Feed) {
_, err := db.MarkFeedFetched(context.Background(), feed.ID)
if err != nil {
log.Printf("couldn't mark the feed %s fetched: %v", feed.Name, err)
return
}
feedData, err := fetchFeed(context.Background(), feed.Url)
if err != nil {
log.Printf("couldn't collect feed %s: %v", feed.Name, err)
}
for _, item := range feedData.Channel.Item {
publishedAt := sql.NullTime{}
if t, err := time.Parse(time.RFC1123Z, item.PubDate); err == nil {
publishedAt = sql.NullTime{
Time: t,
Valid: true,
}
}
_, err := db.CreatePost(context.Background(), database.CreatePostParams{
ID: uuid.New(),
CreatedAt: time.Now().UTC(),
UpdatedAt: time.Now().UTC(),
FeedID: feed.ID,
Title: item.Title,
Description: sql.NullString{
String: item.Description,
Valid: true,
},
Url: item.Link,
PublishedAt: publishedAt,
})
if err != nil {
if strings.Contains(err.Error(), "duplicate key value violates unique constraint") {
continue
}
log.Printf("could not save the post to the db: %v", err)
continue
}
}
fmt.Println("Posts saved !")
}