Files
minxa.lol/app/routes/shortener.py

35 lines
1.2 KiB
Python

from fastapi import APIRouter, HTTPException
from fastapi.responses import RedirectResponse
from app.db import database
from app.exceptions import ShortcodeNotFound, ShortcodeConflict
from app.utils import encoder
from app.schemas import UrlPayload
from app.services import UrlService
router = APIRouter()
url_service = UrlService(db=database)
@router.get("/{shortcode}")
async def redirect_to_original_url(shortcode: str):
if not encoder.is_valid(shortcode):
raise HTTPException(status_code=400, detail=f"Shortcode '{shortcode}' is not valid")
try:
url = await url_service.get_url_by_shortcode(shortcode)
return RedirectResponse(url=url, status_code=302)
except ShortcodeNotFound as e:
raise HTTPException(status_code=404, detail=str(e)) from e
@router.post("/")
async def create_url_shortcode(url_payload: UrlPayload):
url = str(url_payload.url)
try:
return await url_service.generate_shortcode_and_save(url)
except ShortcodeConflict as e:
raise HTTPException(status_code=409, detail=str(e)) from e
except:
raise HTTPException(status_code=500, detail="Internal Server Error") from None