import { UnauthorizedError } from '../errors/unauthorized.error.js'; import { APIError } from '../errors/api.error.js'; export const UnauthorizedStatusCode = 401; export class APIClient { constructor(baseURL = 'http://localhost:8001/api/v1') { this.baseURL = baseURL; this.login = this.login.bind(this); this.logout = this.logout.bind(this); this.retrieveSessionUser = this.retrieveSessionUser.bind(this); this.listUsers = this.listUsers.bind(this); this.listRequests = this.listRequests.bind(this); this.createUser = this.createUser.bind(this); } login(username, password) { return this._callAPI('/login', { username, password }, 'POST') .then(result => result.data); } logout() { return this._callAPI('/logout') } retrieveSessionUser() { return this._callAPI('/me') .then(result => result.data); } listUsers() { return this._callAPI('/users') } listRequests() { } createRequest(request) { } createUser(username, password) { return this._callAPI('/users', { username, password }, 'POST') .then(this._withAPIErrorMiddleware('create_user')) .then(result => result.data); } updateRequestStatus(reqID, newStatus) { } _callAPI(path, body, method='GET') { return fetch(this.baseURL + path, { method, headers: { 'Content-Type': 'application/json', }, mode: 'cors', credentials: 'include', body: JSON.stringify(body), }) .then(this._withUnauthorizedErrorMiddleware()) .then(res => res.json()) } _withUnauthorizedErrorMiddleware() { return res => { if (res.status === UnauthorizedStatusCode) { throw new UnauthorizedError(); } return res; } } _withAPIErrorMiddleware(endpoint) { return result => { if (result.error) { const { code, message, data } = result.error; throw new APIError(endpoint, code, message, data); } return result; } } }