Browse Source

Added EnsureTag function that finds or creates.

master
Gisle Aune 7 years ago
parent
commit
98c813bff5
  1. 25
      model/tag.go
  2. 32
      model/tag_test.go

25
model/tag.go

@ -139,8 +139,29 @@ func FindTag(key string, id string) (*Tag, error) {
return tag, nil return tag, nil
} }
// ListTags finds all the tags, without filter. If it hits
// the tag cache, it will copy it making it safe to modify
// EnsureTag finds or creates a tag.
func EnsureTag(tagType, tagName string) (*Tag, error) {
// Try to find it first
tag, err := FindTag("name", tagName)
if err != nil && err.Error() != "not found" { // You saw nothing
return nil, err
}
// Failing that, make it
if tag == nil {
tag = new(Tag)
tag.Type = tagType
tag.Name = tagName
err = tag.Insert()
if err != nil {
return nil, err
}
}
return tag, nil
}
// ListTags finds all the tags, without filter.
func ListTags() ([]Tag, error) { func ListTags() ([]Tag, error) {
db := server.Main.DB db := server.Main.DB

32
model/tag_test.go

@ -13,7 +13,7 @@ func TestTag(t *testing.T) {
} }
var testTag *Tag var testTag *Tag
name := "Te'Eryvi"
name := "Te'Eryvi (Test)"
id := "" id := ""
t.Run("Insert", func(t *testing.T) { t.Run("Insert", func(t *testing.T) {
@ -187,6 +187,36 @@ func TestTag(t *testing.T) {
} }
}) })
t.Run("EnsureTag", func(t *testing.T) {
tag, err := EnsureTag("Character", "Renala T'Iavay (Test)")
if err != nil {
t.Error(err)
return
}
err = tag.Delete()
if err != nil {
t.Error(err)
return
}
if tag.ID == testTag.ID {
t.Error("Ensured tag matched old tag")
return
}
tag2, err := EnsureTag(testTag.Type, testTag.Name)
if err != nil {
t.Error(err)
return
}
if tag2.ID != testTag.ID {
t.Error("Second ensured tag did not match testTag")
return
}
})
t.Run("Delete", func(t *testing.T) { t.Run("Delete", func(t *testing.T) {
if testTag == nil { if testTag == nil {
t.Error("No tag to delete") t.Error("No tag to delete")

Loading…
Cancel
Save