Created
September 29, 2020 15:38
-
-
Save mlnchk/31c9fb6cc518240f65bc0db74fa3ca9d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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