Skip to content

Instantly share code, notes, and snippets.

@aljorgevi
Last active July 17, 2024 14:53
Show Gist options
  • Save aljorgevi/868b7e6ed24685e07b5a992d05ada609 to your computer and use it in GitHub Desktop.
Save aljorgevi/868b7e6ed24685e07b5a992d05ada609 to your computer and use it in GitHub Desktop.
etc
/**
* Creates a fetch instance with a base URL, customizable headers, and a default method depending on the environment.
* @param {string} endpoint - The endpoint to request.
* @param {Object} options - The options for the fetch request, including method and headers.
* @returns {Promise<Response>} The fetch promise.
*/
function customFetch(endpoint, options = {}) {
// Define the base URL depending on the environment
const baseURL = {
development: 'http://localhost:3000',
production: 'https://api.example.com'
}[process.env.NODE_ENV || 'development'];
// Default settings for fetch options
const defaultOptions = {
method: 'GET', // Default method
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
};
// Merge default options with user-provided options
// This includes merging headers
const fetchOptions = {
...defaultOptions,
...options,
headers: { ...defaultOptions.headers, ...(options.headers || {}) }
};
// Create the full URL
const url = new URL(endpoint, baseURL).href;
return fetch(url, fetchOptions);
}
// Usage example
customFetch('/users') // No method specified, defaults to 'GET'
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
@aljorgevi
Copy link
Author

Screenshot 2023-11-07 at 13 04 47

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment