tsk-5: Add contact (#7)
Closes #5 Reviewed-on: phoenix/textsender-api#7 Co-authored-by: phoenix <kundeng00@pm.me> Co-committed-by: phoenix <kundeng00@pm.me>
This commit is contained in:
+24
-36
@@ -1,32 +1,34 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
// "fmt"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||
"git.kundeng.us/phoenix/textsender-models/pkg/contact"
|
||||
)
|
||||
|
||||
type RequestAddContact struct {
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
UserId uuid.UUID`json:"user_id"`
|
||||
PhoneNumber string `json:"phone_number"`
|
||||
UserId uuid.UUID `json:"user_id"`
|
||||
}
|
||||
|
||||
type LoginResponse struct {
|
||||
Message string `json:"message"`
|
||||
// Data []model.Data`json:"data"`
|
||||
type AddContactResponse struct {
|
||||
Message string `json:"message"`
|
||||
Data []contact.Contact `json:"data"`
|
||||
}
|
||||
|
||||
type ContactHandler struct {
|
||||
ContactStore store.ContactStore
|
||||
}
|
||||
|
||||
/*
|
||||
func NewContactHandler(store model.Store) *ContactHandler {
|
||||
return &ContactHandler{Store: store}
|
||||
func NewContactHandler(str store.ContactStore) *ContactHandler {
|
||||
return &ContactHandler{ContactStore: str}
|
||||
}
|
||||
*/
|
||||
|
||||
func (l *ContactHandler) AddContact(w http.ResponseWriter, r *http.Request) {
|
||||
func (c *ContactHandler) AddContact(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
@@ -38,47 +40,33 @@ func (l *ContactHandler) AddContact(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
newContact := contact.Contact{PhoneNumber: req.PhoneNumber, UserId: req.UserId}
|
||||
|
||||
var statusCode int
|
||||
var resp LoginResponse
|
||||
/*
|
||||
var resp AddContactResponse
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
if exists, err := l.UserStore.UserExists(ctx, req.Username); err != nil {
|
||||
if exists, err := c.ContactStore.ContactExists(ctx, newContact.PhoneNumber, newContact.UserId); err != nil {
|
||||
fmt.Printf("Error: %v", err)
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = err.Error()
|
||||
} else {
|
||||
if !exists {
|
||||
if exists {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "Failure in user check"
|
||||
resp.Message = "Cannot create contact"
|
||||
} else {
|
||||
if user, err := l.UserStore.GetUserByUsername(ctx, req.Username); err != nil {
|
||||
if err := c.ContactStore.CreateContact(ctx, &newContact); err != nil {
|
||||
fmt.Printf("Error: %v", err)
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = err.Error()
|
||||
} else {
|
||||
hashing := utility.HashMash{Password: req.Password}
|
||||
if hashing.CheckPasswordHash(req.Password, user.Password) {
|
||||
var tokGen utility.TokenGenerator
|
||||
secretKey := config.GetSecretKey()
|
||||
tokGen.SetSecretKey(secretKey)
|
||||
if token, err := tokGen.GenerateToken(*user); err != nil {
|
||||
fmt.Println(err.Error())
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = "Error generating token"
|
||||
} else {
|
||||
statusCode = http.StatusOK
|
||||
resp.Data = append(resp.Data, *token)
|
||||
resp.Message = "Successful"
|
||||
}
|
||||
} else {
|
||||
statusCode = http.StatusNotFound
|
||||
resp.Message = "User not found"
|
||||
}
|
||||
statusCode = http.StatusCreated
|
||||
resp.Message = "Contact created"
|
||||
resp.Data = append(resp.Data, newContact)
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
RespondWithJSON(w, statusCode, &resp)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/db"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/handler/endpoint"
|
||||
)
|
||||
|
||||
type Request struct {
|
||||
PhoneNumber string
|
||||
UserId uuid.UUID
|
||||
}
|
||||
|
||||
func TestCreateContactWithMock(t *testing.T) {
|
||||
mockstore := NewMockContactStore()
|
||||
handler := NewContactHandler(mockstore)
|
||||
|
||||
testUserId := uuid.New()
|
||||
testBody := Request{PhoneNumber: "+12335403383", UserId: testUserId}
|
||||
jsonValue, _ := json.Marshal(testBody)
|
||||
|
||||
req, _ := http.NewRequest("POST", endpoint.ADD_CONTACT_ENDPOINT, strings.NewReader(string(jsonValue)))
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.AddContact(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusCreated, rr.Code)
|
||||
|
||||
var response AddContactResponse
|
||||
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
assert.NoError(t, err, "Error Creating contact %v", err)
|
||||
|
||||
assert.NotEmpty(t, response.Data, "No Contact created")
|
||||
|
||||
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
|
||||
}
|
||||
|
||||
func resetTestDB(t *testing.T) {
|
||||
t.Helper()
|
||||
_, err := db.Pool.Exec(context.Background(), "DELETE FROM contacts")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to reset test database: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package endpoint
|
||||
|
||||
const MESSAGE_DRAFT_ENDPOINT = "/api/v1/message/draft"
|
||||
const ADD_CONTACT_ENDPOINT = "/api/v1/contact"
|
||||
@@ -1,4 +0,0 @@
|
||||
package handler
|
||||
|
||||
const MESSAGE_DRAFT_ENDPOINT = "/api/v1/message/draft"
|
||||
const ADD_CONTACT_ENDPOINT = "/api/v1/contact";
|
||||
@@ -4,7 +4,6 @@ import "encoding/json"
|
||||
import "log"
|
||||
import "net/http"
|
||||
|
||||
|
||||
func ExtractFromRequest(r *http.Request, reqItem interface{}) error {
|
||||
err := json.NewDecoder(r.Body).Decode(&reqItem)
|
||||
if err != nil {
|
||||
@@ -14,7 +13,6 @@ func ExtractFromRequest(r *http.Request, reqItem interface{}) error {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Helper function to send JSON responses
|
||||
func RespondWithJSON(w http.ResponseWriter, statusCode int, data interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user