forked from sagnik/Velocity-OS
46 lines
1.4 KiB
TypeScript
46 lines
1.4 KiB
TypeScript
type JsonRecord = Record<string, unknown>;
|
|
|
|
function isRecord(value: unknown): value is JsonRecord {
|
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
}
|
|
|
|
/**
|
|
* Accepts the response shapes used across the legacy Velocity API, the newer
|
|
* WebOS API, and paginated read endpoints. Components should render arrays,
|
|
* not transport envelopes.
|
|
*/
|
|
export function unwrapArray<T>(payload: unknown, keys: string[] = []): T[] {
|
|
if (Array.isArray(payload)) return payload as T[];
|
|
if (!isRecord(payload)) return [];
|
|
|
|
for (const key of [...keys, 'data', 'items', 'results', 'records', 'rows', 'value']) {
|
|
const candidate = payload[key];
|
|
if (Array.isArray(candidate)) return candidate as T[];
|
|
}
|
|
|
|
for (const key of ['data', 'result', 'payload', 'body']) {
|
|
const candidate = payload[key];
|
|
if (isRecord(candidate)) {
|
|
const nested = unwrapArray<T>(candidate, keys);
|
|
if (nested.length > 0) return nested;
|
|
}
|
|
}
|
|
|
|
return [];
|
|
}
|
|
|
|
export function unwrapObject<T>(payload: unknown, keys: string[] = []): T | undefined {
|
|
if (!isRecord(payload)) return undefined;
|
|
|
|
for (const key of [...keys, 'data', 'record', 'result', 'item', 'value']) {
|
|
const candidate = payload[key];
|
|
if (isRecord(candidate)) return candidate as T;
|
|
}
|
|
|
|
return payload as T;
|
|
}
|
|
|
|
export function stableArray<T>(value: unknown): T[] {
|
|
return Array.isArray(value) ? value as T[] : [];
|
|
}
|