From 8d050d2521ba07e96b2415834e201d001bf33aa5 Mon Sep 17 00:00:00 2001 From: Yanislav Igonin Date: Tue, 31 Aug 2021 22:51:10 +0300 Subject: [PATCH] feat: add get posts in repo --- repositories/posts_repository.go | 41 +++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/repositories/posts_repository.go b/repositories/posts_repository.go index 09488ac..ab4f87c 100644 --- a/repositories/posts_repository.go +++ b/repositories/posts_repository.go @@ -12,7 +12,46 @@ type PostsRepository struct{} var Posts PostsRepository func (r *PostsRepository) Get(limit, offset int) ([]Post, error) { - return PostsDb, nil + if Db.Pool == nil { + return PostsDb, nil + } + + sql := ` + SELECT id, title, text, created_at + FROM posts + WHERE + is_parent = true + AND is_deleted = false + ORDER BY updated_at DESC + LIMIT $1 + ` + + conn, err := Db.Pool.Acquire(context.TODO()) + if err != nil { + return nil, err + } + defer conn.Release() + + rows, err := conn.Query(context.TODO(), sql, limit) + if err != nil { + return nil, err + } + if rows.Err() != nil { + return nil, err + } + + var posts []Post + for rows.Next() { + var post Post + err = rows.Scan(&post.ID, &post.Title, &post.Text, &post.CreatedAt) + if err != nil { + return nil, err + } + + posts = append(posts, post) + } + + return posts, nil } func (r *PostsRepository) Create(p Post) (int, error) {