Files
jackwener__opencli/clis/openfda/utils.js
jakevin f033481e67 feat: 2 read adapters (wttr, openfda) + contract tests (#1355)
* feat: 2 read adapters across 2 new sites + contract tests (wttr, openfda)

Trimmed from original Round 11 per WAWQAQ feedback (msg=3899a382): drop
novelty/niche sites (timeapi / zippopotam / spacedevs / citybik) — keep
only sites with clear real-world utility:

- wttr (current, forecast) — wttr.in weather, no auth, simple text/json toggle
- openfda (drug-label, food-recall) — FDA drug labels + food recall enforcement

13 contract tests across 2 sites cover Lucene operator query construction
(openfda +AND+ literal handling), [string] 1-elem array unwrap, brand-OR-
generic match, wttr [{value:"..."}] array-of-objects 1-elem unwrap.

Manifest 757→759 (+2). Audits clean: typed-error-lint=196 baseline.

* fix(openfda): use brand or generic label search
2026-05-06 17:47:05 +08:00

68 lines
2.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// openFDA shared helpers — FDA drug labels + food recall enforcement (no auth, public).
//
// Free public tier with anonymous rate limit (~240 req/min, 1000 req/day per IP).
// API key bumps that to 240 req/min × ~120000 req/day, but is not required for
// modest read traffic.
import { ArgumentError, EmptyResultError, CommandExecutionError } from '@jackwener/opencli/errors';
export const OPENFDA_BASE = 'https://api.fda.gov';
const UA = 'opencli-openfda/1.0';
export function requireString(value, name) {
if (typeof value !== 'string' || !value.trim()) {
throw new ArgumentError(`--${name} is required`);
}
return value.trim();
}
export function requireBoundedInt(value, def, max, name = 'limit') {
const n = value == null || value === '' ? def : Number(value);
if (!Number.isInteger(n) || n < 1 || n > max) {
throw new ArgumentError(`--${name} must be an integer between 1 and ${max}`);
}
return n;
}
export async function openfdaFetch(url, label) {
let resp;
try {
resp = await fetch(url, { headers: { 'User-Agent': UA, accept: 'application/json' } });
} catch (err) {
throw new CommandExecutionError(`${label} request failed: ${err.message}`);
}
if (resp.status === 404) {
// openFDA returns 404 for "no matches" instead of an empty results array.
throw new EmptyResultError(label, `${label} returned 404 (no matches).`);
}
if (resp.status === 429) {
throw new CommandExecutionError(`${label} rate-limited (HTTP 429); back off and retry.`);
}
if (!resp.ok) {
throw new CommandExecutionError(`${label} returned HTTP ${resp.status}.`);
}
let body;
try {
body = await resp.json();
} catch (err) {
throw new CommandExecutionError(`${label} returned non-JSON body: ${err.message}`);
}
return body;
}
// openFDA returns most string fields as `[string]` arrays — collapse to first
// element. Preserves `null` (not coerced to empty string) when the slot is
// missing entirely.
export function firstOrNull(arr) {
if (!Array.isArray(arr) || !arr.length) return null;
const v = arr[0];
if (typeof v !== 'string') return v ?? null;
const trimmed = v.trim();
return trimmed.length ? trimmed : null;
}
// Comma-join an array of strings, preserving null when empty.
export function joinOrNull(arr, max = 5) {
if (!Array.isArray(arr) || !arr.length) return null;
return arr.slice(0, max).map(String).join(', ');
}