/
files_repo.go
87 lines (78 loc) · 1.75 KB
/
files_repo.go
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 repositories
import (
"context"
"github.com/ugent-library/deliver/ent"
"github.com/ugent-library/deliver/ent/file"
"github.com/ugent-library/deliver/models"
)
type FilesRepo struct {
client *ent.Client
}
func (r *FilesRepo) Create(ctx context.Context, f *models.File) error {
if err := f.Validate(); err != nil {
return err
}
row, err := r.client.File.Create().
SetID(f.ID).
SetFolderID(f.FolderID).
SetMd5(f.MD5).
SetName(f.Name).
SetContentType(f.ContentType).
SetSize(f.Size).
Save(ctx)
if err != nil {
return err
}
*f = *rowToFile(row)
return nil
}
func (r *FilesRepo) Exists(ctx context.Context, id string) (bool, error) {
return r.client.File.Query().
Where(file.IDEQ(id)).
Exist(ctx)
}
func (r *FilesRepo) Get(ctx context.Context, id string) (*models.File, error) {
row, err := r.client.File.Query().
Where(file.IDEQ(id)).
WithFolder(func(q *ent.FolderQuery) {
q.WithSpace()
}).
First(ctx)
if ent.IsNotFound(err) {
return nil, models.ErrNotFound
}
if err != nil {
return nil, err
}
return rowToFile(row), nil
}
func (r *FilesRepo) Delete(ctx context.Context, id string) error {
err := r.client.File.
DeleteOneID(id).
Exec(ctx)
return err
}
func (r *FilesRepo) AddDownload(ctx context.Context, id string) error {
err := r.client.File.
UpdateOneID(id).
AddDownloads(1).
Exec(ctx)
return err
}
func rowToFile(row *ent.File) *models.File {
f := &models.File{
ID: row.ID,
FolderID: row.FolderID,
MD5: row.Md5,
Name: row.Name,
Size: row.Size,
ContentType: row.ContentType,
Downloads: row.Downloads,
CreatedAt: row.CreatedAt,
UpdatedAt: row.UpdatedAt,
}
if row.Edges.Folder != nil {
f.Folder = rowToFolder(row.Edges.Folder)
}
return f
}