重构请求逻辑,增加 fetch 超时与错误处理,并配置 pnpm 工作区

This commit is contained in:
YanHao
2026-05-20 10:04:34 +08:00
parent a9504c0cf6
commit 1488aca8f9
3 changed files with 34 additions and 5 deletions
+1
View File
@@ -52,6 +52,7 @@ build/Release
node_modules/
jspm_packages/
.omo/run-continuation/
# Snowpack dependency directory (https://snowpack.dev/)
+4
View File
@@ -0,0 +1,4 @@
allowBuilds:
esbuild: true
sharp: true
workerd: true
+29 -5
View File
@@ -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