From 1488aca8f938a27364cadebe6f7b49196fafadca Mon Sep 17 00:00:00 2001 From: YanHao Date: Wed, 20 May 2026 10:04:34 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=9E=84=E8=AF=B7=E6=B1=82=E9=80=BB?= =?UTF-8?q?=E8=BE=91=EF=BC=8C=E5=A2=9E=E5=8A=A0=20fetch=20=E8=B6=85?= =?UTF-8?q?=E6=97=B6=E4=B8=8E=E9=94=99=E8=AF=AF=E5=A4=84=E7=90=86=EF=BC=8C?= =?UTF-8?q?=E5=B9=B6=E9=85=8D=E7=BD=AE=20pnpm=20=E5=B7=A5=E4=BD=9C?= =?UTF-8?q?=E5=8C=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + pnpm-workspace.yaml | 4 ++++ src/index.js | 34 +++++++++++++++++++++++++++++----- 3 files changed, 34 insertions(+), 5 deletions(-) create mode 100644 pnpm-workspace.yaml diff --git a/.gitignore b/.gitignore index 3b0fe33..2a92025 100644 --- a/.gitignore +++ b/.gitignore @@ -52,6 +52,7 @@ build/Release node_modules/ jspm_packages/ +.omo/run-continuation/ # Snowpack dependency directory (https://snowpack.dev/) diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..661850f --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,4 @@ +allowBuilds: + esbuild: true + sharp: true + workerd: true diff --git a/src/index.js b/src/index.js index baf9371..ba836aa 100644 --- a/src/index.js +++ b/src/index.js @@ -26,10 +26,12 @@ async function handleRequest(request) { const location = getRandomLocationInState(state); const apiUrl = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${location.lat}&lon=${location.lng}&zoom=18&addressdetails=1`; - const response = await fetch(apiUrl, { - headers: { 'User-Agent': 'Cloudflare Worker' }, + const data = await fetchJson(apiUrl, { + headers: { 'User-Agent': 'Real-US-Address-Generator-API/1.0' }, }); - const data = await response.json(); + if (!data) { + break; + } if (data && data.address) { if (data.address.country_code === 'us') { @@ -66,8 +68,7 @@ async function handleRequest(request) { ); } - const userResp = await fetch('https://fakerapi.it/api/v1/persons?_quantity=1&_locale=en_US'); - const userJson = await userResp.json(); + const userJson = await fetchJson('https://fakerapi.it/api/v1/persons?_quantity=1&_locale=en_US'); let firstName, lastName; if (userJson && userJson.data && userJson.data.length > 0) { const user = userJson.data[0]; @@ -170,6 +171,29 @@ async function handleRequest(request) { }); } +async function fetchJson(url, init = {}) { + let response; + try { + response = await fetch(url, { + ...init, + signal: AbortSignal.timeout(5000), + }); + } catch { + return null; + } + + const contentType = response.headers.get('content-type') || ''; + if (!response.ok || !contentType.includes('application/json')) { + return null; + } + + try { + return await response.json(); + } catch { + return null; + } +} + function getRandomLocationInState(state) { const stateCoordinates = { // US States