github.com/bitcubate/cryptojournal@v1.2.5-0.20171102134152-f578b3d788ab/src/lib/resource/query.go (about) 1 package resource 2 3 import ( 4 "time" 5 6 "github.com/fragmenta/query" 7 ) 8 9 // Query creates a new query relation referencing this specific resource by id. 10 func (r *Base) Query() *query.Query { 11 return query.New(r.Table(), r.PrimaryKey()).Where("id=?", r.ID) 12 } 13 14 // ValidateParams allows only those params by AllowedParams() 15 // to perform more sophisticated validation override it. 16 func (r *Base) ValidateParams(params map[string]string, allowed []string) map[string]string { 17 18 for k := range params { 19 paramAllowed := false 20 for _, v := range allowed { 21 if k == v { 22 paramAllowed = true 23 } 24 } 25 if !paramAllowed { 26 delete(params, k) 27 } 28 } 29 return params 30 } 31 32 // Create inserts a new database record and returns the id or an error 33 func (r *Base) Create(params map[string]string) (int64, error) { 34 35 // Make sure updated_at and created_at are set to the current time 36 now := query.TimeString(time.Now().UTC()) 37 params["created_at"] = now 38 params["updated_at"] = now 39 40 // Insert a record into the database 41 id, err := query.New(r.Table(), r.PrimaryKey()).Insert(params) 42 return id, err 43 } 44 45 // Update the database record for this resource with the given params. 46 func (r *Base) Update(params map[string]string) error { 47 48 // Make sure updated_at is set to the current time 49 now := query.TimeString(time.Now().UTC()) 50 params["updated_at"] = now 51 52 return r.Query().Update(params) 53 } 54 55 // Destroy deletes this resource by removing the database record. 56 func (r *Base) Destroy() error { 57 return r.Query().Delete() 58 }