UNPKG

educa-sdk

Version:

A JavaScript SDK for interacting with the Educa backend API (Admin, Staff, and Student methods)

75 lines (60 loc) 2.03 kB
// src/api/request.js const BASE_URL = 'https://api.rigan.com.ng'; // Replace with your actual base URL //const BASE_URL = 'http://127.0.0.1:8000'; /* * Serializes query params into a URL string * @param {Object} params * @returns {string} */ const buildQueryString = (params = {}) => { const query = new URLSearchParams(); for (const key in params) { if (Array.isArray(params[key])) { params[key].forEach((val) => query.append(key, val)); } else { query.append(key, params[key]); } } return query.toString() ? `?${query.toString()}` : ''; }; /* * Main request function using Fetch API * @param {Object} config * @param {string} config.method - GET, POST, PUT, DELETE, etc. * @param {string} config.url - Endpoint path * @param {Object|FormData} [config.data] - Payload for non-GET requests * @param {Object} [config.params] - Query string params for GET/others * @param {string} [config.token] - Bearer token * @returns {Promise<Object>} */ const request = async ({ method = 'GET', url, data = null, params = {}}) => { const queryString = buildQueryString(params); const fullUrl = `${BASE_URL}${url}${queryString}`; const isFormData = data instanceof FormData; const headers = { //...({ 'Accept': 'application/json' }), ...(!isFormData && { 'Content-Type': 'application/json' }), }; const options = { method: method.toUpperCase(), credentials: "include", headers, }; if (method !== 'GET' && method !== 'HEAD' && data) { options.body = isFormData ? data : JSON.stringify(data); } try { const response = await fetch(fullUrl, options); const contentType = response.headers.get('content-type'); const isJson = contentType && contentType.includes('application/json'); const responseData = isJson ? await response.json() : await response.text(); if (!response.ok) { throw responseData; } return responseData; } catch (error) { throw error; } }; export { BASE_URL } export default request;