gte/internal/process/fetch.go

66 lines
1.3 KiB
Go
Raw Normal View History

2021-06-25 09:14:27 +02:00
package process
import (
"errors"
"fmt"
"time"
2021-09-19 11:59:26 +02:00
"ewintr.nl/gte/internal/storage"
"ewintr.nl/gte/internal/task"
2021-06-25 09:14:27 +02:00
)
var (
2021-09-03 07:12:16 +02:00
ErrFetchProcess = errors.New("could not fetch tasks")
2021-06-25 09:14:27 +02:00
)
2021-09-03 07:12:16 +02:00
// Fetch fetches all tasks in regular folders from the remote repository and overwrites what is stored locally
type Fetch struct {
2022-10-25 15:59:09 +02:00
remote *storage.RemoteRepository
local storage.LocalRepository
folders []string
2021-06-25 09:14:27 +02:00
}
2021-09-03 07:12:16 +02:00
type FetchResult struct {
2021-06-25 09:14:27 +02:00
Duration string `json:"duration"`
Count int `json:"count"`
}
2022-10-25 15:59:09 +02:00
func NewFetch(remote *storage.RemoteRepository, local storage.LocalRepository, folders ...string) *Fetch {
if len(folders) == 0 {
folders = task.KnownFolders
}
2021-09-03 07:12:16 +02:00
return &Fetch{
2022-10-25 15:59:09 +02:00
remote: remote,
local: local,
folders: folders,
2021-06-25 09:14:27 +02:00
}
}
2021-09-03 07:12:16 +02:00
func (s *Fetch) Process() (*FetchResult, error) {
2021-06-25 09:14:27 +02:00
start := time.Now()
tasks := []*task.Task{}
2022-10-25 15:59:09 +02:00
for _, folder := range s.folders {
2021-06-25 09:14:27 +02:00
if folder == task.FOLDER_INBOX {
continue
}
folderTasks, err := s.remote.FindAll(folder)
if err != nil {
2021-09-03 07:12:16 +02:00
return &FetchResult{}, fmt.Errorf("%w: %v", ErrFetchProcess, err)
2021-06-25 09:14:27 +02:00
}
for _, t := range folderTasks {
tasks = append(tasks, t)
}
}
if err := s.local.SetTasks(tasks); err != nil {
2021-09-03 07:12:16 +02:00
return &FetchResult{}, fmt.Errorf("%w: %v", ErrFetchProcess, err)
2021-06-25 09:14:27 +02:00
}
2021-09-03 07:12:16 +02:00
return &FetchResult{
2021-06-25 09:14:27 +02:00
Duration: time.Since(start).String(),
Count: len(tasks),
}, nil
}