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
+12 -8
View File
@@ -3,6 +3,7 @@ import './index.css'
import { SearchScreen } from './screens/SearchScreen' import { SearchScreen } from './screens/SearchScreen'
import { WorkshopScreen } from './screens/WorkshopScreen' import { WorkshopScreen } from './screens/WorkshopScreen'
import { ResultScreen } from './screens/ResultScreen' import { ResultScreen } from './screens/ResultScreen'
import type { WidgetData } from './lib/renderWidgets'
export type Achievement = { export type Achievement = {
title: string title: string
@@ -46,6 +47,7 @@ export default function App() {
const [step, setStep] = useState<Step>('search') const [step, setStep] = useState<Step>('search')
const [username, setUsername] = useState('') const [username, setUsername] = useState('')
const [settings, setSettings] = useState<WidgetSettings>({ ...DEFAULT_SETTINGS }) const [settings, setSettings] = useState<WidgetSettings>({ ...DEFAULT_SETTINGS })
const [widgetData, setWidgetData] = useState<WidgetData | null>(null)
const [fetchDone, setFetchDone] = useState(false) const [fetchDone, setFetchDone] = useState(false)
const [fetchError, setFetchError] = useState<string | null>(null) const [fetchError, setFetchError] = useState<string | null>(null)
const fetchRef = useRef<AbortController | null>(null) const fetchRef = useRef<AbortController | null>(null)
@@ -56,18 +58,18 @@ export default function App() {
fetchRef.current = ctrl fetchRef.current = ctrl
setFetchDone(false) setFetchDone(false)
setFetchError(null) setFetchError(null)
setWidgetData(null)
fetch('/api/fetch', { fetch(`/api/${encodeURIComponent(user)}/data`, { signal: ctrl.signal })
method: 'POST', .then(async r => {
headers: { 'Content-Type': 'application/json' }, if (r.status === 404) throw new Error('User not found')
body: JSON.stringify({ username: user }),
signal: ctrl.signal,
})
.then(r => {
if (!r.ok) throw new Error(`Fetch failed (${r.status})`) if (!r.ok) throw new Error(`Fetch failed (${r.status})`)
return r.json() return r.json()
}) })
.then(() => setFetchDone(true)) .then(json => {
setWidgetData(json.data)
setFetchDone(true)
})
.catch(e => { .catch(e => {
if (e.name !== 'AbortError') { if (e.name !== 'AbortError') {
console.warn('Fetch error:', e) console.warn('Fetch error:', e)
@@ -108,6 +110,7 @@ export default function App() {
onGenerate={handleGenerate} onGenerate={handleGenerate}
onBack={handleBack} onBack={handleBack}
fetchDone={fetchDone} fetchDone={fetchDone}
widgetData={widgetData}
/> />
)} )}
{step === 'result' && ( {step === 'result' && (
@@ -116,6 +119,7 @@ export default function App() {
settings={settings} settings={settings}
fetchDone={fetchDone} fetchDone={fetchDone}
fetchError={fetchError} fetchError={fetchError}
widgetData={widgetData}
onBack={handleBack} onBack={handleBack}
/> />
)} )}
+18 -43
View File
@@ -1,6 +1,7 @@
import { useState, useEffect } from 'react' import { useMemo } from 'react'
import DOMPurify from 'dompurify' import DOMPurify from 'dompurify'
import type { WidgetSettings } from '../App' import type { WidgetSettings } from '../App'
import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets'
function sanitizeSvg(raw: string): string { function sanitizeSvg(raw: string): string {
return DOMPurify.sanitize(raw, { return DOMPurify.sanitize(raw, {
@@ -15,44 +16,24 @@ type Props = {
settings: WidgetSettings settings: WidgetSettings
fetchDone: boolean fetchDone: boolean
fetchError: string | null fetchError: string | null
widgetData: WidgetData | null
onBack: () => void onBack: () => void
} }
export function ResultScreen({ username, settings, fetchDone, fetchError, onBack }: Props) { export function ResultScreen({ username, settings, fetchDone, fetchError, widgetData, onBack }: Props) {
const [svgContent, setSvgContent] = useState<string>('') const svgContent = useMemo(() => {
const [loading, setLoading] = useState(true) if (!widgetData) return ''
const [generated, setGenerated] = useState(false) const raw = renderAllWidgets({
data: widgetData,
// Generate the final SVG once fetch completes
useEffect(() => {
if (!fetchDone) return
if (generated) return
setLoading(true)
fetch('/api/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username,
theme: settings.theme, theme: settings.theme,
widgets: settings.widgets, widgets: settings.widgets,
widget_order: ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'], widgetOrder: ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'],
custom_tags: settings.customTags.length ? settings.customTags : undefined,
hidden_languages: settings.hiddenLanguages.length ? settings.hiddenLanguages : undefined,
achievements: settings.achievements.filter(a => a.title.trim()), achievements: settings.achievements.filter(a => a.title.trim()),
widget_settings: settings.widgetSettings, widgetSettings: settings.widgetSettings,
format: 'svg', username,
}),
}) })
.then(r => r.text()) return sanitizeSvg(raw)
.then(svg => { }, [widgetData, settings, username])
// SVG is sanitized via DOMPurify before rendering
setSvgContent(sanitizeSvg(svg))
setLoading(false)
setGenerated(true)
})
.catch(() => setLoading(false))
}, [fetchDone])
const waiting = !fetchDone const waiting = !fetchDone
@@ -81,24 +62,18 @@ export function ResultScreen({ username, settings, fetchDone, fetchError, onBack
<div className="w-5 h-5 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin-slow" /> <div className="w-5 h-5 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin-slow" />
<p className="text-xs text-gray-400">Generating with real data...</p> <p className="text-xs text-gray-400">Generating with real data...</p>
</div> </div>
) : loading ? ( ) : !svgContent ? (
<div className="mt-8 flex flex-col items-center gap-3"> <div className="mt-8 flex flex-col items-center gap-3">
<div className="w-5 h-5 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin-slow" /> <p className="text-[10px] text-amber-500">
<p className="text-xs text-gray-400">Rendering...</p> {fetchError ?? 'Could not fetch live data'}
</p>
</div> </div>
) : ( ) : (
<> <>
{fetchError && (
<p className="text-[10px] text-amber-500 mb-4">
Could not fetch live data — showing demo widget
</p>
)}
{!fetchError && (
<p className="text-xs text-gray-400 mb-6"> <p className="text-xs text-gray-400 mb-6">
Generated with real data Generated with real data
</p> </p>
)} {/* SVG sanitized via DOMPurify.sanitize() before rendering */}
{/* SVG content is sanitized with DOMPurify.sanitize() before rendering */}
<div dangerouslySetInnerHTML={{ __html: svgContent }} /> <div dangerouslySetInnerHTML={{ __html: svgContent }} />
</> </>
)} )}
@@ -1,4 +1,4 @@
import { useState, useEffect, useRef, useMemo } from 'react' import { useState, useMemo } from 'react'
import type { WidgetSettings, Achievement, PerWidgetSettings } from '../App' import type { WidgetSettings, Achievement, PerWidgetSettings } from '../App'
import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets' import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets'
@@ -85,6 +85,7 @@ type Props = {
onGenerate: () => void onGenerate: () => void
onBack: () => void onBack: () => void
fetchDone: boolean fetchDone: boolean
widgetData: WidgetData | null
} }
export function WorkshopScreen({ export function WorkshopScreen({
@@ -94,11 +95,9 @@ export function WorkshopScreen({
onGenerate, onGenerate,
onBack, onBack,
fetchDone, fetchDone,
widgetData,
}: Props) { }: Props) {
const [widgetData, setWidgetData] = useState<WidgetData | null>(null)
const [dataLoading, setDataLoading] = useState(true)
const [expandedWidget, setExpandedWidget] = useState<string | null>(null) const [expandedWidget, setExpandedWidget] = useState<string | null>(null)
const dataFetched = useRef(false)
const updateSetting = <K extends keyof WidgetSettings>(key: K, val: WidgetSettings[K]) => { const updateSetting = <K extends keyof WidgetSettings>(key: K, val: WidgetSettings[K]) => {
onSettingsChange({ ...settings, [key]: val }) onSettingsChange({ ...settings, [key]: val })
@@ -144,32 +143,6 @@ export function WorkshopScreen({
updateSetting('achievements', settings.achievements.filter((_, i) => i !== idx)) updateSetting('achievements', settings.achievements.filter((_, i) => i !== idx))
} }
// Fetch widget data once on mount (or when fetch completes)
useEffect(() => {
if (dataFetched.current || !fetchDone) return
dataFetched.current = true
setDataLoading(true)
fetch('/api/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username,
widgets: ['grade', 'impact', 'collaborators', 'focus', 'languages'],
widget_order: ['grade', 'impact', 'collaborators', 'focus', 'languages'],
custom_tags: settings.customTags.length ? settings.customTags : undefined,
hidden_languages: settings.hiddenLanguages.length ? settings.hiddenLanguages : undefined,
format: 'data',
}),
})
.then(r => r.json())
.then(json => {
setWidgetData(json.data)
setDataLoading(false)
})
.catch(() => setDataLoading(false))
}, [fetchDone])
// Render SVG client-side whenever settings change (instant, no API call) // Render SVG client-side whenever settings change (instant, no API call)
const svgContent = useMemo(() => { const svgContent = useMemo(() => {
if (!widgetData) return '' if (!widgetData) return ''
@@ -440,7 +413,7 @@ export function WorkshopScreen({
<div dangerouslySetInnerHTML={{ __html: svgContent }} /> <div dangerouslySetInnerHTML={{ __html: svgContent }} />
) : ( ) : (
<div className="w-[420px] h-[600px] rounded-2xl border border-gray-200 bg-white flex items-center justify-center"> <div className="w-[420px] h-[600px] rounded-2xl border border-gray-200 bg-white flex items-center justify-center">
{dataLoading ? ( {!fetchDone ? (
<div className="w-5 h-5 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin-slow" /> <div className="w-5 h-5 border-2 border-gray-300 border-t-gray-600 rounded-full animate-spin-slow" />
) : ( ) : (
<p className="text-xs text-gray-400">No data available</p> <p className="text-xs text-gray-400">No data available</p>
+50 -1
View File
@@ -6,10 +6,11 @@ Serves:
/api/* -> JSON/SVG API /api/* -> JSON/SVG API
""" """
import os import os
from dataclasses import asdict
from functools import wraps from functools import wraps
from flask import Flask, jsonify, request, Response, send_from_directory 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") _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) 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: def _serve(username: str, widget_name: str) -> Response:
settings_row = db.get_settings(username) settings_row = db.get_settings(username)
+53
View File
@@ -73,3 +73,56 @@ def test_not_found_status_header(client):
c.commit() c.commit()
r = client.get("/api/ghost") r = client.get("/api/ghost")
assert r.headers["X-Widget-Status"] == "not_found" assert r.headers["X-Widget-Status"] == "not_found"
# ---- GET /api/<username>/data: computed widget data for client-side rendering ----
_FAKE_GITHUB_DATA = {
"user": {"login": "alice", "followers": 10},
"repos": [{"language": "Python", "stargazers_count": 5, "forks_count": 1, "topics": []}],
"events": [],
"commits": [],
"total_commits": 42,
"total_prs": 3,
"recent_commits": 20,
}
def test_data_endpoint_auto_enrolls_and_returns_widget_data(client, monkeypatch):
monkeypatch.setattr(
apimod.fetcher_client, "get_data",
lambda u: {"data": _FAKE_GITHUB_DATA, "payload_hash": "h1", "fetched": True},
)
r = client.get("/api/alice/data")
assert r.status_code == 200
body = r.get_json()
assert "data" in body
for key in ("grade", "impact", "collaborators", "focus", "languages"):
assert key in body["data"]
assert body["data"]["grade"]["grade"] # non-empty letter grade
assert dbmod.get_settings("alice") is not None # auto-enrolled
def test_data_endpoint_returns_404_for_unknown_github_user(client, monkeypatch):
monkeypatch.setattr(
apimod.fetcher_client, "get_data",
lambda u: {"data": {"error": "not_found"}, "payload_hash": "nf"},
)
r = client.get("/api/ghost/data")
assert r.status_code == 404
assert r.get_json()["error"] == "not_found"
def test_data_endpoint_502_when_fetcher_fails(client, monkeypatch):
def boom(_u):
raise RuntimeError("connection refused")
monkeypatch.setattr(apimod.fetcher_client, "get_data", boom)
r = client.get("/api/alice/data")
assert r.status_code == 502
def test_data_endpoint_rate_limited_before_enroll(client, monkeypatch):
monkeypatch.setattr(apimod.config, "ENROLLMENT_DAILY_CAP", 0)
r = client.get("/api/newbie/data")
assert r.status_code == 429
assert r.get_json()["error"] == "rate_limited"