|
| 1 | +# changeset |
| 2 | + |
| 3 | +[](https://godoc.org/github.com/Fs02/changeset) |
| 4 | +[](https://travis-ci.org/Fs02/changeset) |
| 5 | +[](https://goreportcard.com/report/github.com/Fs02/changeset) |
| 6 | +[](https://gocover.io/github.com/Fs02/changeset) |
| 7 | + |
| 8 | +Changeset mutator for [REL](https://github.com/Fs02/rel). Changesets allow filtering, casting, validation and definition of constraints when manipulating structs. |
| 9 | + |
| 10 | +## Install |
| 11 | + |
| 12 | +```bash |
| 13 | +go get github.com/Fs02/changeset |
| 14 | +``` |
| 15 | + |
| 16 | +## Example |
| 17 | + |
| 18 | +```golang |
| 19 | +package main |
| 20 | + |
| 21 | +import ( |
| 22 | +"time" |
| 23 | + |
| 24 | +"github.com/Fs02/rel" |
| 25 | +"github.com/Fs02/rel/adapter/mysql" |
| 26 | +"github.com/Fs02/changeset" |
| 27 | +"github.com/Fs02/changeset/params" |
| 28 | +) |
| 29 | + |
| 30 | +type Product struct { |
| 31 | +ID int |
| 32 | +Name string |
| 33 | +Price int |
| 34 | +CreatedAt time.Time |
| 35 | +UpdatedAt time.Time |
| 36 | +} |
| 37 | + |
| 38 | +// ChangeProduct prepares data before database operation. |
| 39 | +// Such as casting value to appropriate types and perform validations. |
| 40 | +func ChangeProduct(product interface{}, params params.Params) *changeset.Changeset { |
| 41 | +ch := changeset.Cast(product, params, []string{"name", "price"}) |
| 42 | +changeset.ValidateRequired(ch, []string{"name", "price"}) |
| 43 | +changeset.ValidateMin(ch, "price", 100) |
| 44 | +return ch |
| 45 | +} |
| 46 | + |
| 47 | +func main() { |
| 48 | + // initialize mysql adapter. |
| 49 | + adapter, _ := mysql.Open(dsn) |
| 50 | + defer adapter.Close() |
| 51 | + |
| 52 | + // initialize rel's repo. |
| 53 | + repo := rel.New(adapter) |
| 54 | + |
| 55 | +var product Product |
| 56 | + |
| 57 | +// Inserting Products. |
| 58 | +// Changeset is used when creating or updating your data. |
| 59 | +ch := ChangeProduct(product, params.Map{ |
| 60 | +"name": "shampoo", |
| 61 | +"price": 1000, |
| 62 | +}) |
| 63 | + |
| 64 | +if ch.Error() != nil { |
| 65 | +// handle error |
| 66 | +} |
| 67 | + |
| 68 | +// Changeset can also be created directly from json string. |
| 69 | +jsonch := ChangeProduct(product, params.ParseJSON(`{ |
| 70 | +"name": "soap", |
| 71 | +"price": 2000, |
| 72 | +}`)) |
| 73 | + |
| 74 | +// Create products with changeset and return the result to &product, |
| 75 | +if err := repo.Insert(context.TODO(), &product, ch); err != nil { |
| 76 | +// handle error |
| 77 | +} |
| 78 | +} |
| 79 | +``` |
| 80 | + |
| 81 | +## License |
| 82 | + |
| 83 | +Released under the [MIT License](https://github.com/Fs02/grimoire/blob/master/LICENSE) |
0 commit comments