All files / src/components/hooks apiClient.js

0% Statements 0/28
0% Branches 0/24
0% Functions 0/1
0% Lines 0/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45                                                                                         
const BASE_URL = 'https://api.smartindustries.fontysict.net/api';
 
export const apiRequest = async (collection, action, payload = {}) => {
	try {
		let url = `${BASE_URL}/${collection}`;
		const method = action.toUpperCase();
 
		const options = {
			method,
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json',
			},
		};
 
		// Handling GET, POST/PUT and DELETE requests
		if (method === 'GET') {
			const params = new URLSearchParams(payload).toString();
			if (params) url += `?${params}`;
		} else if (['POST', 'PUT'].includes(method)) {
			options.body = JSON.stringify(payload);
		} else if (method === 'DELETE') {
			const id = payload._id || payload.macAddress;
			if (!id) throw new Error('ID of macAddress need to be deleted');
			url += `/${id}`;
		}
 
		const res = await fetch(url, options);
		if (!res.ok) {
			const text = await res.text();
			console.error(`HTTP ${res.status}: ${text}`);
			return [];
		}
		const data = await res.json();
		return Array.isArray(data) && data.length === 1 ? data[0] : data;
 
	} catch (error) {
		if (error instanceof TypeError && (error.message === 'Failed to fetch' || error.message.includes('NetworkError'))) {
			console.error('API request failed: possible CORS error of netwerk problem (Access denied)');
		} else {
			console.error('API request failed:', error);
		}
		return [];
	}
};