import { backendUrl } from "$lib/constants.js"; import { state, testMode } from "$lib/state.js"; export const deepCopy = object => JSON.parse(JSON.stringify(object)) export const getRandomFromArray = array => array[Math.floor(Math.random() * array.length)] export const findLast = array => { if (!array || array.length === 0) { return undefined } return array[array.length - 1] } const jsonRequest = type => async (path, object) => fetch(backendUrl + path, { method: type, body: JSON.stringify(object), headers: { 'Content-Type': 'application/json' } }) /** * * @param path * @param object * @returns {Promise<*|undefined>} */ export const postJson = (path, object) => jsonRequest('POST')(path, object) export const putJson = (path, object) => jsonRequest('PUT')(path, object) const mockApi = { '/clusters': { 'TestCluster': { clientId: 'TestClient', brokers: ['testbroker.com:5000'], ssl: true, sasl: { mechanism: 'SCRAM-SHA-512', username: 'testuser', password: 'XXXXXXXXXXXXXXXXXXXXXX' } } }, '/topics/TestCluster': ['NewReleases'] } /** * Returns the JSON response from the given path, or undefined if an error occurred * Sets `state.error` if something goes wrong. * @param path * @param options Options object to pass to `fetch()` * @returns {Promise} */ export const apiFetch = async (path, options = undefined) => { if (testMode) { return mockApi[path] } let response try { response = await fetch(`${backendUrl}${path}`, options) } catch (e) { console.error(e) state.update(s => ({ ...s, error: 'Could not connect to the backend' })) return undefined } try { const json = await response.json() if (json.error) { state.update(s => ({ ...s, error: json.error, errorDetails: json.errorDetails })) } return json } catch (e) { console.error(e) state.update(s => ({ ...s, error: 'Received non-JSON response from backend' })) return undefined } }