const domain = 'localhost' const port = 3001 const httpProtocol = `http` const prefix = 'api' const remote = `${httpProtocol}://${domain}:${port}/${prefix}` const headerTemplate = { method: null, mode: 'cors', // no-cors, *cors, same-origin cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'omit', // include, *same-origin, omit headers: { 'Content-Type': 'application/json', // 'Content-Type': 'application/x-www-form-urlencoded', }, redirect: 'manual', // manual, *follow, error referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url body: null, // body data type must match "Content-Type" header } class Connector { constructor() { this.apiPrefix = prefix this._verbs = { get: 'GET', post: 'POST', patch: 'PATCH', } } _makeHeader({ method, payload, authorization }) { const header = { ...headerTemplate } header.method = method if (payload) { header.body = JSON.stringify(payload) } if (authorization) { header.headers.authorization = authorization } return header } async _tryFetch({ endpoint, header }, returnHeaders = false) { try { const res = await fetch(`${remote}${endpoint}`, header) if (!res.ok) { throw Error(res.statusText) } if (returnHeaders) { return res.headers } else { const jsonRes = await res.json() return jsonRes.data } } catch (error) { console.error(`[API Util]: ${error}\nroute:`, endpoint) } } async get(endpoint, authHeaders = false) { if (authHeaders) { return await this._tryFetch({ endpoint, header: this._makeHeader({ method: this._verbs.get, authorization: `${authHeaders}`, }), }) } else { return await this._tryFetch({ endpoint, header: this._makeHeader({ method: this._verbs.get }), }) } } async post(endpoint, payload = {}, returnHeaders = false) { return await this._tryFetch({ endpoint, header: this._makeHeader({ method: this._verbs.post, payload }), returnHeaders, }) } async patch(endpoint, payload = {}) { return await this._tryFetch({ endpoint, header: this._makeHeader({ method: this._verbs.patch, payload }), }) } /** !: DEV ONLY */ // async removeAll() { } } const db = new Connector() export { Connector, db, remote }