github.com/bitcubate/cryptojournal@v1.2.5-0.20171102134152-f578b3d788ab/src/lib/resource/resource.go (about) 1 // Package resource provides some shared behaviour for resources, and basic CRUD and URL helpers. 2 package resource 3 4 import ( 5 "crypto/sha256" 6 "fmt" 7 "time" 8 9 "github.com/fragmenta/auth" 10 ) 11 12 // Base defines shared fields and behaviour for resources. 13 type Base struct { 14 // ID is the default primary key of the resource. 15 ID int64 16 17 // CreatedAt stores the creation time of the resource. 18 CreatedAt time.Time 19 20 // UpdatedAt stores the last update time of the resource. 21 UpdatedAt time.Time 22 23 // TableName is used for database queries and urls. 24 TableName string 25 26 // KeyName is used for database queries as the primary key. 27 KeyName string 28 } 29 30 // String returns a string representation of the resource 31 func (r *Base) String() string { 32 return fmt.Sprintf("%s/%d", r.TableName, r.ID) 33 } 34 35 // Queryable interface 36 37 // Table returns the table name for this object 38 func (r *Base) Table() string { 39 return r.TableName 40 } 41 42 // PrimaryKey returns the id for primary key by default - used by query 43 func (r *Base) PrimaryKey() string { 44 return r.KeyName 45 } 46 47 // PrimaryKeyValue returns the unique id 48 func (r *Base) PrimaryKeyValue() int64 { 49 return r.ID 50 } 51 52 // Selectable interface 53 54 // SelectName returns our name for select menus 55 func (r *Base) SelectName() string { 56 return fmt.Sprintf("%s-%d", r.TableName, r.ID) 57 } 58 59 // SelectValue returns our value for select options 60 func (r *Base) SelectValue() string { 61 return fmt.Sprintf("%d", r.ID) 62 } 63 64 // Cacheable interface 65 66 // CacheKey generates a cache key for this resource 67 // based on the TableName, ID and UpdatedAt 68 func (r *Base) CacheKey() string { 69 key := []byte(fmt.Sprintf("%s/%d/%s", r.TableName, r.ID, r.UpdatedAt)) 70 hash := sha256.Sum256(key) 71 return auth.BytesToHex(hash[:32]) 72 } 73 74 // can.Resource interface 75 76 // OwnedBy returns true if the user id passed in owns this resource. 77 func (r *Base) OwnedBy(uid int64) bool { 78 return false 79 } 80 81 // ResourceID returns a key unique to this resource (we use table). 82 func (r *Base) ResourceID() string { 83 return r.TableName 84 }