Last active
July 17, 2024 14:53
-
-
Save aljorgevi/868b7e6ed24685e07b5a992d05ada609 to your computer and use it in GitHub Desktop.
etc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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)); |
Author
aljorgevi
commented
Nov 8, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment