UNPKG

@campusiq/sdk

Version:

Official JavaScript/TypeScript SDK for CampusIQ - A comprehensive school management system API

79 lines 3.13 kB
import { CampusIQError } from '../error'; export class BaseResource { constructor(client) { this.client = client; } async requestGet(endpoint, params) { try { const url = new URL(`${this.client.baseURL}${endpoint}`); if (params) { Object.entries(params).forEach(([key, value]) => { if (value !== undefined && value !== null) { if (Array.isArray(value)) { value.forEach(v => url.searchParams.append(key, String(v))); } else { url.searchParams.append(key, String(value)); } } }); } const response = await fetch(url.toString(), { method: 'GET', headers: { 'Authorization': `Bearer ${this.client.apiKey}`, 'X-School-ID': this.client.schoolId, 'Content-Type': 'application/json', 'User-Agent': `CampusIQ-SDK/${this.client.version}`, }, }); if (!response.ok) { const errorText = await response.text(); throw new CampusIQError(`HTTP ${response.status}: ${response.statusText}`, response.status, errorText); } return await response.json(); } catch (error) { if (error instanceof CampusIQError) throw error; throw new CampusIQError(`Request failed: ${error.message}`, 0, error.message); } } async requestPost(endpoint, data) { return this.sendRequest('POST', endpoint, data); } async requestPut(endpoint, data) { return this.sendRequest('PUT', endpoint, data); } async requestPatch(endpoint, data) { return this.sendRequest('PATCH', endpoint, data); } async requestDelete(endpoint) { return this.sendRequest('DELETE', endpoint); } async sendRequest(method, endpoint, data) { try { const response = await fetch(`${this.client.baseURL}${endpoint}`, { method, headers: { 'Authorization': `Bearer ${this.client.apiKey}`, 'X-School-ID': this.client.schoolId, 'Content-Type': 'application/json', 'User-Agent': `CampusIQ-SDK/${this.client.version}`, }, body: data ? JSON.stringify(data) : undefined, }); if (!response.ok) { const errorText = await response.text(); throw new CampusIQError(`HTTP ${response.status}: ${response.statusText}`, response.status, errorText); } return await response.json(); } catch (error) { if (error instanceof CampusIQError) throw error; throw new CampusIQError(`Request failed: ${error.message}`, 0, error.message); } } } //# sourceMappingURL=base.js.map