Skip to content

Instantly share code, notes, and snippets.

@mlnchk
Created September 29, 2020 15:38
Show Gist options
  • Save mlnchk/31c9fb6cc518240f65bc0db74fa3ca9d to your computer and use it in GitHub Desktop.
Save mlnchk/31c9fb6cc518240f65bc0db74fa3ca9d to your computer and use it in GitHub Desktop.
import { NextPageContext } from "next";
import { parseCookies } from "nookies";
import redirect from "./redirect";
const apiUrl = process.env.API_URL;
export const api = (ctx?: NextPageContext) => (
path: string,
body?: any,
method?: string
) => {
const { authorization } = parseCookies(ctx);
const headers = {
"content-type": "application/json",
...(authorization ? { Authorization: authorization } : {}),
};
const config = {
method: method || (body ? "POST" : "GET"),
headers: {
...headers,
},
body: JSON.stringify(body),
};
return fetch(`${apiUrl}${path}`, config).then(async (response) => {
if (response.status === 401) {
redirect("/login", ctx);
return;
}
const data = await response.json();
if (response.ok) return data;
else return Promise.reject(data);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment