feat: Add helper functions for Book
This commit is contained in:
parent
86f1a8bb7a
commit
6693913274
78
helpers/book_helpers.py
Normal file
78
helpers/book_helpers.py
Normal file
@ -0,0 +1,78 @@
|
||||
from typing import List
|
||||
from sqlalchemy.orm import Session
|
||||
from models.book import Book
|
||||
from schemas.book import BookSchema
|
||||
|
||||
def get_all_books(db: Session) -> List[BookSchema]:
|
||||
"""
|
||||
Retrieve all books from the database.
|
||||
|
||||
Args:
|
||||
db (Session): SQLAlchemy database session.
|
||||
|
||||
Returns:
|
||||
List[BookSchema]: List of book schemas.
|
||||
"""
|
||||
books = db.query(Book).all()
|
||||
return [BookSchema.from_orm(book) for book in books]
|
||||
|
||||
def get_book_by_id(db: Session, book_id: str) -> BookSchema:
|
||||
"""
|
||||
Retrieve a book by its ID from the database.
|
||||
|
||||
Args:
|
||||
db (Session): SQLAlchemy database session.
|
||||
book_id (str): ID of the book to retrieve.
|
||||
|
||||
Returns:
|
||||
BookSchema: Book schema if found, None otherwise.
|
||||
"""
|
||||
book = db.query(Book).filter(Book.id == book_id).first()
|
||||
return BookSchema.from_orm(book) if book else None
|
||||
|
||||
def get_books_by_author(db: Session, author: str) -> List[BookSchema]:
|
||||
"""
|
||||
Retrieve books by author from the database.
|
||||
|
||||
Args:
|
||||
db (Session): SQLAlchemy database session.
|
||||
author (str): Author name to search for.
|
||||
|
||||
Returns:
|
||||
List[BookSchema]: List of book schemas for the given author.
|
||||
"""
|
||||
books = db.query(Book).filter(Book.author == author).all()
|
||||
return [BookSchema.from_orm(book) for book in books]
|
||||
|
||||
def get_books_by_isbn(db: Session, isbn: str) -> List[BookSchema]:
|
||||
"""
|
||||
Retrieve books by ISBN from the database.
|
||||
|
||||
Args:
|
||||
db (Session): SQLAlchemy database session.
|
||||
isbn (str): ISBN to search for.
|
||||
|
||||
Returns:
|
||||
List[BookSchema]: List of book schemas for the given ISBN.
|
||||
"""
|
||||
books = db.query(Book).filter(Book.isbn == isbn).all()
|
||||
return [BookSchema.from_orm(book) for book in books]
|
||||
|
||||
def search_books(db: Session, query: str) -> List[BookSchema]:
|
||||
"""
|
||||
Search for books based on a query string.
|
||||
|
||||
Args:
|
||||
db (Session): SQLAlchemy database session.
|
||||
query (str): Search query string.
|
||||
|
||||
Returns:
|
||||
List[BookSchema]: List of book schemas matching the search query.
|
||||
"""
|
||||
books = db.query(Book).filter(
|
||||
Book.title.ilike(f"%{query}%") |
|
||||
Book.author.ilike(f"%{query}%") |
|
||||
Book.description.ilike(f"%{query}%") |
|
||||
Book.isbn.ilike(f"%{query}%")
|
||||
).all()
|
||||
return [BookSchema.from_orm(book) for book in books]
|
Loading…
x
Reference in New Issue
Block a user