The backend for the AiteStory website
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
1.5 KiB

7 years ago
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "git.aiterp.net/AiteRP/aitestory/server"
  6. "git.aiterp.net/gisle/wrouter/generate"
  7. )
  8. // TagTypes are the allowed values for Tag.Type
  9. var TagTypes = []string{
  10. "Location",
  11. "Character",
  12. "Event",
  13. "Organization",
  14. "Source",
  15. }
  16. // Tag describes a tag
  17. type Tag struct {
  18. ID string
  19. Type string
  20. Name string
  21. }
  22. // Insert adds the tag to the database, giving it a new unique ID
  23. func (tag *Tag) Insert() error {
  24. db := server.Main.DB
  25. // Validate tag type
  26. validType := false
  27. for _, tagType := range TagTypes {
  28. if tagType == tag.Type {
  29. validType = true
  30. break
  31. }
  32. }
  33. if !validType {
  34. return fmt.Errorf("\"%s\" is not a valid tag type", tag.Type)
  35. }
  36. // Validate tag name
  37. if len(tag.Name) == 0 {
  38. return errors.New("Tag name is empty")
  39. }
  40. // Generate an ID if none exists
  41. if tag.ID == "" {
  42. tag.ID = generate.ID()
  43. }
  44. // Do the thing
  45. _, err := db.Exec("INSERT INTO `tag` (id,type,name,disabled) VALUES (?,?,?,false)", tag.ID, tag.Type, tag.Name)
  46. if err != nil {
  47. return err
  48. }
  49. return nil
  50. }
  51. // ListTags finds all the tags, without filter. If it hits
  52. // the tag cache, it will copy it making it safe to modify
  53. func ListTags() ([]Tag, error) {
  54. db := server.Main.DB
  55. // Read from the database
  56. rows, err := db.Query("SELECT id,type,name FROM `tag` WHERE disabled=false")
  57. if err != nil {
  58. return nil, err
  59. }
  60. defer rows.Close()
  61. results := make([]Tag, 0, 64)
  62. for rows.Next() {
  63. tag := Tag{}
  64. rows.Scan(&tag.ID, &tag.Type, &tag.Name)
  65. results = append(results, tag)
  66. }
  67. return results, nil
  68. }