Skip to content

Instantly share code, notes, and snippets.

@vre2h
Created August 8, 2019 13:36
Show Gist options
  • Save vre2h/e7eea04262e006a9099a2ba4d695152b to your computer and use it in GitHub Desktop.
Save vre2h/e7eea04262e006a9099a2ba4d695152b to your computer and use it in GitHub Desktop.
Api request wrapper for ts and js.
/* tslint:disable:no-console */
import store from "../store";
const { REACT_APP_API_ROOT } = process.env;
export function request(url: string, method: string, body?: any) {
const token = store.getState().login.payload.token;
const fetchData: RequestInit = {
body: JSON.stringify(body) || "",
cache: "no-cache",
credentials: "same-origin",
headers: {
Authorization: token ? `JWT ${token}` : "",
"Content-Type": "application/json; charset=utf-8"
},
method,
mode: "cors",
redirect: "follow",
referrer: "no-referrer"
};
if (!(process.env.NODE_ENV === "production")) {
console.group("Request");
console.info(
`url - "${REACT_APP_API_ROOT}/api/v1/${url}"\nrequest - `,
body
);
console.groupEnd();
}
return new Promise((resolve, reject) =>
fetch(`${REACT_APP_API_ROOT}/api/v1/${url}`, fetchData)
.then(async res => {
const parsedBody: any = await res.json();
if (!(process.env.NODE_ENV === "production")) {
console.group("Response");
console.info(
`url - "/${REACT_APP_API_ROOT}/api/v1/${url}"\nresponse - `,
parsedBody
);
console.groupEnd();
}
if (res.ok) {
return resolve(parsedBody);
}
console.log(parsedBody);
return reject({
message: parsedBody.msg
});
})
.catch((e: Error) =>
reject({
message: e.message
})
)
);
}
export function doGet(url: string) {
return request(url, "GET");
}
export function doPost(url: string, body: any) {
return request(url, "POST", body);
}
export function doPut(url: string, body: any) {
return request(url, "PUT", body);
}
export function doPatch(url: string, body: any) {
return request(url, "PATCH", body);
}
export function doDelete(url: string, body: any) {
return request(url, "DELETE", body);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment