contacts_model.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "sync"
  8. )
  9. var (
  10. ContactsFile = "contacts.json"
  11. )
  12. type (
  13. Contacts []Contact
  14. ContactsStore struct {
  15. sync.Mutex
  16. data map[int]Contact
  17. }
  18. )
  19. func NewContactsStore() (*ContactsStore, error) {
  20. cs := ContactsStore{
  21. data: make(map[int]Contact),
  22. }
  23. if err := cs.Load(); err != nil {
  24. return nil, err
  25. }
  26. return &cs, nil
  27. }
  28. func (cs *ContactsStore) Get(search string) Contacts {
  29. return make(Contacts, 0)
  30. }
  31. func (cs *ContactsStore) GetAll() Contacts {
  32. return make(Contacts, 0)
  33. }
  34. func (cs *ContactsStore) Load() error {
  35. if cs == nil {
  36. return errors.New("cannot load into nil store")
  37. }
  38. bs, err := os.ReadFile(ContactsFile)
  39. if err != nil {
  40. return fmt.Errorf("reading file: %w", err)
  41. }
  42. contacts := make(Contacts, 0)
  43. if err := json.Unmarshal(bs, &contacts); err != nil {
  44. return fmt.Errorf("unmarshalling file: %w", err)
  45. }
  46. cs.Lock()
  47. defer cs.Unlock()
  48. for _, contact := range contacts {
  49. cs.data[contact.ID] = contact
  50. }
  51. return nil
  52. }
  53. type Contact struct {
  54. ID int `json:"id"`
  55. First string `json:"first"`
  56. Last string `json:"last"`
  57. Phone string `json:"phone"`
  58. Email string `json:"email"`
  59. errors map[string]string
  60. }