mirror of
https://github.com/rzmk/learnhouse.git
synced 2025-12-19 04:19:25 +00:00
feat: implement runtime configuration and API client enhancements
This commit is contained in:
parent
4663256eed
commit
78cabbc665
6 changed files with 225 additions and 4 deletions
59
apps/web/utils/apiClient.js
Normal file
59
apps/web/utils/apiClient.js
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { getApiUrl } from './runtimeConfig';
|
||||
|
||||
/**
|
||||
* Creates an API client that uses runtime configuration
|
||||
* @returns {Object} API client object with fetch method
|
||||
*/
|
||||
export function createApiClient() {
|
||||
return {
|
||||
/**
|
||||
* Fetch data from the API with the correct runtime URL
|
||||
* @param {string} path - API path to fetch from
|
||||
* @param {Object} options - Fetch options
|
||||
* @returns {Promise<any>} - JSON response
|
||||
*/
|
||||
fetch: async (path, options = {}) => {
|
||||
const url = getApiUrl(path);
|
||||
console.log(`[API] Fetching from: ${url}`);
|
||||
|
||||
const response = await fetch(url, options);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`API request failed: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
},
|
||||
|
||||
/**
|
||||
* Post data to the API with the correct runtime URL
|
||||
* @param {string} path - API path to post to
|
||||
* @param {Object} data - Data to post
|
||||
* @param {Object} options - Additional fetch options
|
||||
* @returns {Promise<any>} - JSON response
|
||||
*/
|
||||
post: async (path, data, options = {}) => {
|
||||
const url = getApiUrl(path);
|
||||
console.log(`[API] Posting to: ${url}`);
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers,
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
...options,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`API request failed: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Create a singleton instance for easier imports
|
||||
export const apiClient = createApiClient();
|
||||
Loading…
Add table
Add a link
Reference in a new issue