feat(api): add endpoint for fetching computed widget data by username.

This commit is contained in:
shay
2026-04-18 10:54:41 -04:00
parent a63c1891a0
commit f0c6edacf6
5 changed files with 143 additions and 89 deletions
+50 -1
View File
@@ -6,10 +6,11 @@ Serves:
/api/* -> JSON/SVG API
"""
import os
from dataclasses import asdict
from functools import wraps
from flask import Flask, jsonify, request, Response, send_from_directory
from . import config, db, fetcher_client, placeholder
from . import config, db, fetcher_client, placeholder, processor
_STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
@@ -54,6 +55,54 @@ def get_widget_named(username: str, widget: str):
return _serve(username, widget_name=widget)
@app.route("/api/<username>/data", methods=["GET"])
def get_user_data(username: str):
"""Computed widget data for client-side SVG rendering.
Auto-enrolls on first access (so the user appears in settings + the cron
keeps their data warm), then computes the data on-demand from fresh
fetcher output. Not cached at this layer — the fetcher already caches raw
GitHub payloads.
"""
settings_row = db.get_settings(username)
if settings_row is None:
if db.enrollments_today() >= config.ENROLLMENT_DAILY_CAP:
return jsonify({"error": "rate_limited"}), 429
defaults = {
"theme": "dark",
"enabled": config.ENABLED_WIDGETS,
"widget_order": config.WIDGET_ORDER,
}
db.enroll(username, defaults)
else:
db.touch_last_requested(username)
try:
result = fetcher_client.get_data(username)
except Exception as e:
return jsonify({"error": f"fetcher unavailable: {e}"}), 502
payload = result.get("data") or {}
if payload.get("error") == "not_found" or "user" not in payload:
return jsonify({"error": "not_found"}), 404
custom_tags = request.args.getlist("custom_tags") or None
hidden_languages = request.args.getlist("hidden_languages") or None
try:
data = {
"grade": asdict(processor.compute_grade(payload, custom_tags=custom_tags)),
"impact": [asdict(w) for w in processor.compute_impact_timeline(payload)],
"collaborators": [asdict(c) for c in processor.compute_collaborators(payload)],
"focus": [asdict(f) for f in processor.compute_focus(payload, hidden_languages=hidden_languages)],
"languages": [asdict(l) for l in processor.compute_languages(payload, hidden_languages=hidden_languages)],
}
except Exception as e:
return jsonify({"error": f"processing failed: {e}"}), 500
return jsonify({"data": data})
def _serve(username: str, widget_name: str) -> Response:
settings_row = db.get_settings(username)