Skip to content

Instantly share code, notes, and snippets.

@brunormferreira
Created December 28, 2020 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunormferreira/05b582df012937fc61765578c0d758a9 to your computer and use it in GitHub Desktop.
Save brunormferreira/05b582df012937fc61765578c0d758a9 to your computer and use it in GitHub Desktop.
const localStorageKey = '__bookshelf_token__'
function client(endpoint, {body, ...customConfig} = {}) {
const token = window.localStorage.getItem(localStorageKey)
const headers = {'content-type': 'application/json'}
if (token) {
headers.Authorization = `Bearer ${token}`
}
const config = {
method: body ? 'POST' : 'GET',
...customConfig,
headers: {
...headers,
...customConfig.headers,
},
}
if (body) {
config.body = JSON.stringify(body)
}
return window
.fetch(`${process.env.REACT_APP_API_URL}/${endpoint}`, config)
.then(async response => {
if (response.status === 401) {
logout()
window.location.assign(window.location)
return
}
const data = await response.json()
if (response.ok) {
return data
} else {
return Promise.reject(data)
}
})
}
function logout() {
window.localStorage.removeItem(localStorageKey)
}
@brunormferreira
Copy link
Author

brunormferreira commented Dec 28, 2020

import {client} from './api-client'

function create(listItemData) {
  return client('list-items', {body: listItemData})
}

function read() {
  return client('list-items')
}

function update(listItemId, updates) {
  return client(`list-items/${listItemId}`, {
    method: 'PUT',
    body: updates,
  })
}

function remove(listItemId) {
  return client(`list-items/${listItemId}`, {method: 'DELETE'})
}

export {create, read, remove, update}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment