| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- 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
- }
- async get(endpoint) {
- const header = { headerTemplate }
- header.method = 'GET'
- try {
- console.log(`${remote}${endpoint}`)
- let res = await fetch(`${remote}${endpoint}`, header)
- if (!res.ok) {
- throw Error(res.statusText)
- }
- const jsonRes = await res.json()
- return jsonRes.data
- } catch (error) {
- console.error(error)
- }
- }
- async post(endpoint, payload = {}) {
- const header = { ...headerTemplate }
- header.method = 'POST'
- header.body = JSON.stringify(payload)
- try {
- let res = await fetch(`${remote}${endpoint}`, header)
- if (!res.ok) {
- throw Error(res.statusText)
- }
- const jsonRes = await res.json()
- return jsonRes.data
- } catch (error) {
- console.error(error)
- }
- }
- async patch(endpoint, payload = {}) {
- const header = { ...headerTemplate }
- header.method = 'PATCH'
- header.body = JSON.stringify(payload)
- try {
- let res = await fetch(`${remote}${endpoint}`, header)
- if (!res.ok) {
- throw Error(res.statusText)
- }
- const jsonRes = await res.json()
- return jsonRes.data
- } catch (error) {
- console.error(error)
- }
- }
-
- /** !: DEV ONLY */
- // async removeAll() { }
- }
- const db = new Connector()
- export { Connector, db }
|