Skip to content

Commit

Permalink
api setup
Browse files Browse the repository at this point in the history
  • Loading branch information
saddamBD committed Oct 21, 2024
1 parent 9b75df2 commit c69f81c
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ lerna-debug.log*
node_modules
dist
dist-ssr
.env
*.local

# Editor directories and files
Expand Down
65 changes: 65 additions & 0 deletions src/redux/features/books/booksApi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import getBaseUrl from "../../../utils/baseURL";

const baseQuery = fetchBaseQuery({
baseUrl: `${getBaseUrl()}/api/books`,
credentials: "include",
prepareHeaders: (Headers) => {
const token = localStorage.getItem("token");
if (token) {
Headers.set("Authorization", `Bearer ${token}`);
}
return Headers;
},
});

const booksApi = createApi({
reducerPath: "booksApi",
baseQuery,
tagTypes: ["Books"],
endpoints: (builder) => ({
fetchAllBooks: builder.query({
query: () => "/",
providesTags: ["Books"],
}),
fetchBookById: builder.query({
query: (id) => `/${id}`,
providesTags: (result, error, id) => [{ type: "Books", id }],
}),
addBook: builder.mutation({
query: (newBook) => ({
url: `/create-book`,
method: "POST",
body: newBook,
}),
invalidatesTags: ["Books"],
}),
updateBook: builder.mutation({
query: ({ id, ...rest }) => ({
url: `/edit/${id}`,
method: "PUT",
body: rest,
headers: {
"Content-Type": "application/json",
},
}),
invalidatesTags: ["Books"],
}),
deleteBook: builder.mutation({
query: (id) => ({
url: `/${id}`,
method: "DELETE",
}),
invalidatesTags: ["Books"],
}),
}),
});

export const {
useFetchAllBooksQuery,
useFetchBookByIdQuery,
useAddBookMutation,
useUpdateBookMutation,
useDeleteBookMutation,
} = booksApi;
export default booksApi;
6 changes: 6 additions & 0 deletions src/redux/store.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { configureStore } from "@reduxjs/toolkit";
import cartReducer from "./features/cart/cartSlice";
import booksApi from "./features/books/booksApi";
import ordersApi from "./features/orders/ordersApi";

export const store = configureStore({
reducer: {
cart: cartReducer,
[booksApi.reducerPath]: booksApi.reducer,
[ordersApi.reducerPath]: ordersApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(booksApi.middleware, ordersApi.middleware),
});
5 changes: 5 additions & 0 deletions src/utils/baseURL.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const getBaseUrl = () => {
return "http://localhost:5000";
};

export default getBaseUrl;

0 comments on commit c69f81c

Please sign in to comment.