@smartsamurai/krapi-sdk
Version:
KRAPI TypeScript SDK - Easy-to-use client SDK for connecting to self-hosted KRAPI servers (like Appwrite SDK)
96 lines (81 loc) • 2.32 kB
text/typescript
/**
* Response Normalizer
*
* Utility functions for normalizing inconsistent API responses.
*/
// Note: ApiResponse and PaginatedResponse imported for future use
import { Document, Collection } from "../types";
/**
* Response Normalizer class
*/
export class ResponseNormalizer {
/**
* Normalize document list responses from different API formats
*/
static normalizeDocumentListResponse(
response: unknown
): Document[] {
if (!response) return [];
// Handle different response formats
if (Array.isArray(response)) {
return response as Document[];
}
if (typeof response === "object" && response !== null) {
// Check for { data: [...] } format
if ("data" in response) {
const data = (response as { data?: unknown }).data;
if (Array.isArray(data)) {
return data as Document[];
}
}
// Check for { documents: [...] } format
if ("documents" in response) {
const documents = (response as { documents?: unknown }).documents;
if (Array.isArray(documents)) {
return documents as Document[];
}
}
}
return [];
}
/**
* Normalize single document responses
*/
static normalizeDocumentResponse(
response: unknown
): Document {
if (!response) return {} as Document;
if (typeof response === "object" && response !== null) {
// Check for { data: {...} } format
if ("data" in response) {
const data = (response as { data?: unknown }).data;
if (data && typeof data === "object") {
return data as Document;
}
}
// Direct object format
return response as Document;
}
return {} as Document;
}
/**
* Normalize collection responses
*/
static normalizeCollectionResponse(
response: unknown
): Collection {
if (!response) return {} as Collection;
if (typeof response === "object" && response !== null) {
// Check for { data: {...} } format
if ("data" in response) {
const data = (response as { data?: unknown }).data;
if (data && typeof data === "object") {
return data as Collection;
}
}
// Direct object format
return response as Collection;
}
return {} as Collection;
}
}