feat: implement retrieve by hash function

This commit is contained in:
Bastien Riviere 2024-01-29 19:51:23 +01:00
parent e17aa7dc38
commit 8e03a1e087
Signed by: babariviere
GPG key ID: 4E5F0839249F162E
19 changed files with 275 additions and 155 deletions

38
internal/api/handler.go Normal file
View file

@ -0,0 +1,38 @@
package api
import (
"context"
"errors"
"fmt"
"github.com/babariviere/short/internal/db"
"github.com/babariviere/short/internal/oas"
"github.com/jackc/pgx/v5"
)
var _ oas.Handler = (*handler)(nil)
type handler struct {
oas.UnimplementedHandler
queries *db.Queries
}
func NewHandler(queries *db.Queries) *handler {
return &handler{
queries: queries,
}
}
func (h *handler) RedirectLongURL(ctx context.Context, params oas.RedirectLongURLParams) (oas.RedirectLongURLRes, error) {
res, err := h.queries.GetURLByHash(ctx, params.Hash)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return &oas.RedirectLongURLNotFound{}, nil
}
return nil, fmt.Errorf("unable to fetch URL by hash: %w", err)
}
return &oas.RedirectLongURLTemporaryRedirect{
Location: oas.NewOptString(res.LongUrl),
}, nil
}