Skip to content

Commit

Permalink
feat: add axios base api, thunks extras and api global const
Browse files Browse the repository at this point in the history
  • Loading branch information
TomatoVan committed Nov 28, 2023
1 parent ee6b2c0 commit 27893e1
Show file tree
Hide file tree
Showing 15 changed files with 68 additions and 20 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ module.exports = {
},
globals: {
__IS_DEV__: true,
__API__: true,
},
overrides: [
{
Expand Down
3 changes: 2 additions & 1 deletion config/build/buildPlugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import { BuildOptions } from './types/config';

export function buildPlugins({ paths, isDev }: BuildOptions): webpack.WebpackPluginInstance[] {
export function buildPlugins({ paths, isDev, apiUrl }: BuildOptions): webpack.WebpackPluginInstance[] {
const plugins = [
new HtmlWebpackPlugin({
template: paths.html,
Expand All @@ -16,6 +16,7 @@ export function buildPlugins({ paths, isDev }: BuildOptions): webpack.WebpackPlu
}),
new webpack.DefinePlugin({
__IS_DEV__: JSON.stringify(isDev),
__API__: JSON.stringify(apiUrl),
}),
];

Expand Down
2 changes: 2 additions & 0 deletions config/build/types/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ export interface BuildPaths {
export interface BuildEnv {
mode: BuildMode;
port: number;
apiUrl: string;
}

export interface BuildOptions {
mode: BuildMode;
paths: BuildPaths;
isDev: boolean;
port: number;
apiUrl: string;
}
1 change: 1 addition & 0 deletions config/jest/jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import path from 'path';
export default {
globals: {
__IS_DEV__: true,
__API__: '',
},
clearMocks: true,
testEnvironment: 'jsdom',
Expand Down
3 changes: 2 additions & 1 deletion config/storybook/webpack.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ export default ({ config }: {config: webpack.Configuration}) => {
config.module.rules.push(buildCssLoader(true));

config.plugins.push(new DefinePlugin({
__IS_DEV__: true,
__IS_DEV__: JSON.stringify(true),
__API__: JSON.stringify(''),
}));

return config;
Expand Down
15 changes: 14 additions & 1 deletion src/app/providers/StoreProvider/config/StateSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@ import {
} from '@reduxjs/toolkit';
import { CombinedState } from 'redux';
import { ProfileSchema } from 'entities/Profile';
import { AxiosInstance } from 'axios';
import { To } from '@remix-run/router';
import { NavigateOptions } from 'react-router/dist/lib/context';

export interface StateSchema {
counter: CounterSchema;
user: UserSchema;
// Асинхронные редюсеры
// async reducers
loginForm?: LoginSchema;
profile?: ProfileSchema
}
Expand All @@ -27,3 +30,13 @@ export interface ReducerManager {
export interface ReduxStoreWithManager extends EnhancedStore<StateSchema> {
reducerManager: ReducerManager;
}

export interface ThunkExtraArg {
api: AxiosInstance,
navigate: (to: To, options?: NavigateOptions) => void
}

export interface ThunkConfig<T> {
rejectValue: T,
extra: ThunkExtraArg
}
15 changes: 14 additions & 1 deletion src/app/providers/StoreProvider/config/store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { configureStore, ReducersMapObject } from '@reduxjs/toolkit';
import { $api } from 'shared/api/api';
import { To } from '@remix-run/router';
import { NavigateOptions } from 'react-router/dist/lib/context';
import { counterReducer } from '../../../../entities/Counter';
import { userReducer } from '../../../../entities/User';
import { StateSchema } from './StateSchema';
Expand All @@ -7,6 +10,7 @@ import { createReducerManager } from './reducerManager';
export function createReduxStore(
initialState?: StateSchema,
asyncReducers?: ReducersMapObject<StateSchema>,
navigate?: (to: To, options?: NavigateOptions) => void,
) {
const rootReducers: ReducersMapObject<StateSchema> = {
...asyncReducers,
Expand All @@ -16,10 +20,19 @@ export function createReduxStore(

const reducerManager = createReducerManager(rootReducers);

const store = configureStore<StateSchema>({
const store = configureStore({
reducer: reducerManager.reduce,
devTools: __IS_DEV__,
preloadedState: initialState,
middleware: (getDefaultMiddleware) => getDefaultMiddleware({
thunk: {
extraArgument: {
api: $api,
navigate,
},
},

}),
});

// @ts-ignore
Expand Down
4 changes: 2 additions & 2 deletions src/app/providers/StoreProvider/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import {
AppDispatch,
createReduxStore,
} from 'app/providers/StoreProvider/config/store';
import type { StateSchema } from 'app/providers/StoreProvider/config/StateSchema';
import type { StateSchema, ThunkExtraArg, ThunkConfig } from 'app/providers/StoreProvider/config/StateSchema';

export {
StoreProvider, createReduxStore, StateSchema, AppDispatch,
StoreProvider, createReduxStore, StateSchema, AppDispatch, ThunkExtraArg, ThunkConfig,
};
4 changes: 4 additions & 0 deletions src/app/providers/StoreProvider/ui/StoreProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Provider } from 'react-redux';
import { createReduxStore } from 'app/providers/StoreProvider/config/store';
import { StateSchema } from 'app/providers/StoreProvider/config/StateSchema';
import { DeepPartial, ReducersMapObject } from '@reduxjs/toolkit';
import { useNavigate } from 'react-router-dom';

interface StoreProviderProps {
children?: ReactNode | any;
Expand All @@ -17,9 +18,12 @@ export const StoreProvider = (props: StoreProviderProps) => {
asyncReducers,
} = props;

const navigate = useNavigate();

const store = createReduxStore(
initialState as StateSchema,
asyncReducers as ReducersMapObject<StateSchema>,
navigate,
);
return (
<Provider store={store}>
Expand Down
1 change: 1 addition & 0 deletions src/app/types/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ declare module '*.svg' {
}

declare const __IS_DEV__: boolean;
declare const __API__: string;
1 change: 0 additions & 1 deletion src/entities/User/model/slice/userSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export const userSlice = createSlice({
},
initAuthData: (state, action:PayloadAction<User>) => {
const user = localStorage.getItem(USER_LOCALSTORAGE_KEY);
console.log(JSON.parse(user));
if (user) {
state.authData = JSON.parse(user);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,33 +1,34 @@
import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
import { USER_LOCALSTORAGE_KEY } from 'shared/const/localstorage';
import { ThunkConfig } from 'app/providers/StoreProvider';
import { User, userActions } from '../../../../../entities/User';

interface LoginByUsernameProps {
username: string;
password: string
username: string;
password: string;
}

export const loginByUsername = createAsyncThunk<
User,
LoginByUsernameProps,
{ rejectValue: string }
ThunkConfig<string>
>('login/loginByUsername', async (authData, thunkAPI) => {
const { extra, dispatch, rejectWithValue } = thunkAPI;

try {
const response = await axios.post<User>(
'http://localhost:8000/login',
const response = await extra.api.post<User>(
'/login',
authData,
);
if (!response.data) {
throw new Error();
}
localStorage.setItem(USER_LOCALSTORAGE_KEY, JSON.stringify(response.data));

thunkAPI.dispatch(userActions.setAuthData(response.data));
dispatch(userActions.setAuthData(response.data));

return response.data;
} catch (error) {
console.log(error);
return thunkAPI.rejectWithValue('error');
return rejectWithValue('error');
}
});
8 changes: 4 additions & 4 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ import './shared/config/i18n/i18n';
import { ErrorBoundary } from './app/providers/ErrorBoundary';

render(
<StoreProvider>
<BrowserRouter>
<BrowserRouter>
<StoreProvider>
<ErrorBoundary>
<ThemeProvider>
<App />
</ThemeProvider>
</ErrorBoundary>
</BrowserRouter>
</StoreProvider>,
</StoreProvider>
</BrowserRouter>,
document.getElementById('root'),
);
9 changes: 9 additions & 0 deletions src/shared/api/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import axios from 'axios';
import { USER_LOCALSTORAGE_KEY } from 'shared/const/localstorage';

export const $api = axios.create({
baseURL: __API__,
headers: {
authorization: localStorage.getItem(USER_LOCALSTORAGE_KEY),
},
});
2 changes: 2 additions & 0 deletions webpack.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ export default (env: BuildEnv) => {
const PORT = env.port || 3000;

const isDev = mode === 'development';
const apiUrl = env.apiUrl || 'http://localhost:8000';

const config: webpack.Configuration = buildWebpackConfig({
mode,
paths,
isDev,
port: PORT,
apiUrl,
});

return config;
Expand Down

0 comments on commit 27893e1

Please sign in to comment.