justusbot/internal/models/library.go

105 lines
2.3 KiB
Go
Raw Normal View History

2026-11-12 19:27:20 -07:00
package models
import (
"context"
"time"
"github.com/jmoiron/sqlx"
)
type Library struct {
Id int `db:"id"`
BookID int `db:"bookid"`
ChatID int `db:"chatid"`
Available bool `db:"available"`
}
type LibraryBook struct {
ID int `db:"id"`
ISBN string `db:"isbn"`
Title string `db:"title"`
Authors string `db:"authors"`
Meta map[string]string `db:"meta"`
}
type LibraryCheckout struct {
LibraryID int `db:"libraryid"`
UserID int `db:"userid"`
Recipient string `db:"recipient"`
CheckedOut time.Time `db:"checked_out"`
ReturnedAt *time.Time `db:"returned_at"`
}
type LibraryQueue struct {
BookID int `db:"bookid"`
UserID int `db:"userid"`
Requester string `db:"requester"`
}
type OLCache struct {
ISBN string `db:"isbn"`
ResponseCode int `db:"response_code"`
Requested time.Time `db:"requested"`
JSONResponse string `db:"json_response"`
}
type LibraryModel struct {
ctx context.Context
db *sqlx.DB
tx *sqlx.Tx
}
func NewLibraryModel(ctx context.Context, db *sqlx.DB) *LibraryModel {
return &LibraryModel{ctx, db, nil}
}
func (lm *LibraryModel) AddBook(book *LibraryBook) error {
q := `insert or ignore into library_books (isbn, title, authors, meta) values (?, ?, ?, ?)`
fn := lm.db.ExecContext
if lm.tx != nil {
fn = lm.tx.ExecContext
}
if _, err := fn(lm.ctx, q, book.ISBN, book.Title, book.Authors, book.Meta); err != nil {
return err
}
return nil
}
func (lm *LibraryModel) AddToLibrary(book *LibraryBook) error {
return nil
}
func (lm *LibraryModel) CacheOLResponse(ol *OLCache) error {
q := `insert or replace into ol_cache (isbn, response_code, json_response) values (?, ?, ?)`
fn := lm.db.ExecContext
if lm.tx != nil {
fn = lm.tx.ExecContext
}
if _, err := fn(lm.ctx, q, ol.ISBN, ol.ResponseCode, ol.JSONResponse); err != nil {
return err
}
return nil
}
func (lm *LibraryModel) GetOLCache(isbn string) (*LibraryBook, error) {
q := `select isbn, response_code, requested, json_response from ol_cache where isbn = ?`
fn := lm.db.GetContext
if lm.tx != nil {
fn = lm.tx.GetContext
}
b := &LibraryBook{}
if err := fn(lm.ctx, b, q, isbn); err != nil {
return nil, err
}
return b, nil
}