-
Notifications
You must be signed in to change notification settings - Fork 0
/
add_tags.go
71 lines (57 loc) · 1.71 KB
/
add_tags.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
package lib
import (
"fmt"
"github.com/samber/lo"
)
// addTagsOptions are the optional arguments for AddTags.
type addTagsOptions struct {
db NullString
}
// DefaultAddTagsOptions are the default options for AddTags.
func DefaultAddTagsOptions() addTagsOptions {
return addTagsOptions{}
}
// WithDB sets the location of the bookmarks database.
func (o *addTagsOptions) WithDB(db string) {
o.db = NullStringFrom(db)
}
// AddTags adds tags to a bookmark in the bookmarks database.
func AddTags(id string, tags []string, options addTagsOptions) (Book, error) {
return queryWithTransaction(options.db, connectDB, func(tx transaction) (Book, error) {
var book Book
books, err := getBooksDB(tx, getBooksDBArgs{
idFilter: id,
includeBooks: true,
})
if err != nil {
return book, fmt.Errorf("error getting tags while adding tags: %w", err)
}
if len(books) != 1 || books[0].IsFolder {
return book, ErrBookNotFound
}
if err := validateTags(tags, books[0].Tags); err != nil {
return book, fmt.Errorf("tags validation failed while adding tags: %w", err)
}
existingTags, err := getTagsDB(tx, getTagsDBArgs{
tagsFilter: tags,
})
if err != nil {
return book, err
}
tagsToAdd, _ := lo.Difference(tags, existingTags)
if err = addTagsDB(tx, tagsToAdd); err != nil {
return book, fmt.Errorf("error while adding tags: %w", err)
}
if err = linkTagsDB(tx, id, tags); err != nil {
return book, fmt.Errorf("error linking tags while adding tags: %w", err)
}
books, err = getBooksDB(tx, getBooksDBArgs{
idFilter: id,
includeBooks: true,
})
if err != nil {
return book, fmt.Errorf("error getting bookmarks while adding tags: %w", err)
}
return books[0], nil
})
}