Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. package fake
  2.  
  3. import "sort"
  4.  
  5. type Doc struct {
  6. ID uint
  7.  
  8. Foo string
  9. Bar string
  10. }
  11.  
  12. type store map[uint]Doc
  13.  
  14. type Fake struct {
  15. stores store
  16. }
  17.  
  18. func NewFake() *Fake {
  19. stores := make(store, 5)
  20. return &Fake{stores}
  21. }
  22.  
  23. func (f *Fake) Seed(docs []Doc) {
  24.  
  25. for _, d := range docs {
  26. f.stores[d.ID] = d
  27. }
  28. }
  29.  
  30. func (f *Fake) Create(d Doc) error {
  31. f.stores[d.ID] = d
  32. return nil
  33. }
  34.  
  35. func (f *Fake) Get(id uint) Doc {
  36. return f.stores[id]
  37. }
  38.  
  39. func (f *Fake) Update(d Doc) error {
  40. if _, found := f.stores[d.ID]; found {
  41. f.stores[d.ID] = d
  42. }
  43. return nil
  44. }
  45.  
  46. func (f *Fake) Delete(id uint) error {
  47. delete(f.stores, id)
  48. return nil
  49. }
  50.  
  51. func (f *Fake) Upsert(d Doc) error {
  52. if _, found := f.stores[d.ID]; found {
  53. f.stores[d.ID] = d
  54. return nil
  55. }
  56. return f.Create(d)
  57. }
  58.  
  59. func (f *Fake) CountAll() int {
  60. return len(f.stores)
  61. }
  62.  
  63. func (f *Fake) RemoveAll() error {
  64. f.stores = make(store, 5)
  65. return nil
  66. }
  67.  
  68. func (f *Fake) All() []Doc {
  69. var docs []Doc
  70. for _, d := range f.stores {
  71. docs = append(docs, d)
  72. }
  73.  
  74. sort.Slice(docs, func(i, j int) bool {
  75. return docs[i].ID < docs[j].ID
  76. })
  77.  
  78. return docs
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement