umami/hooks/useApi.js

49 lines
1.1 KiB
JavaScript
Raw Normal View History

2022-02-23 08:52:31 +01:00
import { useCallback } from 'react';
import { useRouter } from 'next/router';
2022-02-27 00:53:45 +01:00
import { get, post, put, del, getItem } from 'lib/web';
import { AUTH_TOKEN } from 'lib/constants';
2022-02-27 09:25:24 +01:00
function includeAuthToken(headers = {}) {
2022-02-27 00:53:45 +01:00
const authToken = getItem(AUTH_TOKEN);
if (authToken) {
headers.Authorization = `Bearer ${authToken}`;
}
return headers;
}
2022-02-23 08:52:31 +01:00
export default function useApi() {
const { basePath } = useRouter();
return {
2022-02-27 00:53:45 +01:00
get: useCallback(
2022-02-27 09:25:24 +01:00
async (url, params, headers) => {
return get(`${basePath}/api${url}`, params, includeAuthToken(headers));
2022-02-27 00:53:45 +01:00
},
[get],
),
2022-02-23 08:52:31 +01:00
2022-02-27 00:53:45 +01:00
post: useCallback(
async (url, params, headers) => {
2022-02-27 09:25:24 +01:00
return post(`${basePath}/api${url}`, params, includeAuthToken(headers));
2022-02-27 00:53:45 +01:00
},
[post],
),
2022-02-23 08:52:31 +01:00
2022-02-27 00:53:45 +01:00
put: useCallback(
async (url, params, headers) => {
2022-02-27 09:25:24 +01:00
return put(`${basePath}/api${url}`, params, includeAuthToken(headers));
2022-02-27 00:53:45 +01:00
},
[put],
),
2022-02-23 08:52:31 +01:00
2022-02-27 00:53:45 +01:00
del: useCallback(
async (url, params, headers) => {
2022-02-27 09:25:24 +01:00
return del(`${basePath}/api${url}`, params, includeAuthToken(headers));
2022-02-27 00:53:45 +01:00
},
[del],
),
2022-02-23 08:52:31 +01:00
};
}