Built-in HTTP client with automatic caching, transformation support, and error handling for fetching remote data. The client is built on top of the got library and provides intelligent caching with TTL support.
Fetch remote data with automatic JSON parsing, caching, and error handling.
/**
* Fetch remote data with caching and transformation support
* @param url - URL to fetch (must be a string)
* @param options - Configuration options extending got options
* @returns Promise resolving to the response body or transformed data
*/
function fetch(url: string, options?: FetchOptions): Promise<unknown>;
interface FetchOptions extends Partial<GotOptions> {
/** Number of milliseconds to cache the response */
maxAge?: number;
/** Transform function applied before caching */
transform?: (body: unknown) => unknown;
/** Parse response as JSON (default: true) */
json?: boolean;
/** Return only response body vs full response (default: true) */
resolveBodyOnly?: boolean;
}Basic Usage:
import alfy from "alfy";
// Simple JSON fetch
const posts = await alfy.fetch('https://jsonplaceholder.typicode.com/posts');
console.log(posts); // Array of post objects
// Fetch with caching (1 hour)
const data = await alfy.fetch('https://api.example.com/data', {
maxAge: 60 * 60 * 1000 // Cache for 1 hour
});
// Fetch text content
const html = await alfy.fetch('https://example.com', {
json: false // Returns text instead of parsing JSON
});Transform responses before they are cached using the transform option.
/**
* Transform function receives response data and returns modified data
* Can return a Promise for asynchronous transformations
*/
type TransformFunction = (body: unknown) => unknown | Promise<unknown>;Usage Examples:
import alfy from "alfy";
// Transform API response
const users = await alfy.fetch('https://api.example.com/users', {
transform: (data) => {
// Add computed properties and filter
return data.users
.filter(user => user.active)
.map(user => ({
...user,
displayName: `${user.firstName} ${user.lastName}`,
initials: user.firstName[0] + user.lastName[0]
}));
},
maxAge: 5 * 60 * 1000 // Cache transformed data for 5 minutes
});
// Transform full response object
const apiData = await alfy.fetch('https://api.example.com/data', {
resolveBodyOnly: false,
transform: (response) => {
// Access headers and body
return {
data: response.body,
lastModified: response.headers['last-modified'],
etag: response.headers.etag
};
}
});
// Asynchronous transformation with external processing
const processedData = await alfy.fetch('https://api.example.com/xml', {
json: false,
transform: async (xmlString) => {
const xml2js = await import('xml2js');
const parser = new xml2js.Parser();
return parser.parseStringPromise(xmlString);
}
});The fetch function includes intelligent caching with the following features:
maxAgeCaching Examples:
import alfy from "alfy";
// Cache for 10 minutes
const shortCache = await alfy.fetch('https://api.example.com/status', {
maxAge: 10 * 60 * 1000
});
// Cache for 24 hours
const longCache = await alfy.fetch('https://api.example.com/config', {
maxAge: 24 * 60 * 60 * 1000
});
// No caching (always fetch fresh)
const fresh = await alfy.fetch('https://api.example.com/realtime');
// Without maxAge, data is fetched fresh each time but may still use cache on errorThe fetch function provides robust error handling:
Error Handling Examples:
import alfy from "alfy";
try {
const data = await alfy.fetch('https://unreliable-api.com/data', {
maxAge: 60 * 60 * 1000, // 1 hour cache
transform: (response) => {
if (!response.success) {
throw new Error(`API Error: ${response.message}`);
}
return response.data;
}
});
console.log('Fresh or cached data:', data);
} catch (error) {
console.error('Fetch failed:', error.message);
// Alfy will automatically show user-friendly error in Alfred
}
// The fetch function will automatically return cached data
// if network fails but cache exists, so this often succeeds
// even when the API is temporarily unavailableThe fetch function accepts all standard got options for advanced HTTP configuration:
import alfy from "alfy";
// Custom headers and authentication
const apiData = await alfy.fetch('https://api.example.com/private', {
headers: {
'Authorization': 'Bearer ' + process.env.API_TOKEN,
'User-Agent': 'MyWorkflow/1.0'
},
timeout: {
request: 10000 // 10 second timeout
},
retry: {
limit: 3 // Retry failed requests 3 times
},
maxAge: 5 * 60 * 1000 // Cache for 5 minutes
});
// POST request with JSON body
const result = await alfy.fetch('https://api.example.com/submit', {
method: 'POST',
json: {
name: 'John Doe',
email: 'john@example.com'
},
responseType: 'json'
});