You can intercept the request/response lifecycle by providing onRequest, onResponse, and onError hooks in the initialization configuration. This is useful for adding custom headers, implementing automatic retries, or custom caching.
Available Hooks
onRequest(resource, config)
Called before a request is made. Can be async.
resource: The API endpoint being called.config: An object containing:cancelRequest: Function to cancel the request.headers: The Headers object (can be modified).options: Original initialization options (cache, testMode, timeout).params: Query parameters (can be modified).type: String identifying the resource type.
- Note: You must return
options, headers, and params from this hook.
onResponse(response, config)
Called after a response is received. Can be async.
response: A clone of the JS Fetch Response object.config: Contains options, params, and type.- Note: This hook expects no return value.
onError(errors, config)
Called when an error occurs. This is not an async function.
errors: An object containing { details: "Error details" }.config: Contains options, params, and type.- Note: This hook expects no return value.
Example Configuration
const butter = Butter("your_api_token", {
onRequest: async (resource, config) => {
// Modify headers or params here
return { ...config, headers: config.headers };
},
onResponse: async (response, config) => {
// Handle response
},
onError: (errors, config) => {
console.error("API Error:", errors.details);
}
});
const butter = Butter(
"your butter API token",
{
onError: Function,
onRequest: Function,
onResponse: Function
}
);