feat: add frontend project to repo
This commit is contained in:
1
backend/utils/__init__.py
Normal file
1
backend/utils/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
from .encoder import encoder
|
||||
28
backend/utils/encoder.py
Normal file
28
backend/utils/encoder.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from hashids import Hashids
|
||||
|
||||
from backend.config import settings
|
||||
|
||||
class ShortCodeEncoder:
|
||||
def __init__(self, salt=None, alphabet=None, min_length=6):
|
||||
self.salt = salt or settings.hashids_salt
|
||||
self.alphabet = alphabet or settings.encoder_alphabet
|
||||
|
||||
self.hashids = Hashids(salt=self.salt, min_length=min_length, alphabet=self.alphabet)
|
||||
self.min_length = min_length
|
||||
|
||||
def encode(self, url_id: int) -> str:
|
||||
return self.hashids.encode(url_id)
|
||||
|
||||
def decode(self, shortcode: str) -> int:
|
||||
decoded = self.hashids.decode(shortcode)
|
||||
return decoded[0] if decoded else None
|
||||
|
||||
def is_valid(self, shortcode: str) -> bool:
|
||||
if len(shortcode) < self.min_length:
|
||||
return False
|
||||
if any(char not in self.alphabet for char in shortcode):
|
||||
return False
|
||||
return True
|
||||
|
||||
# Singleton instance of encoder
|
||||
encoder = ShortCodeEncoder()
|
||||
Reference in New Issue
Block a user