Skip to content

Commit

Permalink
Merge pull request #139 from Alt-Org/leo/refactor/91-refactor-rtk-que…
Browse files Browse the repository at this point in the history
…ry-api

Leo/refactor/91 refactor rtk query api
  • Loading branch information
leolabdev authored Oct 4, 2024
2 parents 861e56b + 0737a71 commit 43a3c4d
Show file tree
Hide file tree
Showing 15 changed files with 89 additions and 174 deletions.
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import {authApi, AuthUserSchema} from "@/entities/Auth";
import {clanApi} from "@/entities/Clan";
import {galleryApi} from "@/entities/Gallery";
import {profileApi} from "@/entities/Profile";

import {AuthUserSchema} from "@/entities/Auth";
import {gameApi} from "@/shared/api";

export interface StateSchema {
authUser: AuthUserSchema;
[authApi.reducerPath]: ReturnType<typeof authApi.reducer>;
[profileApi.reducerPath]: ReturnType<typeof profileApi.reducer>;
[clanApi.reducerPath]: ReturnType<typeof clanApi.reducer>;
[galleryApi.reducerPath]: ReturnType<typeof galleryApi.reducer>;
[gameApi.reducerPath]: ReturnType<typeof gameApi.reducer>;
// todo add here strapiApi
}

Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@ import { persistStore, persistReducer } from 'redux-persist'
import createWebStorage from 'redux-persist/lib/storage/createWebStorage';
import {envHelper} from "@/shared/const/envHelper";
import {StateSchema} from "./StateSchema";
import {authApi,authUserReducer, authMiddleware} from "@/entities/Auth";
import {clanApi} from "@/entities/Clan";
import {galleryApi} from "@/entities/Gallery";
import {authUserReducer, authMiddleware} from "@/entities/Auth";
import {FLUSH, PAUSE, PERSIST, PURGE, REGISTER, REHYDRATE} from "redux-persist";
import {setupListeners} from "@reduxjs/toolkit/query";
import {profileApi} from "@/entities/Profile";
import {gameApi} from "@/shared/api";


const createNoopStorage= () => {
Expand Down Expand Up @@ -36,16 +34,15 @@ export function createReduxStore(initialState?: StateSchema) {

const rootReducer = combineReducers({
authUser: authUserReducer,
[authApi.reducerPath]: authApi.reducer,
[profileApi.reducerPath]: profileApi.reducer,
[clanApi.reducerPath]: clanApi.reducer,
[galleryApi.reducerPath]: galleryApi.reducer,
[gameApi.reducerPath]: gameApi.reducer,
// todo add here strapiApi
});

const persistConfig = {
key: 'root',
storage,
blacklist: [authApi.reducerPath, clanApi.reducerPath, galleryApi.reducerPath]
// todo add here strapiApi
blacklist: [gameApi.reducerPath]
};


Expand All @@ -66,9 +63,7 @@ export function createReduxStore(initialState?: StateSchema) {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}).concat(
authApi.middleware,
clanApi.middleware,
galleryApi.middleware,
gameApi.middleware,
authMiddleware,
),

Expand Down
1 change: 0 additions & 1 deletion frontend-next-migration/src/entities/Auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ export type {


export {
authApi,
useLoginMutation,
useRegisterMutation,
useLogoutMutation,
Expand Down
35 changes: 6 additions & 29 deletions frontend-next-migration/src/entities/Auth/model/authApi.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,36 @@
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import {StateSchema} from "@/app/_providers/StoreProvider";
import {envHelper} from "@/shared/const/envHelper";
import {gameApi} from "@/shared/api";
import {
IUserRegisterDto,
IUserLoginDto, ILoginResponse,
} from "../types/authUser";



export const authApi = createApi({
reducerPath: 'authApi',
baseQuery: fetchBaseQuery(
{
baseUrl: envHelper.apiLink,
credentials: "include",
prepareHeaders :(headers,{getState, endpoint})=>{
const accessTokenInfo = (getState() as StateSchema).authUser.accessTokenInfo;
const excludedEndpoints = ['login', 'refresh', 'register'];
if(accessTokenInfo && !excludedEndpoints.includes(endpoint)) {
headers.set('Authorization', `Bearer ${accessTokenInfo?.accessToken}`);
}
},

}),
const authApi = gameApi.injectEndpoints({
endpoints: (builder) => ({

login: builder.mutation<ILoginResponse, IUserLoginDto>({
query: (loginDTO) => ({
url: 'auth/signIn',
url: '/auth/signIn',
method: 'POST',
body: loginDTO,
}),
}),

register: builder.mutation<Object, IUserRegisterDto>({
query: (registerDto) => ({
url: '/profile',
method: 'POST',
body: registerDto,
}),
}),

logout: builder.mutation<void, void>({
query: () => ({
url: 'auth/logout',
url: '/auth/logout',
method: 'POST',
}),

}),

}),
})
overrideExisting: false,
});

export const {
util,
useLoginMutation,
useRegisterMutation,
useLogoutMutation,
Expand Down
2 changes: 0 additions & 2 deletions frontend-next-migration/src/entities/Clan/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@ export {
useCreateClanMutation,
useDeleteClanMutation,
useUpdateClanMutation,
clanApi,
useGetClanByIdQuery,
useGetClanByIdWithPlayersQuery,
useGetClansQuery,
useLeaveClanMutation,
useJoinClanMutation,
clanEndpoints
} from "./model/clanApi";

export { useClanData } from "./model/useClanData";
Expand Down
70 changes: 18 additions & 52 deletions frontend-next-migration/src/entities/Clan/model/clanApi.ts
Original file line number Diff line number Diff line change
@@ -1,93 +1,60 @@
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { StateSchema } from "@/app/_providers/StoreProvider";
import { envHelper } from "@/shared/const/envHelper";
import { GetClanResponse, GetClansResponse, IClan, IClanCreateDto, IClanUpdateDto, ICreateClanResponse, IJoin } from "../../Clan";
import {gameApi, GameApiCacheTags} from "@/shared/api";
import { GetClanResponse, GetClansResponse, IClanCreateDto, IClanUpdateDto, ICreateClanResponse, IJoin } from "../../Clan";

interface GetClansQueryParams {
page?: number,
search?: string,
}
const clanUrl = "clan";

export const clanApi = createApi({
reducerPath: 'clanApi',
tagTypes: ['Clan'],
baseQuery: fetchBaseQuery(
{
baseUrl: envHelper.apiLink,
credentials: "include",
prepareHeaders: (headers, { getState, endpoint }) => {
const accessTokenInfo = (getState() as StateSchema).authUser.accessTokenInfo;
const excludedEndpoints = ['login', 'refresh', 'register'];
if (accessTokenInfo && !excludedEndpoints.includes(endpoint)) {
headers.set('Authorization', `Bearer ${accessTokenInfo?.accessToken}`);
}
},

}),
const clanApi = gameApi.injectEndpoints({
endpoints: (builder) => ({

getClans: builder.query<GetClansResponse, GetClansQueryParams>({

query: (params) => {
// const paramsToBeSent= {
// page: options.page,
// limit: options.limit,
// sortBy: options?.sort?.sortBy,
// sortOrder: options?.sort?.sortOrder
// }
return {
url: clanUrl,
method: 'GET',
params: params,
}
},
providesTags: ['Clan'],
query: (params) => ({
url: clanUrl,
method: 'GET',
params,
}),
providesTags: [GameApiCacheTags.CLAN],
}),

getClanById: builder.query<GetClanResponse, string>({
query: (clanId) => `${clanUrl}/${clanId}`,
providesTags: ['Clan']
providesTags: [GameApiCacheTags.CLAN],
}),

getClanByIdWithPlayers: builder.query<GetClanResponse, string>({
query: (clanId) => `${clanUrl}/${clanId}?with=Player`,
providesTags: ['Clan']
providesTags: [GameApiCacheTags.CLAN],
}),

createClan: builder.mutation<ICreateClanResponse, IClanCreateDto>({
query: (clan) => ({
url: clanUrl,
method: 'POST',
body: clan,
}),
invalidatesTags: ['Clan'],
invalidatesTags: [GameApiCacheTags.CLAN],
}),

deleteClan: builder.mutation<void, string>({
query: (clanId) => ({
url: `${clanUrl}/${clanId}`,
method: 'DELETE',
}),
invalidatesTags: ['Clan'],
invalidatesTags: [GameApiCacheTags.CLAN],
}),

updateClan: builder.mutation<void, IClanUpdateDto>({
query: (clan) => ({
url: clanUrl,
method: 'PUT',
body: clan,
}),
invalidatesTags: ['Clan'],
invalidatesTags: [GameApiCacheTags.CLAN],
}),

joinClan: builder.mutation<void, IJoin>({
query: (join) => ({
url: `${clanUrl}/join`,
method: 'POST',
body: join,
}),
invalidatesTags: ['Clan'],
invalidatesTags: [GameApiCacheTags.CLAN],
}),
leaveClan: builder.mutation<void, void>({
query: () => ({
Expand All @@ -96,10 +63,10 @@ export const clanApi = createApi({
}),
}),
}),
})
overrideExisting: false,
});

export const {
util,
useGetClansQuery,
useGetClanByIdQuery,
useGetClanByIdWithPlayersQuery,
Expand All @@ -108,5 +75,4 @@ export const {
useUpdateClanMutation,
useJoinClanMutation,
useLeaveClanMutation,
endpoints: clanEndpoints
} = clanApi;
} = clanApi;
14 changes: 2 additions & 12 deletions frontend-next-migration/src/entities/Gallery/index.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,12 @@
export type {IGalleryDirectory,IGalleryPicture} from "./types/gallery";
export type {DirectoryWithPhotos, ParentDirectory,} from "./model/galleryApi";
export {
galleryApi,
useGetAllDirectoryPhotosQuery
} from "./model/galleryApi";
export type {ParentDirectory} from "./model/galleryApi";

export {
useGalleryCategories
} from "./model/useGalleryCategories";


export {
transformToGalleryPropsFormat
} from "./model/transformToGalleryPropsFormat";


export type {
GalleryCategoriesWithModalSliderProps,
} from "./ui/GalleryCategoriesWithModalSlider";

export {GalleryCategoriesWithModalSlider,} from "./ui/GalleryCategoriesWithModalSlider";
export {GalleryCategoriesWithModalSlider} from "./ui/GalleryCategoriesWithModalSlider";
30 changes: 5 additions & 25 deletions frontend-next-migration/src/entities/Gallery/model/galleryApi.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import {envHelper} from "@/shared/const/envHelper";
import {HYDRATE} from "next-redux-wrapper";

import {gameApi} from "@/shared/api";

const url = "public/site";

Expand Down Expand Up @@ -36,20 +34,8 @@ type GetAllDirectoryPhotosQueryArgs = {
parentDirectory: ParentDirectory
};



export const galleryApi = createApi({
reducerPath: "galleryApi",
tagTypes: ['Gallery'],
baseQuery: fetchBaseQuery({
baseUrl: envHelper.apiLink,
}),
extractRehydrationInfo(action, { reducerPath }) {
if (action.type === HYDRATE) {
return action.payload[reducerPath]
}
},
endpoints: (builder) => ({
const galleryApi = gameApi.injectEndpoints({
endpoints: (builder) => ({
getAllDirectoryPhotos: builder.query<DirectoryWithPhotos[], GetAllDirectoryPhotosQueryArgs>({
queryFn: async (args, _queryApi, _extraOptions, fetchWithBQ) => {
const parentDirectory = args.parentDirectory;
Expand Down Expand Up @@ -82,16 +68,10 @@ export const galleryApi = createApi({
});

const allDirectoriesWithPhotos = await Promise.all(photosPromises);



return { data: allDirectoriesWithPhotos };
}
})


}),
overrideExisting: false
});


export const { useGetAllDirectoryPhotosQuery} = galleryApi;
export const { useGetAllDirectoryPhotosQuery } = galleryApi;
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {DirectoryWithPhotos} from "@/entities/Gallery";
import {GalleryCategoriesWithModalSliderProps} from "../ui/GalleryCategoriesWithModalSlider";
import { DirectoryWithPhotos } from "./galleryApi";

export const transformToGalleryPropsFormat = (data: DirectoryWithPhotos[]): GalleryCategoriesWithModalSliderProps[] => {
return data?.map(category => ({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
'use client'
import {
transformToGalleryPropsFormat,
useGetAllDirectoryPhotosQuery,
} from "@/entities/Gallery";
import {ParentDirectory, GalleryCategoriesWithModalSliderProps} from "@/entities/Gallery";
import { GalleryCategoriesWithModalSliderProps } from "../ui/GalleryCategoriesWithModalSlider";
import {ParentDirectory, useGetAllDirectoryPhotosQuery } from "./galleryApi";
import { transformToGalleryPropsFormat } from "./transformToGalleryPropsFormat";

export const useGalleryCategories = (parentDirectory: ParentDirectory) => {
const { data, isError, isLoading} = useGetAllDirectoryPhotosQuery({ parentDirectory });
Expand Down
1 change: 0 additions & 1 deletion frontend-next-migration/src/entities/Profile/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
export {
profileEndpoints,
profileApi,
useDeleteProfileMutation,
} from "./model/profileApi"
export type {IProfile} from "./types/profile";
Loading

0 comments on commit 43a3c4d

Please sign in to comment.