Skip to content

Instantly share code, notes, and snippets.

@unlabeled
Created November 3, 2017 12:32
Show Gist options
  • Save unlabeled/cd3e2f366aacea65197d1ec3410719c3 to your computer and use it in GitHub Desktop.
Save unlabeled/cd3e2f366aacea65197d1ec3410719c3 to your computer and use it in GitHub Desktop.
import request from "axios"
import { getQuery } from "../entities/utils"
import { getCookie } from "utils/cookie"
import { sendError } from "utils/errors"
const parseQuery = new RegExp("^([a-z]*)-(.*)-({.*})-({.*})$")
function addDataFromJson(obj, json, key) {
const params = JSON.parse(json)
if (Object.keys(params).length) {
obj[key] = params
}
}
function requestKeyToData(key) {
try {
const match = key.match(parseQuery)
const result = {
requestMethod: match[1],
requestUrl: match[2],
}
addDataFromJson(result, match[3], "requestParams")
addDataFromJson(result, match[4], "requestData")
return result
} catch (e) {
return { requestKey: key }
}
}
class Api {
constructor() {
this.request = request.create({
timeout: 30000,
withCredentials: true,
})
this.pending = new Map()
}
createItem(url, data, params = {}) {
return this.makeRequest("post", url, data, params)
}
getItem(url, id, params = {}) {
return this.makeRequest(
"get",
`${url}${id ? "/" + id : ""}${params ? getQuery(params) : ""}`
)
}
deleteItem(url, id) {
return this.makeRequest("delete", `${url}${id ? "/" + id : ""}`)
}
getList(url, params) {
return this.makeRequest("get", url, params)
}
metrics(url, data) {
console.info(url, data)
}
makeRequest(method, url = "", data = {}, params = {}) {
const currentQuery = [
method,
url,
JSON.stringify(data),
JSON.stringify(params),
].join("-")
if (this.pending.has(currentQuery)) {
return this.pending.get(currentQuery)
}
params.headers = { "X-XSRFToken": getCookie("_xsrf") }
const promise = this.request
[method](`/-/${url}`, data, params)
.then(response => {
this.pending.delete(currentQuery)
return response.data
})
.catch(error => {
this.pending.delete(currentQuery)
// Send error on timeout
if (error.code === "ECONNABORTED") {
sendError(error, requestKeyToData(currentQuery))
}
// TODO: Handle statuses 400, 403
})
this.pending.set(currentQuery, promise)
return promise
}
post(url, data, params) {
return this.makeRequest("post", url, data, params)
}
updateItem(url, data, id) {
return this.makeRequest(
"patch",
`${url}${id ? "/" + id : ""}`,
data,
void 0
)
}
}
const api = new Api()
export default api
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment