PageRenderTime 2900ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/storage/item.go

https://github.com/facette/facette
Go | 58 lines | 41 code | 13 blank | 4 comment | 13 complexity | afea719d315711b678022b830528ab2f MD5 | raw file
  1. package storage
  2. import (
  3. "time"
  4. "github.com/hashicorp/go-uuid"
  5. "github.com/jinzhu/gorm"
  6. )
  7. // Item represents a storage item instance.
  8. type Item struct {
  9. Type string `gorm:"-" json:"type,omitempty"`
  10. ID string `gorm:"type:varchar(36);not null;primary_key" json:"id"`
  11. Name string `gorm:"type:varchar(128);not null;unique_index" json:"name"`
  12. Description *string `gorm:"type:text" json:"description"`
  13. Created time.Time `gorm:"not null;default:current_timestamp" json:"created"`
  14. Modified time.Time `gorm:"not null;default:current_timestamp" json:"modified"`
  15. storage *Storage
  16. }
  17. // BeforeSave handles the ORM 'BeforeSave' callback.
  18. func (i *Item) BeforeSave(scope *gorm.Scope) error {
  19. if i.ID == "" {
  20. id, err := uuid.GenerateUUID()
  21. if err != nil {
  22. return err
  23. }
  24. scope.SetColumn("ID", id)
  25. } else if _, err := uuid.ParseUUID(i.ID); err != nil {
  26. return ErrInvalidID
  27. }
  28. if !nameRegexp.MatchString(i.Name) {
  29. return ErrInvalidName
  30. }
  31. now := time.Now().UTC().Round(time.Second)
  32. if i.Created.IsZero() {
  33. scope.SetColumn("Created", now)
  34. }
  35. scope.SetColumn("Modified", now)
  36. // Ensure optional fields are null if empty
  37. if i.Description != nil && *i.Description == "" {
  38. scope.SetColumn("Description", nil)
  39. }
  40. return nil
  41. }
  42. // SetStorage sets the item internal storage reference.
  43. func (i *Item) SetStorage(s *Storage) {
  44. i.storage = s
  45. }