Tuas W06
This commit is contained in:
@@ -2,6 +2,7 @@ package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
|
||||
"5803025020/w04/internal/models"
|
||||
@@ -9,6 +10,9 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// ErrSnippetNotFound dikembalikan saat snippet dengan id yang diminta tidak ada.
|
||||
var ErrSnippetNotFound = errors.New("snippet not found")
|
||||
|
||||
type SnippetStore struct {
|
||||
conn *pgx.Conn
|
||||
mu *sync.Mutex
|
||||
@@ -45,6 +49,9 @@ func (s *SnippetStore) GetByID(ctx context.Context, id string) (*models.Snippet,
|
||||
query := `SELECT id, title, content, user_id FROM snippets WHERE id = $1`
|
||||
err := s.conn.QueryRow(ctx, query, id).Scan(&sn.ID, &sn.Title, &sn.Content, &sn.UserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrSnippetNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &sn, nil
|
||||
@@ -100,11 +107,19 @@ func (s *SnippetStore) GetAll(ctx context.Context) ([]*models.Snippet, error) {
|
||||
return snippets, nil
|
||||
}
|
||||
|
||||
// Delete menghapus snippet dengan id tersebut. Jika id tidak ditemukan, ia
|
||||
// mengembalikan ErrSnippetNotFound.
|
||||
func (s *SnippetStore) Delete(ctx context.Context, id string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
query := `DELETE FROM snippets WHERE id = $1`
|
||||
_, err := s.conn.Exec(ctx, query, id)
|
||||
return err
|
||||
tag, err := s.conn.Exec(ctx, query, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrSnippetNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user