Closes #5 Reviewed-on: phoenix/textsender-api#7 Co-authored-by: phoenix <kundeng00@pm.me> Co-committed-by: phoenix <kundeng00@pm.me>
118 lines
2.3 KiB
Go
118 lines
2.3 KiB
Go
package handler
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"sync"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"git.kundeng.us/phoenix/textsender-models/pkg/contact"
|
|
)
|
|
|
|
type Key struct {
|
|
PhoneNumber string
|
|
UserId uuid.UUID
|
|
}
|
|
|
|
type MockContactStore struct {
|
|
Contacts map[uuid.UUID]*contact.Contact
|
|
ContactsByKey map[Key]*contact.Contact
|
|
mu sync.RWMutex
|
|
Error error // Optional: simulate errors
|
|
}
|
|
|
|
func NewMockContactStore() *MockContactStore {
|
|
return &MockContactStore{
|
|
Contacts: make(map[uuid.UUID]*contact.Contact),
|
|
ContactsByKey: make(map[Key]*contact.Contact),
|
|
}
|
|
}
|
|
|
|
func (m *MockContactStore) CreateContact(ctx context.Context, con *contact.Contact) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
|
|
if m.Error != nil {
|
|
return m.Error
|
|
}
|
|
|
|
if con.Id == uuid.Nil {
|
|
con.Id = uuid.New()
|
|
}
|
|
|
|
key := Key{PhoneNumber: con.PhoneNumber, UserId: con.UserId}
|
|
if _, exists := m.ContactsByKey[key]; exists {
|
|
return errors.New("Contact with phone number already exists")
|
|
}
|
|
|
|
m.Contacts[con.Id] = con
|
|
m.ContactsByKey[key] = con
|
|
return nil
|
|
}
|
|
|
|
func (m *MockContactStore) GetContactByID(ctx context.Context, id uuid.UUID) (*contact.Contact, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
|
|
if m.Error != nil {
|
|
return nil, m.Error
|
|
}
|
|
|
|
if m.Error != nil {
|
|
return nil, m.Error
|
|
}
|
|
|
|
con, exists := m.Contacts[id]
|
|
if !exists {
|
|
return nil, errors.New("Contact not found")
|
|
}
|
|
|
|
return con, nil
|
|
}
|
|
|
|
func (m *MockContactStore) GetContactByPhone(ctx context.Context, phoneNumber string, userId uuid.UUID) (*contact.Contact, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
|
|
if m.Error != nil {
|
|
return nil, m.Error
|
|
}
|
|
|
|
con, exists := m.ContactsByKey[Key{PhoneNumber: phoneNumber, UserId: userId}]
|
|
if !exists {
|
|
return nil, errors.New("Contact not found")
|
|
}
|
|
|
|
return con, nil
|
|
}
|
|
|
|
func (m *MockContactStore) GetAllContacts(ctx context.Context) ([]*contact.Contact, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
|
|
if m.Error != nil {
|
|
return nil, m.Error
|
|
}
|
|
|
|
cons := make([]*contact.Contact, 0, len(m.Contacts))
|
|
for _, con := range m.Contacts {
|
|
cons = append(cons, con)
|
|
}
|
|
|
|
return cons, nil
|
|
}
|
|
|
|
func (m *MockContactStore) ContactExists(ctx context.Context, phoneNumber string, userId uuid.UUID) (bool, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
|
|
if m.Error != nil {
|
|
return false, m.Error
|
|
}
|
|
|
|
_, exists := m.ContactsByKey[Key{PhoneNumber: phoneNumber, UserId: userId}]
|
|
|
|
return exists, nil
|
|
}
|