mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
feat(api): add endpoint for fetching computed widget data by username.
This commit is contained in:
@@ -3,6 +3,7 @@ import './index.css'
|
||||
import { SearchScreen } from './screens/SearchScreen'
|
||||
import { WorkshopScreen } from './screens/WorkshopScreen'
|
||||
import { ResultScreen } from './screens/ResultScreen'
|
||||
import type { WidgetData } from './lib/renderWidgets'
|
||||
|
||||
export type Achievement = {
|
||||
title: string
|
||||
@@ -46,6 +47,7 @@ export default function App() {
|
||||
const [step, setStep] = useState<Step>('search')
|
||||
const [username, setUsername] = useState('')
|
||||
const [settings, setSettings] = useState<WidgetSettings>({ ...DEFAULT_SETTINGS })
|
||||
const [widgetData, setWidgetData] = useState<WidgetData | null>(null)
|
||||
const [fetchDone, setFetchDone] = useState(false)
|
||||
const [fetchError, setFetchError] = useState<string | null>(null)
|
||||
const fetchRef = useRef<AbortController | null>(null)
|
||||
@@ -56,18 +58,18 @@ export default function App() {
|
||||
fetchRef.current = ctrl
|
||||
setFetchDone(false)
|
||||
setFetchError(null)
|
||||
setWidgetData(null)
|
||||
|
||||
fetch('/api/fetch', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username: user }),
|
||||
signal: ctrl.signal,
|
||||
})
|
||||
.then(r => {
|
||||
fetch(`/api/${encodeURIComponent(user)}/data`, { signal: ctrl.signal })
|
||||
.then(async r => {
|
||||
if (r.status === 404) throw new Error('User not found')
|
||||
if (!r.ok) throw new Error(`Fetch failed (${r.status})`)
|
||||
return r.json()
|
||||
})
|
||||
.then(() => setFetchDone(true))
|
||||
.then(json => {
|
||||
setWidgetData(json.data)
|
||||
setFetchDone(true)
|
||||
})
|
||||
.catch(e => {
|
||||
if (e.name !== 'AbortError') {
|
||||
console.warn('Fetch error:', e)
|
||||
@@ -108,6 +110,7 @@ export default function App() {
|
||||
onGenerate={handleGenerate}
|
||||
onBack={handleBack}
|
||||
fetchDone={fetchDone}
|
||||
widgetData={widgetData}
|
||||
/>
|
||||
)}
|
||||
{step === 'result' && (
|
||||
@@ -116,6 +119,7 @@ export default function App() {
|
||||
settings={settings}
|
||||
fetchDone={fetchDone}
|
||||
fetchError={fetchError}
|
||||
widgetData={widgetData}
|
||||
onBack={handleBack}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useMemo } from 'react'
|
||||
import DOMPurify from 'dompurify'
|
||||
import type { WidgetSettings } from '../App'
|
||||
import { renderAllWidgets, type WidgetData } from '../lib/renderWidgets'
|
||||
|
||||
function sanitizeSvg(raw: string): string {
|
||||
return DOMPurify.sanitize(raw, {
|
||||
@@ -15,44 +16,24 @@ type Props = {
|
||||
settings: WidgetSettings
|
||||
fetchDone: boolean
|
||||
fetchError: string | null
|
||||
widgetData: WidgetData | null
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
export function ResultScreen({ username, settings, fetchDone, fetchError, onBack }: Props) {
|
||||
const [svgContent, setSvgContent] = useState<string>('')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [generated, setGenerated] = useState(false)
|
||||
|
||||
// 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,
|
||||
export function ResultScreen({ username, settings, fetchDone, fetchError, widgetData, onBack }: Props) {
|
||||
const svgContent = useMemo(() => {
|
||||
if (!widgetData) return ''
|
||||
const raw = renderAllWidgets({
|
||||
data: widgetData,
|
||||
theme: settings.theme,
|
||||
widgets: settings.widgets,
|
||||
widget_order: ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'],
|
||||
custom_tags: settings.customTags.length ? settings.customTags : undefined,
|
||||
hidden_languages: settings.hiddenLanguages.length ? settings.hiddenLanguages : undefined,
|
||||
widgetOrder: ['grade', 'impact', 'collaborators', 'focus', 'languages', 'achievements'],
|
||||
achievements: settings.achievements.filter(a => a.title.trim()),
|
||||
widget_settings: settings.widgetSettings,
|
||||
format: 'svg',
|
||||
}),
|
||||
widgetSettings: settings.widgetSettings,
|
||||
username,
|
||||
})
|
||||
.then(r => r.text())
|
||||
.then(svg => {
|
||||
// SVG is sanitized via DOMPurify before rendering
|
||||
setSvgContent(sanitizeSvg(svg))
|
||||
setLoading(false)
|
||||
setGenerated(true)
|
||||
})
|
||||
.catch(() => setLoading(false))
|
||||
}, [fetchDone])
|
||||
return sanitizeSvg(raw)
|
||||
}, [widgetData, settings, username])
|
||||
|
||||
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" />
|
||||
<p className="text-xs text-gray-400">Generating with real data...</p>
|
||||
</div>
|
||||
) : loading ? (
|
||||
) : !svgContent ? (
|
||||
<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-xs text-gray-400">Rendering...</p>
|
||||
<p className="text-[10px] text-amber-500">
|
||||
{fetchError ?? 'Could not fetch live data'}
|
||||
</p>
|
||||
</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">
|
||||
Generated with real data
|
||||
</p>
|
||||
)}
|
||||
{/* SVG content is sanitized with DOMPurify.sanitize() before rendering */}
|
||||
{/* SVG sanitized via DOMPurify.sanitize() before rendering */}
|
||||
<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 { renderAllWidgets, type WidgetData } from '../lib/renderWidgets'
|
||||
|
||||
@@ -85,6 +85,7 @@ type Props = {
|
||||
onGenerate: () => void
|
||||
onBack: () => void
|
||||
fetchDone: boolean
|
||||
widgetData: WidgetData | null
|
||||
}
|
||||
|
||||
export function WorkshopScreen({
|
||||
@@ -94,11 +95,9 @@ export function WorkshopScreen({
|
||||
onGenerate,
|
||||
onBack,
|
||||
fetchDone,
|
||||
widgetData,
|
||||
}: Props) {
|
||||
const [widgetData, setWidgetData] = useState<WidgetData | null>(null)
|
||||
const [dataLoading, setDataLoading] = useState(true)
|
||||
const [expandedWidget, setExpandedWidget] = useState<string | null>(null)
|
||||
const dataFetched = useRef(false)
|
||||
|
||||
const updateSetting = <K extends keyof WidgetSettings>(key: K, val: WidgetSettings[K]) => {
|
||||
onSettingsChange({ ...settings, [key]: val })
|
||||
@@ -144,32 +143,6 @@ export function WorkshopScreen({
|
||||
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)
|
||||
const svgContent = useMemo(() => {
|
||||
if (!widgetData) return ''
|
||||
@@ -440,7 +413,7 @@ export function WorkshopScreen({
|
||||
<div dangerouslySetInnerHTML={{ __html: svgContent }} />
|
||||
) : (
|
||||
<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" />
|
||||
) : (
|
||||
<p className="text-xs text-gray-400">No data available</p>
|
||||
|
||||
+50
-1
@@ -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)
|
||||
|
||||
|
||||
@@ -73,3 +73,56 @@ def test_not_found_status_header(client):
|
||||
c.commit()
|
||||
r = client.get("/api/ghost")
|
||||
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"
|
||||
|
||||
Reference in New Issue
Block a user