Commit 2078e52e authored by Ли Джен Сеп's avatar Ли Джен Сеп 💬

#6 рефакторю код. соеденил фронт и бек

parent 6ab37d66
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 80
}
\ No newline at end of file
"semi": true,
"singleQuote": true,
"tabWidth": 3,
"trailingComma": "es5",
"printWidth": 140
}
import { Typography } from '@mui/material';
export function Header() {
return (
<Typography
variant="h3"
sx={{
fontSize: {
xs: '24px',
sm: '36px',
},
}}
>
Cypher Coder/Decoder
</Typography>
);
}
import { Grid2, TextField, Typography } from "@mui/material";
import { ChangeEvent } from "react";
import { Grid2, TextField, Typography } from '@mui/material';
import { ChangeEvent } from 'react';
interface Props {
name: "Decoded" | "Encoded" | "Password";
value: string;
onChange: (e: ChangeEvent<HTMLInputElement>) => void;
name: 'Decoded' | 'Encoded' | 'Password';
value: string;
onChange: (e: ChangeEvent<HTMLInputElement>) => void;
}
export default function InputField({ name, value, onChange }: Props) {
let labelText: string = "";
switch (name) {
case "Decoded":
labelText = `Decoded message`;
break;
case "Encoded":
labelText = `Encoded message`;
break;
case "Password":
labelText = "";
break;
default:
break;
}
let labelText: string = '';
switch (name) {
case 'Decoded':
labelText = `Decoded message`;
break;
case 'Encoded':
labelText = `Encoded message`;
break;
case 'Password':
labelText = '';
break;
default:
break;
}
return (
<Grid2 container alignItems="center" paddingY={2} spacing={2}>
<Grid2 flexGrow={1}>
<Typography
component="label"
htmlFor={`${name}-input`}
sx={{
fontSize: {
xs: "16px",
sm: "20px",
},
}}
>
{labelText}
</Typography>
</Grid2>
return (
<Grid2 container alignItems="center" paddingY={2} spacing={2}>
<Grid2 flexGrow={1}>
<Typography
component="label"
htmlFor={`${name}-input`}
sx={{
fontSize: {
xs: '16px',
sm: '20px',
},
}}
>
{labelText}
</Typography>
</Grid2>
<Grid2 size={name === "Password" ? 6 : 8} sx={{ "@media (max-width: 900px)": { width: "100%" } }}>
<TextField
fullWidth
multiline={name !== "Password"}
rows={name === "Password" ? 1 : 6}
variant="outlined"
id={`${name}-input`}
name={name}
label={name}
value={value}
onChange={onChange}
/>
</Grid2>
</Grid2>
);
<Grid2 size={name === 'Password' ? 6 : 8} sx={{ '@media (max-width: 900px)': { width: '100%' } }}>
<TextField
fullWidth
multiline={name !== 'Password'}
rows={name === 'Password' ? 1 : 6}
variant="outlined"
id={`${name}-input`}
name={name}
label={name}
value={value}
type="password"
onChange={onChange}
/>
</Grid2>
</Grid2>
);
}
"use client";
import { store } from "@/store/store";
import { Provider } from "react-redux";
'use client';
import { store } from '@/store/store';
import { Provider } from 'react-redux';
export default function RootLayout({
children,
children,
}: Readonly<{
children: React.ReactNode;
children: React.ReactNode;
}>) {
return (
<Provider store={store}>
<html lang="en">
<body>{children}</body>
</html>
</Provider>
);
return (
<Provider store={store}>
<html lang="en">
<body>{children}</body>
</html>
</Provider>
);
}
'use client';
import { ChangeEvent, useEffect, useState } from 'react';
import { Box, Button, Container, Grid2, Typography } from '@mui/material';
import ArrowDownwardIcon from '@mui/icons-material/ArrowDownward';
import { ChangeEvent, useEffect, useState } from 'react';
import InputField from './components/InputField';
import '@/animations/Loader.css';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { Header } from './components/Header/Header';
import { encodeMessage, decodeMessage } from '@/features/requestSlice';
interface IFormData {
decoded: string;
encoded: string;
password: string;
decoded: string;
encoded: string;
password: string;
}
export default function Home() {
const dispatch = useAppDispatch();
const { loading, result, error } = useAppSelector((state) => state.request);
const dispatch = useAppDispatch();
const { loading, result, error } = useAppSelector((state) => state.request);
const [formData, setFormData] = useState<IFormData>({
encoded: '',
decoded: '',
password: '',
});
const [formData, setFormData] = useState<IFormData>({
encoded: '',
decoded: '',
password: '',
});
const onCypherHandler = (): void => {
if (!formData.password.trim()) {
alert('Please, type in password!');
return;
}
dispatch(
encodeMessage({
password: formData.password,
message: formData.decoded,
})
);
};
const onCypherHandler = (): void => {
if (!formData.password.trim()) {
alert('Please, type in password!');
return;
}
if (!formData.encoded.trim()) {
alert('Please fill in the "Decoded" field!');
return;
}
dispatch(
encodeMessage({ password: formData.password, message: formData.decoded })
);
};
const onDecypherHandler = (): void => {
if (!formData.password.trim()) {
alert('Please, type in password!');
return;
}
const onDecypherHandler = (): void => {
if (!formData.password.trim()) {
alert('Please, type in password!');
return;
}
if (!formData.decoded.trim()) {
alert('Please fill in the "Decoded" field!');
return;
}
dispatch(
decodeMessage({ password: formData.password, message: formData.decoded })
);
};
dispatch(
decodeMessage({
password: formData.password,
message: formData.encoded,
})
);
};
useEffect(() => {
if (result) {
if (formData.decoded) {
setFormData((prev) => ({ ...prev, encoded: result }));
} else {
setFormData((prev) => ({ ...prev, decoded: result }));
useEffect(() => {
if (result) {
if (formData.decoded) {
setFormData((prev) => ({ ...prev, encoded: result }));
} else {
setFormData((prev) => ({ ...prev, decoded: result }));
}
}
}
}, [result]);
}, [result]);
const onInputChangeHandler = (e: ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setFormData((prevData) => ({
...prevData,
[name.toLowerCase()]: value,
}));
};
const onInputChangeHandler = (e: ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setFormData((prevData) => ({
...prevData,
[name.toLowerCase()]: value,
}));
};
return (
return (
<div className="App">
<Container sx={{ marginTop: 2 }} maxWidth="lg">
<Typography
variant="h3"
sx={{
fontSize: {
xs: '24px',
sm: '36px',
},
}}
>
Cypher Coder/Decoder
</Typography>
<Box
sx={{
maxWidth: {
xs: '90%',
sm: '80%',
lg: '70%',
},
}}
component="form"
autoComplete="off"
padding={2}
>
<Grid2 container direction="column" spacing={2}>
<InputField
name="Decoded"
value={formData.decoded}
onChange={onInputChangeHandler}
/>
<Grid2
container
alignItems="center"
sx={{
flexDirection: {
xs: 'column',
md: 'row',
<Container sx={{ marginTop: 2 }} maxWidth="lg">
<Header />
<Box
sx={{
maxWidth: {
xs: '90%',
sm: '80%',
lg: '70%',
},
}}
>
<Grid2 size={7}>
<InputField
name="Password"
value={formData.password}
onChange={onInputChangeHandler}
/>
</Grid2>
<Grid2 container>
<Grid2>
<Button
size="small"
variant="contained"
startIcon={<ArrowDownwardIcon />}
onClick={onDecypherHandler}
>
<Typography
sx={{
display: { xs: 'none', md: 'inline' },
}}
>
Encode
</Typography>
</Button>
</Grid2>
}}
component="form"
autoComplete="off"
padding={2}
>
<Grid2 container direction="column" spacing={2}>
<InputField name="Decoded" value={formData.decoded} onChange={onInputChangeHandler} />
<Grid2
container
alignItems="center"
sx={{
flexDirection: {
xs: 'column',
md: 'row',
},
}}
>
<Grid2 size={7}>
<InputField name="Password" value={formData.password} onChange={onInputChangeHandler} />
</Grid2>
<Grid2 container>
<Grid2>
<Button size="small" variant="contained" startIcon={<ArrowDownwardIcon />} onClick={onDecypherHandler}>
<Typography
sx={{
display: {
xs: 'none',
md: 'inline',
},
}}
>
Decode
</Typography>
</Button>
</Grid2>
<Grid2>
<Button
size="small"
variant="contained"
startIcon={
<ArrowDownwardIcon
sx={{ transform: 'rotate(180deg)' }}
/>
}
onClick={onCypherHandler}
>
<Typography
sx={{
display: { xs: 'none', md: 'inline' },
}}
>
Decode
</Typography>
</Button>
<Grid2>
<Button
size="small"
variant="contained"
startIcon={
<ArrowDownwardIcon
sx={{
transform: 'rotate(180deg)',
}}
/>
}
onClick={() => onCypherHandler()}
>
<Typography
sx={{
display: {
xs: 'none',
md: 'inline',
},
}}
>
Encode
</Typography>
</Button>
</Grid2>
</Grid2>
</Grid2>
</Grid2>
</Grid2>
<InputField
name="Encoded"
value={formData.encoded}
onChange={onInputChangeHandler}
/>
</Grid2>
</Box>
<InputField name="Encoded" value={formData.encoded} onChange={onInputChangeHandler} />
</Grid2>
</Box>
{loading && (
<div className="loader">
<div className="lds-ripple">
<div></div>
<div></div>
</div>
</div>
)}
{error && <Typography color="error">{error}</Typography>}
</Container>
{loading && (
<div className="loader">
<div className="lds-ripple">
<div></div>
<div></div>
</div>
</div>
)}
{error && <Typography color="error">{error}</Typography>}
</Container>
</div>
);
);
}
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axiosClient from '@/helpers/axiosClient';
import { axiosClient } from '@/helpers/axiosClient';
interface RequestState {
loading: boolean;
error?: string | null;
result: string;
loading: boolean;
error?: string | null;
result: string;
}
interface IData {
password: string;
message: string;
password: string;
message: string;
}
const initialState: RequestState = {
loading: false,
error: null,
result: '',
loading: false,
error: null,
result: '',
};
export const encodeMessage = createAsyncThunk(
'request/encode',
async (data: IData) => {
try {
const response = await axiosClient.post('/encode', data);
return response.data.encoded;
} catch (error: any) {
throw new Error(
error.response?.data?.message || 'Error decoding message'
);
}
}
);
export const encodeMessage = createAsyncThunk('request/encode', async (newMessage: IData) => {
try {
const { data } = await axiosClient.post('/encode', newMessage);
console.log(data);
export const decodeMessage = createAsyncThunk(
'request/decode',
async (data: IData) => {
try {
const response = await axiosClient.post('/decode', data);
return response.data.decoded;
} catch (error: any) {
throw new Error(
error.response?.data?.message || 'Error encoding message'
);
}
}
);
return data.encoded;
} catch (error: any) {
throw new Error(error.response?.data?.message || 'Error decoding message');
}
});
export const decodeMessage = createAsyncThunk('request/decode', async (newMessage: IData) => {
try {
const { data } = await axiosClient.post('/decode', newMessage);
console.log(data);
return data.decoded;
} catch (error: any) {
throw new Error(error.response?.data?.message || 'Error encoding message');
}
});
const requestSlice = createSlice({
name: 'request',
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(encodeMessage.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(encodeMessage.fulfilled, (state, action) => {
state.loading = false;
state.result = action.payload;
})
.addCase(encodeMessage.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message || "Error occured";
})
.addCase(decodeMessage.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(decodeMessage.fulfilled, (state, action) => {
state.loading = false;
state.result = action.payload;
})
.addCase(decodeMessage.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message || "Error occured";
});
},
name: 'request',
initialState,
reducers: {},
extraReducers: (builder) => {
builder
.addCase(encodeMessage.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(encodeMessage.fulfilled, (state, action) => {
state.loading = false;
state.result = action.payload;
})
.addCase(encodeMessage.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message || 'Error occured';
})
.addCase(decodeMessage.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(decodeMessage.fulfilled, (state, action) => {
state.loading = false;
state.result = action.payload;
})
.addCase(decodeMessage.rejected, (state, action) => {
state.loading = false;
state.error = action.error.message || 'Error occured';
});
},
});
export default requestSlice.reducer;
import axios from 'axios';
const axiosClient = axios.create({
baseURL: 'https://localhost/8000',
export const axiosClient = axios.create({
baseURL: 'http://localhost:8000',
});
export default axiosClient;
import { useDispatch, useSelector } from "react-redux";
import type { TypedUseSelectorHook } from "react-redux";
import type { RootState, AppDispatch } from "./store";
import { useDispatch, useSelector } from 'react-redux';
import type { TypedUseSelectorHook } from 'react-redux';
import type { RootState, AppDispatch } from './store';
export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
......@@ -2,9 +2,9 @@ import { configureStore } from '@reduxjs/toolkit';
import requestReducer from '@/features/requestSlice';
export const store = configureStore({
reducer: {
request: requestReducer,
},
reducer: {
request: requestReducer,
},
});
export type RootState = ReturnType<typeof store.getState>;
......
......@@ -6,6 +6,12 @@ ConfigModule.forRoot();
async function startServer() {
const app = await NestFactory.create(MessageModule);
app.enableCors({
origin: 'http://localhost:666',
methods: 'GET,POST,PUT,DELETE',
allowedHeaders: 'Content-Type,Authorization',
credentials: true,
});
await app.listen(8000);
}
startServer();
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment