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';
|
2022-05-06 04:04:28 +02:00
|
|
|
import { AUTH_TOKEN, SHARE_TOKEN_HEADER } from 'lib/constants';
|
|
|
|
import useStore from 'store/app';
|
2022-02-27 00:53:45 +01:00
|
|
|
|
2022-05-06 04:04:28 +02:00
|
|
|
const selector = state => state.shareToken;
|
2022-02-27 00:53:45 +01:00
|
|
|
|
2022-08-02 08:04:47 +02:00
|
|
|
function parseHeaders(headers, { authToken, shareToken }) {
|
2022-02-27 00:53:45 +01:00
|
|
|
if (authToken) {
|
2022-05-06 04:04:28 +02:00
|
|
|
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();
|
2022-05-06 04:04:28 +02:00
|
|
|
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(
|
2022-08-02 08:04:47 +02:00
|
|
|
async (url, params = {}, headers = {}) => {
|
2022-05-06 04:04:28 +02:00
|
|
|
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(
|
2022-08-02 08:04:47 +02:00
|
|
|
async (url, params = {}, headers = {}) => {
|
2022-05-06 04:04:28 +02:00
|
|
|
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(
|
2022-08-02 08:04:47 +02:00
|
|
|
async (url, params = {}, headers = {}) => {
|
2022-05-06 04:04:28 +02:00
|
|
|
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(
|
2022-08-02 08:04:47 +02:00
|
|
|
async (url, params = {}, headers = {}) => {
|
2022-05-06 04:04:28 +02:00
|
|
|
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
|
|
|
};
|
|
|
|
}
|