Refactor link repository and improve logging

This commit is contained in:
Andrey Chervyakov 2021-03-18 20:53:59 +06:00
parent ddaf0dcbfc
commit 458ae28901
7 changed files with 63 additions and 19 deletions

View file

@ -1,6 +1,7 @@
package link
import (
"cgnolink/database"
"context"
"errors"
"github.com/jackc/pgtype"
@ -15,7 +16,7 @@ const defaultContextTimeout = 10 * time.Second
type Repository interface {
Save(link *Link) error
FindById(id string) (*Link, error)
FindAll(limit int, offset int) (Links, error)
GetAll(limit int, offset int) (Links, error)
Update(link *Link) error
DeleteById(id string) error
}
@ -37,6 +38,7 @@ func (r *PgRepository) Save(link *Link) error {
VALUES ($1, $2, $3, $4::timestamp)
`
database.LogPoolState(r.pool, "Saving link")
_, err := r.pool.Exec(ctx, sql, link.Id, link.Name, link.RedirectURL.String(), link.CreationTime.Format("2006-01-02 15:04:05"))
if err != nil {
return err
@ -55,6 +57,7 @@ func (r *PgRepository) FindById(id string) (*Link, error) {
WHERE id = $1
`
database.LogPoolState(r.pool, "Finding link by ID")
entity, err := mapRowToEntity(r.pool.QueryRow(ctx, sql, id))
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
@ -67,7 +70,7 @@ func (r *PgRepository) FindById(id string) (*Link, error) {
return entity, nil
}
func (r *PgRepository) FindAll(limit int, offset int) (Links, error) {
func (r *PgRepository) GetAll(limit int, offset int) (Links, error) {
if limit < 0 {
return nil, errors.New("limit can't be negative")
}
@ -85,6 +88,7 @@ func (r *PgRepository) FindAll(limit int, offset int) (Links, error) {
OFFSET $2
`
database.LogPoolState(r.pool, "Getting all links")
rows, err := r.pool.Query(ctx, sql, limit, offset)
if err != nil {
return nil, err
@ -122,6 +126,7 @@ func (r *PgRepository) Update(link *Link) error {
WHERE id = $3
`
database.LogPoolState(r.pool, "Updating link")
_, err := r.pool.Exec(ctx, sql, link.Name, link.RedirectURL.String(), link.Id)
if err != nil {
return err
@ -138,6 +143,7 @@ func (r *PgRepository) DeleteById(id string) error {
DELETE FROM links WHERE id = $1
`
database.LogPoolState(r.pool, "Deleting link")
_, err := r.pool.Exec(ctx, sql, id)
if err != nil {
return err