feat: add new encoder and restructure project

This commit is contained in:
2025-07-22 21:55:45 +00:00
parent 83d828c935
commit ee67589393
20 changed files with 143 additions and 75 deletions

27
app/services/encoder.py Normal file
View File

@@ -0,0 +1,27 @@
from app.config import settings
from hashids import Hashids
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, id: int) -> str:
return self.hashids.encode(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()