Implement an update to the create function to not allow duplicate emails

This commit is contained in:
Colin Bassett 2025-02-25 12:29:26 -05:00
parent d3e63fbae9
commit 5ecc7ea615
2 changed files with 7 additions and 1 deletions

4
api.py
View File

@ -17,6 +17,10 @@ app = FastAPI(lifespan=lifespan)
# Routes
@app.post("/heroes/create", response_model=HeroPublic)
def create_hero(hero: HeroCreate, session: SessionDep):
existing_hero = session.query(Hero).filter(Hero.email == hero.email).first()
if existing_hero:
raise HTTPException(status_code=400, detail="Email already registered")
db_hero = Hero.model_validate(hero)
session.add(db_hero)
session.commit()

4
sql.py
View File

@ -2,6 +2,8 @@
from typing import Annotated
from fastapi import Depends
from sqlmodel import Field, Session, SQLModel, create_engine
from sqlalchemy import String
from sqlalchemy.sql.schema import Column
# The base hero class
class HeroBase(SQLModel):
@ -12,7 +14,7 @@ class HeroBase(SQLModel):
# The main hero class. It inherits the name, gold, and health
class Hero(HeroBase, table=True):
id: int | None = Field(default=None, primary_key=True, index=True)
email: str = Field(index=True)
email: str = Field(index=True, unique=True)
password: str
salt: int