Skip to content

Commit

Permalink
fixes search func
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinGallauner committed Apr 29, 2024
1 parent d4105fa commit 776cb97
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 8 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,7 @@ Connect your physical bookshelf with your friends!



## Trade offs
- I regret adding Gorm as the ORM library.
- The search implementation is not okay.

22 changes: 20 additions & 2 deletions collection_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,32 @@ func (cfg *BookclubServer) AddBookToCollection(isbn string, userId uint) (Book,
func (cfg *BookclubServer) SearchBookInNetwork(userId uint, isbn string) ([]User, error) {

//get linked users
links, err := cfg.LinkRepository.GetAcceptedById(userId)
if err != nil {
return nil, err
}

// filter user for searched book

users, err := cfg.UserRepository.SearchBook(isbn)
if err != nil {
return nil, err
}
return users, nil

var collection = make(map[uint]User)
for _, user := range users {
for _, link := range links {
if user.ID == link.SenderId || user.ID == link.ReceiverId {
collection[user.ID] = user
}
}
}

result := make([]User, 0, len(collection))
for _, value := range collection {
result = append(result, value)
}

return result, nil
}

type SearchRequest struct {
Expand Down
4 changes: 4 additions & 0 deletions collection_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/magiconair/properties/assert"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -75,6 +76,9 @@ func TestSearchBookInNetwork(t *testing.T) {
s.LinkUsers(userWithBook.ID, userWithoutBooks.ID)
s.LinkUsers(userWithoutBooks.ID, userWithBook.ID)

link, err := s.LinkRepository.Get(userWithBook.ID, userWithoutBooks.ID)
fmt.Println(link)

if err != nil {
t.Fatalf("Unable to setup test.")
}
Expand Down
2 changes: 1 addition & 1 deletion handler_search.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func (cfg *BookclubServer) handlerSearch(w http.ResponseWriter, r *http.Request)
respondWithError(w, 400, fmt.Sprintf("Error decoding parameters: %s", err))
return
}

//todo remove ID from user response
users, err := cfg.SearchBookInNetwork(body.UserId, body.ISBN)
if err != nil {
respondWithError(w, 404, "Book is not available in the users network.")
Expand Down
20 changes: 17 additions & 3 deletions repository.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"fmt"
"gorm.io/gorm"
)

Expand Down Expand Up @@ -42,9 +43,9 @@ func (r *PostgresUserRepository) Save(user *User) error {

func (r *PostgresUserRepository) SearchBook(isbn string) ([]User, error) {
var users []User
err := r.Database.Preload("Books", "isbn = ?", isbn).Find(&users).Error
if err != nil {
return nil, err
result := r.Database.Raw(fmt.Sprintf("SELECT * FROM users\nJOIN user_books ON users.id = user_books.user_id\nWHERE book_isbn = '%v'", isbn)).Scan(&users)
if result.Error != nil {
return nil, result.Error
}
return users, nil
}
Expand Down Expand Up @@ -79,6 +80,19 @@ func (r *PostgresLinkRepository) GetById(userId string) ([]Link, error) { //todo
return links, nil
}

func (r *PostgresLinkRepository) GetAcceptedById(userId uint) ([]Link, error) { //todo
var links []Link

// Build the query with OR condition
result := r.Database.Where("sender_id = ? OR receiver_id = ?", userId, userId).Where("accepted_at > created_at").Find(&links)

if result.Error != nil {
// handle error
return nil, result.Error
}
return links, nil
}

func (r *PostgresLinkRepository) Save(link *Link) error {
err := r.Database.Table("links").Save(&link).Error
return err
Expand Down
3 changes: 3 additions & 0 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ type LinkRepository interface {
//Returns all links concerned with the user
GetById(userId string) ([]Link, error)

//Returns all links concerned with the user that are accepted
GetAcceptedById(userId uint) ([]Link, error)

//Persists link.
Save(link *Link) error
}
Expand Down
7 changes: 5 additions & 2 deletions user_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func (cfg *BookclubServer) LinkUsers(senderId uint, receiverId uint) (Link, erro
//ask if request already exists, if yes exit
existingLink, err := cfg.LinkRepository.Get(senderId, receiverId)

if existingLink.SenderId == senderId && existingLink.ReceiverId == receiverId {
if existingLink.SenderId == senderId && existingLink.ReceiverId == receiverId { //if already exists, return that right away
return existingLink, err
}

Expand All @@ -36,7 +36,10 @@ func (cfg *BookclubServer) LinkUsers(senderId uint, receiverId uint) (Link, erro
existingRequest, err := cfg.LinkRepository.Get(receiverId, senderId)
if err != gorm.ErrRecordNotFound {
existingRequest.AcceptedAt = time.Now()
cfg.LinkRepository.Save(&existingLink)
err := cfg.LinkRepository.Save(&existingRequest)
if err != nil {
return Link{}, err
}
return existingRequest, nil
}

Expand Down
7 changes: 7 additions & 0 deletions user_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,5 +155,12 @@ func TestAcceptLink(t *testing.T) {
t.Fatalf("Unable to parse response from server %q, '%v'", response.Body, err)
}
assertStatus(t, response.Code, http.StatusOK)

fetchLink, _ := s.LinkRepository.Get(user1.ID, user2.ID)

//persisted
assert.Equal(t, fetchLink.AcceptedAt.After(fetchLink.CreatedAt), true)

//response
assert.Equal(t, got.IsLinked, true)
}

0 comments on commit 776cb97

Please sign in to comment.