Add collection stats endpoint

This commit is contained in:
Correl Roush 2022-08-03 17:26:14 -04:00
parent f1a0f8233d
commit 362bef913c
2 changed files with 35 additions and 0 deletions

View file

@ -356,3 +356,23 @@ async def store_var(db: psycopg.Cursor, key: str, value: str) -> None:
""",
{"key": key, "value": value},
)
async def collection_stats(db: psycopg.Cursor) -> dict:
db.row_factory = psycopg.rows.dict_row
await db.execute(
"""
SELECT COUNT("copies"."id") AS cards
, SUM(
CASE WHEN "copies"."isFoil"
THEN "card_prices"."usd_foil"
ELSE "card_prices"."usd"
END
) AS value
, COUNT(DISTINCT cards.set_code) AS sets
FROM "copies"
JOIN "cards" USING ("scryfall_id")
LEFT JOIN "card_prices" USING ("scryfall_id")
"""
)
return await db.fetchone()

View file

@ -4,6 +4,7 @@ import typing
import urllib.parse
import psycopg
import psycopg.rows
import psycopg_pool
import tornado.ioloop
import tornado.web
@ -85,11 +86,13 @@ class SearchHandler(tornado.web.RequestHandler):
if has_more:
links["next"] = update_args(self.request.full_url(), page=page + 1)
self.set_links(**links)
def price(amount: typing.Optional[decimal.Decimal]) -> typing.Optional[str]:
if amount is not None:
return str(amount)
else:
return None
self.write(
json.dumps(
[
@ -119,10 +122,22 @@ class SearchHandler(tornado.web.RequestHandler):
)
class CollectionHandler(tornado.web.RequestHandler):
async def get(self) -> None:
async with self.application.pool.connection() as conn:
async with conn.cursor() as cursor:
self.write(
json.dumps(
await tutor.database.collection_stats(cursor), default=str
)
)
class Application(tornado.web.Application):
def __init__(self, **settings):
paths = [
(r"/search", SearchHandler),
(r"/collection", CollectionHandler),
]
if static_path := settings.get("static"):
paths.extend(