add methods in Repository and Model for importing data
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"kontor-api-gin/internal/models"
|
||||
"log/slog"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type MediaArticleRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (repository *MediaArticleRepository) Import(dtos models.MediaArticleDTOList) {
|
||||
slog.Info("MediaArticleRepository#Import")
|
||||
for index, dto := range dtos {
|
||||
slog.Info("importing", "index", index, "profile", dto)
|
||||
model := dto.ConvertDTOToModel()
|
||||
existing_item := models.MediaArticle{ID: dto.ID}
|
||||
result_existing := repository.db.First(&existing_item)
|
||||
if result_existing.Error != nil {
|
||||
slog.Info("check existing id: not found - inserting")
|
||||
result := repository.db.Create(&model)
|
||||
if result.Error != nil {
|
||||
slog.Info("error during import", "error", result.Error.Error())
|
||||
}
|
||||
} else {
|
||||
slog.Info("check existing id: found - updating")
|
||||
result := repository.db.Save(&model)
|
||||
if result.Error != nil {
|
||||
slog.Info("error during updating", "error", result.Error.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func NewMediaArticleRepository(db *gorm.DB) *MediaArticleRepository {
|
||||
repo := &MediaArticleRepository{db: db}
|
||||
return repo
|
||||
}
|
||||
|
||||
func (repository *MediaArticleRepository) FindAll(context context.Context) ([]models.MediaArticle, error) {
|
||||
var articles []models.MediaArticle
|
||||
|
||||
result := repository.db.Find(&articles)
|
||||
slog.Info("MediaArticleRepository#FindAll", "count", result.RowsAffected)
|
||||
|
||||
return articles, nil
|
||||
}
|
||||
|
||||
func (repository *MediaArticleRepository) GetById(context context.Context, id string) (*models.MediaArticle, error) {
|
||||
var file = models.MediaArticle{ID: id}
|
||||
slog.Info("MediaArticleRepository#GetById", "id", id)
|
||||
result := repository.db.First(&file)
|
||||
if result.Error != nil {
|
||||
slog.Info("MediaArticleRepository#GetById", "error", result.Error.Error())
|
||||
return nil, result.Error
|
||||
}
|
||||
return &file, result.Error
|
||||
}
|
||||
|
||||
func (repository *MediaArticleRepository) Add(context context.Context, url string) (*models.MediaArticle, error) {
|
||||
slog.Info("MediaArticleRepository#Add", "url", url)
|
||||
return nil, fmt.Errorf("unimplemented method MediaArticleRepository#Add")
|
||||
}
|
||||
|
||||
func (repository *MediaArticleRepository) Delete(context context.Context, id string) error {
|
||||
var file = models.MediaArticle{ID: id}
|
||||
slog.Info("MediaArticleRepository#Delete", "id", id)
|
||||
result := repository.db.Delete(&file)
|
||||
if result.Error != nil {
|
||||
slog.Info("MediaArticleRepository#Delete", "error", result.Error.Error())
|
||||
}
|
||||
return result.Error
|
||||
}
|
||||
Reference in New Issue
Block a user