2024-01-29 18:51:23 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/babariviere/short/internal/db"
|
|
|
|
"github.com/babariviere/short/internal/oas"
|
2024-01-29 20:21:23 +00:00
|
|
|
"github.com/babariviere/short/internal/url"
|
2024-01-29 18:51:23 +00:00
|
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
)
|
|
|
|
|
|
|
|
var _ oas.Handler = (*handler)(nil)
|
|
|
|
|
|
|
|
type handler struct {
|
2024-01-29 20:21:23 +00:00
|
|
|
serverUrl string
|
|
|
|
queries *db.Queries
|
2024-01-29 18:51:23 +00:00
|
|
|
}
|
|
|
|
|
2024-01-29 20:21:23 +00:00
|
|
|
func NewHandler(serverUrl string, queries *db.Queries) *handler {
|
2024-01-29 18:51:23 +00:00
|
|
|
return &handler{
|
2024-01-29 20:21:23 +00:00
|
|
|
serverUrl: serverUrl,
|
|
|
|
queries: queries,
|
2024-01-29 18:51:23 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *handler) RedirectLongURL(ctx context.Context, params oas.RedirectLongURLParams) (oas.RedirectLongURLRes, error) {
|
|
|
|
res, err := h.queries.GetURLByHash(ctx, params.Hash)
|
2024-02-09 18:36:05 +00:00
|
|
|
|
|
|
|
switch {
|
|
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
|
|
return &oas.RedirectLongURLNotFound{}, nil
|
|
|
|
case err != nil:
|
2024-01-29 18:51:23 +00:00
|
|
|
return nil, fmt.Errorf("unable to fetch URL by hash: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &oas.RedirectLongURLTemporaryRedirect{
|
|
|
|
Location: oas.NewOptString(res.LongUrl),
|
|
|
|
}, nil
|
|
|
|
}
|
2024-01-29 20:21:23 +00:00
|
|
|
|
|
|
|
func (h *handler) CreateShortURL(ctx context.Context, req *oas.CreateShortURLReq) (oas.CreateShortURLRes, error) {
|
|
|
|
hash, err := url.GenerateHash(req.URL)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to generate hash for url %s: %w", req.URL, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
res, err := h.queries.InsertURL(ctx, db.InsertURLParams{
|
|
|
|
Hash: hash,
|
|
|
|
LongUrl: req.URL,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to insert url: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &oas.CreateShortURLCreated{
|
|
|
|
Shorten: h.serverUrl + "/" + res.Hash,
|
|
|
|
}, nil
|
|
|
|
}
|