From d829cf190c8bb8bec41a592098deff8852bc814f Mon Sep 17 00:00:00 2001 From: cjtim <47479090+cjtim@users.noreply.github.com> Date: Sun, 11 Sep 2022 17:07:48 +0000 Subject: [PATCH] feat: list pet by shelterId --- handlers/pet/get.go | 13 +++++++++++++ repository/pet.go | 19 +++++++++++++++++++ tools/db/5-data.sql | 14 +++++++------- 3 files changed, 39 insertions(+), 7 deletions(-) diff --git a/handlers/pet/get.go b/handlers/pet/get.go index c2d4ceb..8fa39f0 100644 --- a/handlers/pet/get.go +++ b/handlers/pet/get.go @@ -5,6 +5,7 @@ import ( "github.com/cjtim/be-friends-api/repository" "github.com/gofiber/fiber/v2" + "github.com/google/uuid" ) // PetList - list all pets from database @@ -17,6 +18,18 @@ import ( // @Failure 500 {string} string // @Router /api/v1/pet [get] func PetList(c *fiber.Ctx) error { + userId := c.Query("user_id") + if userId != "" { + _, err := uuid.Parse(userId) + if err != nil { + return err + } + pets, err := repository.PetRepo.List() + if err != nil { + return err + } + return c.JSON(pets) + } pets, err := repository.PetRepo.List() if err != nil { return err diff --git a/repository/pet.go b/repository/pet.go index b6e265a..cb2e323 100644 --- a/repository/pet.go +++ b/repository/pet.go @@ -47,6 +47,25 @@ func (p *PetImpl) List() (pets []PetWithPic, err error) { return pets, err } +func (p *PetImpl) ListByUserId(userId uuid.UUID) (pets []PetWithPic, err error) { + stm := ` + SELECT + p.*, + ( + SELECT COALESCE(json_agg(pic), '[]') + FROM ( + SELECT picture_url + FROM "pic_pet" pp + WHERE pp.pet_id = p.id + ) pic + ) AS picture_urls + FROM pet p + WHERE p.user_id = $1 + ` + err = DB.Select(&pets, stm, userId) + return pets, err +} + func (p *PetImpl) GetById(id int) (pet PetWithPic, err error) { stm := ` SELECT diff --git a/tools/db/5-data.sql b/tools/db/5-data.sql index 7a40234..e6a7f2b 100644 --- a/tools/db/5-data.sql +++ b/tools/db/5-data.sql @@ -2,13 +2,13 @@ INSERT INTO "status" (name) VALUES ('new'), ('pending'), ('adoped'); --- -- Test credential --- -- test-preview@gmail.com --- -- test --- INSERT INTO "user" (id, name, email, password, is_org, line_uid) --- VALUES --- ('097b2b93-0a66-4de2-a5a6-4f0b15acc54c', 'Test', 'test-preview@gmail.com', '$2a$04$x1jU9wX5Ab7fzyL.qG5CO.4CHB/t3lq0obSjdXkJ5.tmlwjVJZyRO', TRUE, NULL), --- ('e15f64ec-d87e-4bc3-8680-3fb7b47d438d', 'Line User Test', NULL, NULL, FALSE, 'aaaaaaaaaaaaaaaaaaaa'); +-- Test credential +-- test-preview@gmail.com +-- test +INSERT INTO "user" (id, name, email, password, is_org, line_uid) +VALUES +('097b2b93-0a66-4de2-a5a6-4f0b15acc54c', 'Test', 'test-preview@gmail.com', '$2a$04$x1jU9wX5Ab7fzyL.qG5CO.4CHB/t3lq0obSjdXkJ5.tmlwjVJZyRO', TRUE, NULL), +('e15f64ec-d87e-4bc3-8680-3fb7b47d438d', 'Line User Test', NULL, NULL, FALSE, 'aaaaaaaaaaaaaaaaaaaa'); -- INSERT INTO "pet" (name, description, lat, lng) -- VALUES