umami/hooks/useApi.js

72 lines
1.6 KiB
JavaScript
Raw Normal View History

2022-02-23 08:52:31 +01:00
import { useCallback } from 'react';
import { useRouter } from 'next/router';
2022-08-29 05:20:54 +02:00
import { get, post, put, del, getItem } from 'next-basics';
import { AUTH_TOKEN, SHARE_TOKEN_HEADER } from 'lib/constants';
import useStore from 'store/app';
2022-02-27 00:53:45 +01:00
const selector = state => state.shareToken;
2022-02-27 00:53:45 +01:00
function parseHeaders(headers, { authToken, shareToken }) {
2022-02-27 00:53:45 +01:00
if (authToken) {
headers.authorization = `Bearer ${authToken}`;
}
if (shareToken) {
headers[SHARE_TOKEN_HEADER] = shareToken.token;
2022-02-27 00:53:45 +01:00
}
return headers;
}
2022-02-23 08:52:31 +01:00
export default function useApi() {
const { basePath } = useRouter();
const authToken = getItem(AUTH_TOKEN);
const shareToken = useStore(selector);
2022-02-23 08:52:31 +01:00
return {
2022-02-27 00:53:45 +01:00
get: useCallback(
async (url, params = {}, headers = {}) => {
return get(
`${basePath}/api${url}`,
params,
parseHeaders(headers, { authToken, shareToken }),
);
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 = {}) => {
return post(
`${basePath}/api${url}`,
params,
parseHeaders(headers, { authToken, shareToken }),
);
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 = {}) => {
return put(
`${basePath}/api${url}`,
params,
parseHeaders(headers, { authToken, shareToken }),
);
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 = {}) => {
return del(
`${basePath}/api${url}`,
params,
parseHeaders(headers, { authToken, shareToken }),
);
2022-02-27 00:53:45 +01:00
},
[del],
),
2022-02-23 08:52:31 +01:00
};
}