Ejemplo n.º 1
0
func (r Repository) SaveAllArticles(articles []*entity.Article) error {
	tx := r.DB.Begin()
	for i, a := range articles {
		article := entity.Article{ID: a.ID}
		tx.Preload("Images").Preload("Crawl").FirstOrCreate(&article)

		article.Ordering = len(articles) - 1 - i
		article.Title = a.Title
		article.URL = a.URL
		article.Preview = a.Preview

		author := entity.Author{}
		tx.First(&author, "name = ?", strings.TrimSpace(a.Author.Name))
		if author.ID == 0 {
			r.Logger.Log("msg", "Can't find author for article ", "author", a.Author.Name, "article", a.URL)
			continue
		}
		article.AuthorID = author.ID

		for _, i := range a.Images {
			article.AddImage(i)
		}

		if article.Crawl.ID == 0 {
			article.Crawl = entity.Crawl{Next: time.Now()}
		}

		tx.Save(&article)
	}
	tx.Commit()

	return nil
}