feat: add create short url

This commit is contained in:
Bastien Riviere 2024-01-29 21:21:23 +01:00
parent c7be765c23
commit 31fde6cad6
Signed by: babariviere
GPG key ID: 4E5F0839249F162E
8 changed files with 149 additions and 20 deletions

View file

@ -7,19 +7,21 @@ import (
"github.com/babariviere/short/internal/db"
"github.com/babariviere/short/internal/oas"
"github.com/babariviere/short/internal/url"
"github.com/jackc/pgx/v5"
)
var _ oas.Handler = (*handler)(nil)
type handler struct {
oas.UnimplementedHandler
queries *db.Queries
serverUrl string
queries *db.Queries
}
func NewHandler(queries *db.Queries) *handler {
func NewHandler(serverUrl string, queries *db.Queries) *handler {
return &handler{
queries: queries,
serverUrl: serverUrl,
queries: queries,
}
}
@ -36,3 +38,28 @@ func (h *handler) RedirectLongURL(ctx context.Context, params oas.RedirectLongUR
Location: oas.NewOptString(res.LongUrl),
}, nil
}
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 {
// No row == conflict since we do a "ON CONFLICT DO NOTHING"
if errors.Is(err, pgx.ErrNoRows) {
return &oas.CreateShortURLBadRequest{
Message: oas.NewOptString("URL already exist."),
}, nil
}
return nil, fmt.Errorf("failed to insert url: %w", err)
}
return &oas.CreateShortURLCreated{
Shorten: h.serverUrl + "/" + res.Hash,
}, nil
}