refactor: dedupe edge api json response assembly (#1702)

* refactor: dedupe edge api json response assembly

* refactor: expand jsonResponse helper to all edge functions

Roll out jsonResponse() from _json-response.js to 16 files (14 handlers
+ 2 shared helpers), eliminating 55 instances of the
new Response(JSON.stringify(...)) boilerplate.

Only exception: health.js uses JSON.stringify(body, null, indent) for
pretty-print mode, which is incompatible with the helper signature.

Replaced local jsonResponse/json() definitions in contact.js,
register-interest.js, and cache-purge.js with the shared import.
This commit is contained in:
Elie Habib
2026-03-16 11:52:56 +04:00
committed by GitHub
parent be93a940a3
commit bdd8743a26
19 changed files with 122 additions and 237 deletions

View File

@@ -1,5 +1,6 @@
import { getRelayBaseUrl, getRelayHeaders, fetchWithTimeout } from './_relay.js';
import { getCorsHeaders, isDisallowedOrigin } from './_cors.js';
import { jsonResponse } from './_json-response.js';
export const config = { runtime: 'edge' };
@@ -7,27 +8,18 @@ export default async function handler(req) {
const corsHeaders = getCorsHeaders(req, 'GET, OPTIONS');
if (isDisallowedOrigin(req)) {
return new Response(JSON.stringify({ error: 'Origin not allowed' }), {
status: 403,
headers: { 'Content-Type': 'application/json', ...corsHeaders },
});
return jsonResponse({ error: 'Origin not allowed' }, 403, corsHeaders);
}
if (req.method === 'OPTIONS') {
return new Response(null, { status: 204, headers: corsHeaders });
}
if (req.method !== 'GET') {
return new Response(JSON.stringify({ error: 'Method not allowed' }), {
status: 405,
headers: { 'Content-Type': 'application/json', ...corsHeaders },
});
return jsonResponse({ error: 'Method not allowed' }, 405, corsHeaders);
}
const relayBaseUrl = getRelayBaseUrl();
if (!relayBaseUrl) {
return new Response(JSON.stringify({ error: 'WS_RELAY_URL is not configured' }), {
status: 503,
headers: { 'Content-Type': 'application/json', ...corsHeaders },
});
return jsonResponse({ error: 'WS_RELAY_URL is not configured' }, 503, corsHeaders);
}
try {
@@ -65,12 +57,9 @@ export default async function handler(req) {
});
} catch (error) {
const isTimeout = error?.name === 'AbortError';
return new Response(JSON.stringify({
return jsonResponse({
error: isTimeout ? 'Relay timeout' : 'Relay request failed',
details: error?.message || String(error),
}), {
status: isTimeout ? 504 : 502,
headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...corsHeaders },
});
}, isTimeout ? 504 : 502, { 'Cache-Control': 'no-store', ...corsHeaders });
}
}