feat: add create short url
This commit is contained in:
parent
c7be765c23
commit
31fde6cad6
8 changed files with 149 additions and 20 deletions
|
@ -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
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue