From fd50c13e27a65a7b852da22d5fd07c752af0e3ec Mon Sep 17 00:00:00 2001 From: Natalia Bandurova Date: Fri, 4 Oct 2024 12:32:50 +0300 Subject: [PATCH] feat: add authorization header to query --- frontend/src/api/{getChannels.js => channelsApi.js} | 3 ++- frontend/src/components/Channels.jsx | 2 +- frontend/src/helpers/prepareHeaders.js | 11 +++++++++++ frontend/src/store/store.js | 2 +- 4 files changed, 15 insertions(+), 3 deletions(-) rename frontend/src/api/{getChannels.js => channelsApi.js} (71%) create mode 100644 frontend/src/helpers/prepareHeaders.js diff --git a/frontend/src/api/getChannels.js b/frontend/src/api/channelsApi.js similarity index 71% rename from frontend/src/api/getChannels.js rename to frontend/src/api/channelsApi.js index cab1747..9e71f63 100644 --- a/frontend/src/api/getChannels.js +++ b/frontend/src/api/channelsApi.js @@ -1,9 +1,10 @@ import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; +import prepareHeaders from '../helpers/prepareHeaders'; import apiPath from './apiPath'; export const channelsApi = createApi({ reducerPath: 'channels', - baseQuery: fetchBaseQuery({ baseUrl: apiPath.channels() }), + baseQuery: fetchBaseQuery({ baseUrl: apiPath.channels(), prepareHeaders }), endpoints: (builder) => ({ getChannels: builder.query({ query: () => '', diff --git a/frontend/src/components/Channels.jsx b/frontend/src/components/Channels.jsx index 1043189..34c027a 100644 --- a/frontend/src/components/Channels.jsx +++ b/frontend/src/components/Channels.jsx @@ -2,7 +2,7 @@ import Nav from 'react-bootstrap/Nav'; import Col from 'react-bootstrap/Col'; import Button from 'react-bootstrap/Button'; import { Plus } from 'react-bootstrap-icons'; -import { useGetChannelsQuery } from '../api/getChannels'; +import { useGetChannelsQuery } from '../api/channelsApi'; const Channels = () => { const channels = useGetChannelsQuery; diff --git a/frontend/src/helpers/prepareHeaders.js b/frontend/src/helpers/prepareHeaders.js new file mode 100644 index 0000000..60408ed --- /dev/null +++ b/frontend/src/helpers/prepareHeaders.js @@ -0,0 +1,11 @@ +const prepareHeaders = (headers, { getState }) => { + const state = getState(); + const { token } = state.auth; + + if (token) { + headers.set('Authorization', `Bearer ${token}`); + } + return headers; +}; + +export default prepareHeaders; diff --git a/frontend/src/store/store.js b/frontend/src/store/store.js index b7d7893..ce476d8 100644 --- a/frontend/src/store/store.js +++ b/frontend/src/store/store.js @@ -1,5 +1,5 @@ import { configureStore } from '@reduxjs/toolkit'; -import { channelsApi } from '../api/getChannels'; +import { channelsApi } from '../api/channelsApi'; import authReducer from './slices/authSlice';