| 887 | * turns what comes back into a Response. |
| 888 | */ |
| 889 | export async function handleApi(env: Env, url: URL): Promise<ApiResult> { |
| 890 | if (url.pathname === '/api/session') return { body: { authenticated: true } }; |
| 891 | if (url.pathname === '/api/health') return health(env); |
| 892 | if (url.pathname === '/api/meta') return meta(env); |
| 893 | |
| 894 | const ranged = new Set(['/api/summary', '/api/timeseries', '/api/breakdown', '/api/activation', '/api/retention']); |
| 895 | if (!ranged.has(url.pathname)) return fail('not found', 404); |
| 896 | |
| 897 | const range = parseRange(url); |
| 898 | if (isApiResult(range)) return range; |
| 899 | |
| 900 | try { |
| 901 | switch (url.pathname) { |
| 902 | case '/api/summary': |
| 903 | return await summary(env, range); |
| 904 | case '/api/timeseries': |
| 905 | return await timeseries(env, url, range); |
| 906 | case '/api/breakdown': |
| 907 | return await breakdown(env, url, range); |
| 908 | case '/api/activation': |
| 909 | return await activation(env, url, range); |
| 910 | case '/api/retention': |
| 911 | return await retention(env, range); |
| 912 | default: |
| 913 | return fail('not found', 404); |
| 914 | } |
| 915 | } catch (err) { |
| 916 | // The query failed, not the caller. Log the cause, tell the page something |
| 917 | // it can put in the panel, and let the other panels carry on. |
| 918 | console.error(JSON.stringify({ msg: 'api query failed', path: url.pathname, err: String(err) })); |
| 919 | return { body: { error: 'query failed' }, status: 503 }; |
| 920 | } |
| 921 | } |