Here's a robust TypeScript implementation for fetching files with proper error handling and type safety:
typescript Copy code
// types.ts
export type FetchFileOptions = {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
headers?: Record<string, string>;
body?: BodyInit;
timeout?: number;
responseType?: 'json' | 'text' | 'blob' | 'arraybuffer';
signal?: AbortSignal;
};
export type FetchFileResult<T = unknown> = {
data: T | null;
error: Error | null;
status: number | null;
statusText: string | null;
headers: Headers | null;
};
// fetchFile.ts
import { FetchFileOptions, FetchFileResult } from './types';
export async function fetchFile<T = unknown>(
url: string,
options: FetchFileOptions = {}
): Promise<FetchFileResult<T>> {
const {
method = 'GET',
headers = {},
body = null,
timeout = 8000,
responseType = 'json',
signal: externalSignal,
} = options;
const controller = new AbortController();
const signal = externalSignal || controller.signal;
const timeoutId = timeout
? setTimeout(() => controller.abort(`Request timed out after ${timeout}ms`), timeout)
: null;
const result: FetchFileResult<T> = {
data: null,
error: null,
status: null,
statusText: null,
headers: null,
};
try {
const response = await fetch(url, {
method,
headers,
body,
signal,
});
result.status = response.status;
result.statusText = response.statusText;
result.headers = response.headers;
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
try {
switch (responseType) {
case 'json':
result.data = (await response.json()) as T;
break;
case 'text':
result.data = (await response.text()) as T;
break;
case 'blob':
result.data = (await response.blob()) as T;
break;
case 'arraybuffer':
result.data = (await response.arrayBuffer()) as T;
break;
default:
throw new Error(`Unsupported responseType: ${responseType}`);
}
} catch (parseError) {
throw new Error(`Failed to parse response as ${responseType}: ${parseError instanceof Error ? parseError.message : String(parseError)}`);
}
} catch (error) {
result.error = error instanceof Error
? error
: new Error(String(error));
} finally {
if (timeoutId) clearTimeout(timeoutId);
}
return result;
}
// Example usage:
/*
async function exampleUsage() {
const { data, error, status } = await fetchFile<{ id: number; name: string }>(
'https://api.example.com/data',
{
responseType: 'json',
timeout: 5000,
headers: {
'Content-Type': 'application/json',
},
}
);
if (error) {
console.error('Fetch failed:', error.message);
return;
}
if (data) {
console.log('Received data:', data);
console.log('Status:', status);
}
}
*/
This implementation provides a robust foundation for file fetching in TypeScript applications with proper error handling at every stage of the process.