Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | 13x 13x 13x 2x 2x 2x 6x 77x 83x 83x 83x 83x 83x 80x 80x 76x 3x 3x 7x 89x 89x 86x 73x 73x 73x 73x 87x 87x 77x 77x 77x 76x 12x 64x 10x 10x 1x 9x 89x 2x 1x 2x 1x 3x 1x 2x 1x 2x 1x 2x 1x 2x 2x | // API client factory and fetch wrapper with in-memory caching
import { cachedFetch } from "./cache";
import { createBaseApiMethods } from "./client.methods";
/**
* Error thrown for any non-ok API response. Carries the HTTP `status` so callers
* can distinguish "not found" (404) from a genuine upstream failure. The message
* stays `API error: ${status}` for backward compatibility with existing matchers
* (e.g. inquiry.ts `.message.includes("API error: 429")`).
*/
export class ApiError extends Error {
readonly status: number;
constructor(status: number) {
super(`API error: ${status}`);
this.name = "ApiError";
this.status = status;
}
}
// Cold-path resilience for GET reads. A cold isolate hitting a cold API/D1 can
// see a transient timeout or 5xx; one immediate retry almost always succeeds —
// the server-side equivalent of the user hitting reload. NEVER retry a 4xx,
// including 429: retrying into a rate limit is pointless and abusive.
const FETCH_TIMEOUT_MS = 4000;
const RETRY_DELAY_MS = 150;
const sleep = (ms: number) =>
new Promise<void>((resolve) => setTimeout(resolve, ms));
async function fetchWithRetry(url: string, init: RequestInit): Promise<Response> {
let lastErr: unknown;
for (let attempt = 0; attempt < 2; attempt++) {
if (attempt > 0) await sleep(RETRY_DELAY_MS);
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
try {
const res = await fetch(url, { ...init, signal: controller.signal });
clearTimeout(timer);
// Retry a 5xx once; pass everything else (2xx–4xx, incl. 429) straight back.
if (res.status >= 500 && attempt === 0) continue;
return res;
} catch (err) {
clearTimeout(timer);
lastErr = err; // network error or timeout (abort) — retry once
}
}
throw lastErr;
}
export function createApiClient(apiUrl: string, apiKey?: string) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (apiKey) {
headers["X-API-Key"] = apiKey;
}
// The API returns pagination under `meta` (see apps/api/src/lib/response.ts:59),
// but ApiResponse<T> in types.ts exposes it as `pagination`. Normalize here so
// the type contract matches runtime for every caller.
function normalizeResponse<T>(json: unknown): T {
Eif (json && typeof json === "object") {
const obj = json as Record<string, unknown>;
Iif (obj.meta && obj.pagination === undefined) {
obj.pagination = obj.meta;
}
}
return json as T;
}
async function fetchApi<T>(
endpoint: string,
options?: RequestInit,
): Promise<T> {
const isGet = !options?.method || options.method === "GET";
// Two-layer caching for GET reads:
// L1 = in-memory per-isolate (cachedFetch, 5 min) — fast repeats inside
// one Worker isolate.
// L2 = Cloudflare's edge cache for the fetch() subrequest — survives
// isolate recycling, so a COLD isolate hits the cached API response
// instead of live D1. Enabled simply by NOT setting `cache:
// "no-store"`: Workers honor the response's Cache-Control, and the
// API already sends `public, max-age=1800` (per-endpoint: taxonomy
// 3600s, calculator-config 60s) on /api/marketplace/* and /api/taxonomy/*.
// Previously no-store forced every cold isolate to re-render from D1,
// which is the root cause of the recurring cold-SSR TTFB spikes
// (interiors ~1.4s, listings 0.5-1.1s). The API key travels as the
// custom `X-API-Key` header and responses carry no per-user data, so
// sharing the edge-cached response across requests is safe.
if (isGet) {
const cacheKey = `${apiUrl}${endpoint}`;
return cachedFetch<T>(cacheKey, async () => {
const response = await fetchWithRetry(`${apiUrl}${endpoint}`, {
...options,
headers: {
...headers,
...options?.headers,
},
});
if (!response.ok) {
throw new ApiError(response.status);
}
return normalizeResponse<T>(await response.json());
});
}
// Non-GET requests (POST, etc.) bypass cache
const response = await fetch(`${apiUrl}${endpoint}`, {
...options,
cache: "no-store",
headers: {
...headers,
...options?.headers,
},
});
if (!response.ok) {
throw new ApiError(response.status);
}
return normalizeResponse<T>(await response.json());
}
return {
...createBaseApiMethods(fetchApi),
// SEO content — DB-backed (replaces static TS content files)
// These methods use `typeof this.<method> extends Promise<infer R> ? R : never`
// for return type inference — they must stay together in one object literal.
async getSeoCity(cityId: string): Promise<{
city: {
id: string;
name: string;
headline: string | null;
intro: string | null;
faqs: { question: string; answer: string }[];
zones: { id: string; name: string; slug: string | null }[];
services: { id: string; slug: string; name: string }[];
bhkTypes: { id: string; slug: string; label: string }[];
localities: { id: string; slug: string | null; name: string; zoneId: string; zoneSlug: string | null }[];
};
}> {
const res = await fetchApi<{ data: { city: NonNullable<unknown> } }>(`/api/marketplace/seo/cities/${cityId}`);
return res.data as ReturnType<typeof this.getSeoCity> extends Promise<infer R> ? R : never;
},
async getSeoZone(cityId: string, zoneSlug: string): Promise<{
zone: {
id: string;
name: string;
slug: string | null;
tier: string | null;
headline: string | null;
intro: string | null;
priceRange: string | null;
faqs: { question: string; answer: string }[];
whatsappMessage: string | null;
localities: { id: string; slug: string | null; name: string }[];
};
}> {
const res = await fetchApi<{ data: { zone: NonNullable<unknown> } }>(`/api/marketplace/seo/cities/${cityId}/zones/${zoneSlug}`);
return res.data as ReturnType<typeof this.getSeoZone> extends Promise<infer R> ? R : never;
},
async getSeoLocality(cityId: string, zoneSlug: string, localitySlug: string): Promise<{
locality: {
id: string;
name: string;
slug: string | null;
zoneId: string;
zoneSlug: string | null;
zoneName: string;
tier: string | null;
intro: string | null;
pinCodes: string[];
landmarks: string[];
typicalHomeSize: string | null;
faqOverrides: { question: string; answer: string }[];
};
}> {
const res = await fetchApi<{ data: { locality: NonNullable<unknown> } }>(`/api/marketplace/seo/cities/${cityId}/zones/${zoneSlug}/localities/${localitySlug}`);
return res.data as ReturnType<typeof this.getSeoLocality> extends Promise<infer R> ? R : never;
},
async getSeoService(cityId: string, slug: string): Promise<{
service: {
id: string;
slug: string;
name: string;
headline: string | null;
intro: string | null;
priceRange: string | null;
priceNote: string | null;
included: string[];
excluded: string[];
timeline: string | null;
faqs: { question: string; answer: string }[];
whatsappMessage: string | null;
};
}> {
const res = await fetchApi<{ data: { service: NonNullable<unknown> } }>(`/api/marketplace/seo/cities/${cityId}/services/${slug}`);
return res.data as ReturnType<typeof this.getSeoService> extends Promise<infer R> ? R : never;
},
async getSeoFaqHub(cityId: string): Promise<{
faqSections: {
category: string;
title: string;
faqs: { question: string; answer: string }[];
}[];
}> {
const res = await fetchApi<{ data: { faqSections: NonNullable<unknown> } }>(`/api/marketplace/seo/cities/${cityId}/faq-hub`);
return res.data as ReturnType<typeof this.getSeoFaqHub> extends Promise<infer R> ? R : never;
},
async getSeoBhk(cityId: string, slug: string): Promise<{
bhkType: {
id: string;
slug: string;
label: string;
bhkCount: number;
headline: string | null;
sqftRange: string | null;
priceRange: string | null;
priceNote: string | null;
timeline: string | null;
rooms: string[];
costTable: { room: string; budget: string; comfort: string; premium: string }[];
faqs: { question: string; answer: string }[];
whatsappMessage: string | null;
};
}> {
const res = await fetchApi<{ data: { bhkType: NonNullable<unknown> } }>(`/api/marketplace/seo/cities/${cityId}/bhk/${slug}`);
return res.data as ReturnType<typeof this.getSeoBhk> extends Promise<infer R> ? R : never;
},
async getSeoRoomFAQs(category: string): Promise<{ faqs: { question: string; answer: string }[] }> {
return fetchApi<{ faqs: { question: string; answer: string }[] }>(`/api/marketplace/seo/rooms/${category}`);
},
async getSeoPage(pageKey: string): Promise<{ faqs: { question: string; answer: string }[] }> {
return fetchApi<{ faqs: { question: string; answer: string }[] }>(`/api/marketplace/seo/pages/${pageKey}`);
},
};
}
|