fix: treat empty IMGW warning products as no warnings
This commit is contained in:
17
lib/imgw-empty-response.ts
Normal file
17
lib/imgw-empty-response.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
export function isImgwNoProductsResponse(value: unknown) {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const response = value as { status?: unknown; message?: unknown };
|
||||
return response.status === false
|
||||
&& typeof response.message === "string"
|
||||
&& response.message.toLocaleLowerCase("en-US").includes("no products were found");
|
||||
}
|
||||
|
||||
export async function readImgwResponseBody(response: Response) {
|
||||
const text = await response.text().catch(() => "");
|
||||
if (!text) return { text, json: null as unknown };
|
||||
try {
|
||||
return { text, json: JSON.parse(text) as unknown };
|
||||
} catch {
|
||||
return { text, json: null as unknown };
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { normalizeWarning } from "@/lib/weather-utils";
|
||||
import { isImgwNoProductsResponse, readImgwResponseBody } from "@/lib/imgw-empty-response";
|
||||
import type { RawWarning, WeatherWarning } from "@/types/imgw";
|
||||
|
||||
const IMGW_WARNINGS_METEO_URL = "https://danepubliczne.imgw.pl/api/data/warningsmeteo";
|
||||
@@ -11,8 +12,9 @@ export async function fetchMeteoWarnings(signal?: AbortSignal): Promise<WeatherW
|
||||
signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
const details = await response.text().catch(() => "");
|
||||
throw new Error(`Unable to load IMGW meteorological warnings: ${response.status}${details ? ` ${details.slice(0, 240)}` : ""}`);
|
||||
const details = await readImgwResponseBody(response);
|
||||
if (response.status === 404 && isImgwNoProductsResponse(details.json)) return [];
|
||||
throw new Error(`Unable to load IMGW meteorological warnings: ${response.status}${details.text ? ` ${details.text.slice(0, 240)}` : ""}`);
|
||||
}
|
||||
const rows = await response.json() as RawWarning[];
|
||||
return Array.isArray(rows) ? rows.map((warning, index) => normalizeWarning(warning, "meteo", index)) : [];
|
||||
|
||||
Reference in New Issue
Block a user