Commit e2dd9549 authored by Цой Кирилл's avatar Цой Кирилл

Initial commit

parents
node_modules
\ No newline at end of file
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
'prettier',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 'latest',
sourceType: 'module',
// project: "./tsconfig.json",
},
plugins: ['react-refresh', 'react', '@typescript-eslint'],
rules: {
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
'react/react-in-jsx-scope': 0,
},
};
node_modules
\ No newline at end of file
node_modules
build
.next
dist
\ No newline at end of file
module.exports = {
tabWidth: 2,
singleQuote: true,
trailingComma: "es5",
printWidth: 100,
useTabs: false,
};
# Eslint_Prettier_VScode
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
This diff is collapsed.
{
"name": "client",
"private": true,
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"lint-fix": "eslint --fix 'src/**/*.{js,ts,tsx}'",
"preview": "vite preview",
"check": "npm-check -uE"
},
"dependencies": {
"@emotion/styled": "^11.11.5",
"@fontsource/roboto": "^5.0.12",
"@mui/material": "5.15.15",
"@reduxjs/toolkit": "2.2.3",
"antd": "^5.16.1",
"axios": "1.6.8",
"path": "^0.12.7",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^9.1.0",
"react-router-dom": "^6.22.3"
},
"devDependencies": {
"@types/node": "20.12.7",
"@types/react": "18.2.75",
"@types/react-dom": "18.2.24",
"@typescript-eslint/eslint-plugin": "^6.20.0",
"@typescript-eslint/parser": "^6.14.0",
"@vitejs/plugin-react": "^4.2.1",
"eslint": "^8.55.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-react": "7.34.1",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
"prettier": "^3.2.5",
"vite": "5.2.8"
}
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
\ No newline at end of file
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
import { Link, Route, Routes } from 'react-router-dom';
import { Products } from './containers/Products';
import { NewProductForm } from './containers/NewProductForm';
import { Breadcrumb, Layout, theme } from 'antd';
import { AppToolbar } from './components/UI/AppToolbar';
const { Content, Footer } = Layout;
const layoutStyle = {
overflow: 'hidden',
width: '100%',
};
function App() {
const {
token: { colorBgContainer, borderRadiusLG },
} = theme.useToken();
return (
<Layout style={layoutStyle}>
<AppToolbar />
<Content style={{ padding: '0 48px' }}>
<Breadcrumb style={{ margin: '16px 0' }}>
<Breadcrumb.Item>
<Link to="/">Home</Link>
</Breadcrumb.Item>
<Breadcrumb.Item>Products</Breadcrumb.Item>
</Breadcrumb>
<div
style={{
background: colorBgContainer,
minHeight: 280,
padding: 24,
borderRadius: borderRadiusLG,
}}
>
<Routes>
<Route path="/" element={<Products />} />
<Route path="/products/new" element={<NewProductForm />} />
</Routes>
</div>
</Content>
<Footer style={{ textAlign: 'center' }}>
Ant Design ©{new Date().getFullYear()} Created by Ant UED
</Footer>
</Layout>
);
}
export default App;
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
\ No newline at end of file
import { Alert, Form, FormInstance, Input } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { useAppDispatch, useAppSelector } from '@/store/hook';
import { UserRequest, loginUser } from '@/features/userSlice';
import { useContext, useEffect, useState } from 'react';
import { UserContext } from '@/hooks/auth';
interface Props {
form: FormInstance;
closeModal: () => void;
}
export function LoginForm({ form, closeModal }: Props) {
const dispatch = useAppDispatch();
const { loading, loginError } = useAppSelector((state) => state.user);
const [submitted, setSubmitted] = useState(false);
const userContext = useContext(UserContext);
useEffect(() => {
if (!loading && submitted && !loginError) {
userContext.setToken('abc');
form.resetFields();
closeModal();
}
}, [loading, submitted]);
const onFinish = (values: UserRequest) => {
dispatch(loginUser(values));
setSubmitted(true);
};
return (
<>
<Form name="login-form" onFinish={onFinish} form={form}>
{loginError ? (
<Form.Item>
<Alert message={loginError} type="error" />
</Form.Item>
) : null}
<Form.Item
name="username"
// rules={[{ required: true, message: 'Please input your Username!' }]}
>
<Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="Username" />
</Form.Item>
<Form.Item
name="password"
// rules={[{ required: true, message: 'Please input your Password!' }]}
>
<Input
prefix={<LockOutlined className="site-form-item-icon" />}
type="password"
placeholder="Password"
/>
</Form.Item>
</Form>
</>
);
}
import { logoutUser } from '@/features/userSlice';
import { UserContext } from '@/hooks/auth';
import { useAppDispatch } from '@/store/hook';
import { useContext } from 'react';
import { useNavigate } from 'react-router-dom';
export function Logout() {
const navigate = useNavigate();
const user = useContext(UserContext);
const dispatch = useAppDispatch();
const onClick = () => {
dispatch(logoutUser());
localStorage.removeItem('token');
user.setToken('');
navigate('/');
};
return <a onClick={onClick}>Logout</a>;
}
import { IProduct } from '@/containers/Products';
// import { ChangeEvent, FormEvent, useState } from 'react';
import { Button, Form, Input, InputNumber, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import TextArea from 'antd/es/input/TextArea';
import { useState } from 'react';
interface Props {
onProductFormSubmit: (product: FormData) => Promise<void>;
}
export function ProductForm({ onProductFormSubmit }: Props) {
const [file, setFile] = useState<File | undefined>();
const submitFormHandler = (values: IProduct) => {
const formData: FormData = new FormData();
Object.entries(values).forEach(([key, value]) => {
if (!Array.isArray(value) && value) {
formData.append(key, value);
}
});
if (file) {
formData.append('image', file);
}
onProductFormSubmit(formData);
};
// const fileChangeHandler = (e: ChangeEvent<HTMLInputElement>) => {
// if (e?.target?.files?.[0]) {
// const name = e.target.name;
// const file: File = e.target.files[0];
// setProduct((prevProduct) => {
// return { ...prevProduct, [name]: file };
// });
// }
// };
const normFile = (e: { file: File; fileList: File[] }) => {
console.log('Upload event:', e);
if (e?.file) {
setFile(e.file);
}
};
// <FileInput label="Image" name="image" onChange={fileChangeHandler}/>
return (
<Form name="product-creation" onFinish={submitFormHandler}>
<Form.Item
label="Title"
name="title"
rules={[{ required: true, message: 'Please enter title' }]}
>
<Input placeholder="Username" />
</Form.Item>
<Form.Item
label="Price"
name="price"
rules={[{ required: true, message: 'Please enter price' }]}
>
<InputNumber min={1} />
</Form.Item>
<Form.Item
label="Category"
name="categoryId"
rules={[{ required: true, message: 'Please enter categoryId' }]}
>
<InputNumber min={1} />
</Form.Item>
<Form.Item label="Description" name="description">
<TextArea />
</Form.Item>
<Form.Item name="image" label="Image" valuePropName="fileList" getValueFromEvent={normFile}>
<Upload name="logo" listType="picture" beforeUpload={() => false}>
<Button icon={<UploadOutlined />}>Click to upload</Button>
</Upload>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" className="login-form-button">
Create new product
</Button>
</Form.Item>
</Form>
);
}
import { Form, FormInstance, Input } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { UserRequest, registerUser } from '@/features/userSlice';
import { useAppDispatch, useAppSelector } from '@/store/hook';
import { useEffect, useState } from 'react';
interface Props {
form: FormInstance;
closeModal: () => void;
}
export function RegisterForm({ form, closeModal }: Props) {
const dispatch = useAppDispatch();
const errors = useAppSelector((state) => state.user.registerError);
const loading = useAppSelector((state) => state.user.loading);
const [submitted, setSubmitted] = useState(false);
useEffect(() => {
if (!loading && submitted) {
if (Array.isArray(errors)) {
const fieldsError = errors.map((err) => {
return { name: err.type, errors: err.message };
});
form.setFields(fieldsError);
} else {
form.resetFields();
closeModal();
}
}
}, [loading, submitted]);
const onFinish = (values: UserRequest) => {
dispatch(registerUser(values));
setSubmitted(true);
};
return (
<Form name="register-form" onFinish={onFinish} form={form}>
<Form.Item
name="username"
// rules={[{ required: true, message: 'Please input your Username!' }]}
>
<Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="Username" />
</Form.Item>
<Form.Item name="displayName">
<Input
prefix={<UserOutlined className="site-form-item-icon" />}
placeholder="Display name"
/>
</Form.Item>
<Form.Item
name="password"
// rules={[{ required: true, message: 'Please input your Password!' }]}
>
<Input
prefix={<LockOutlined className="site-form-item-icon" />}
type="password"
placeholder="Password"
/>
</Form.Item>
</Form>
);
}
import { AuthModal } from '@/containers/AuthModal';
import { UserContext } from '@/hooks/auth';
import { Menu, MenuProps } from 'antd';
import { Header } from 'antd/es/layout/layout';
import { useContext } from 'react';
import { Logout } from '../Logout';
export function AppToolbar() {
const user = useContext(UserContext);
let items: MenuProps['items'] = [];
if (user.token) {
items.push({
label: <Logout />,
key: 'logout',
});
} else {
items = items.concat([
{
label: <AuthModal type="register" />,
key: 'register',
},
{
label: <AuthModal type="login" />,
key: 'login',
},
]);
}
return (
<Header style={{ display: 'flex', alignItems: 'center' }}>
<div className="demo-logo" style={{ color: 'white' }}>
Computer parts shop
</div>
<Menu
theme="dark"
mode="horizontal"
items={items}
style={{ flex: 1, minWidth: 0 }}
selectable={false}
/>
</Header>
);
}
import { Button, Grid, TextField, styled } from "@mui/material";
import { ChangeEvent, useRef, useState } from "react";
interface Props {
name: string;
label: string;
onChange: (event: ChangeEvent<HTMLInputElement>) => void;
}
const HiddenInputFile = styled("input")({display: 'none'});
export function FileInput({name, label, onChange}: Props) {
const inputRef = useRef<HTMLInputElement>(null);
const [fileName, setFileName] = useState("");
const activeInput = () => {
if (inputRef.current) {
inputRef.current.click();
}
}
const onFileChange = (e: ChangeEvent<HTMLInputElement>) => {
if (e?.target?.files?.[0]) {
setFileName(e.target.files[0].name);
} else {
setFileName("");
}
onChange(e);
}
return <>
<HiddenInputFile
type="file"
name={name}
onChange={onFileChange}
ref={inputRef}
/>
<Grid container direction={"row"} spacing={2} alignItems={"center"}>
<Grid item xs>
<TextField
variant="outlined"
fullWidth
label={label}
value={fileName}
disabled
onClick={activeInput}
/>
</Grid>
<Grid item>
<Button variant="contained" onClick={activeInput}>Browse</Button>
</Grid>
</Grid>
</>
}
\ No newline at end of file
import { LoginForm } from '@/components/LoginForm';
import { RegisterForm } from '@/components/RegisterForm';
import { Flex, Modal, Form } from 'antd';
import { useState } from 'react';
interface Props {
type: 'register' | 'login';
}
export function AuthModal({ type }: Props) {
const [isModalOpen, setIsModalOpen] = useState(false);
const [form] = Form.useForm();
const showModal = () => {
setIsModalOpen(true);
};
const handleCancel = () => {
setIsModalOpen(false);
form.resetFields();
};
const handleOk = async () => {
try {
await form.validateFields();
form.submit();
} catch (e) {}
};
const buttonText = type === 'register' ? 'Register' : 'Login';
return (
<>
<a onClick={showModal}>{buttonText}</a>
<Modal
title={buttonText}
open={isModalOpen}
onOk={handleOk}
onCancel={handleCancel}
okText={buttonText}
>
<Flex gap="middle" align="start" justify="center">
{type === 'register' ? (
<RegisterForm form={form} closeModal={() => setIsModalOpen(false)} />
) : (
<LoginForm form={form} closeModal={() => setIsModalOpen(false)} />
)}
</Flex>
</Modal>
</>
);
}
import { ProductForm } from '@/components/ProductForm';
import { createProduct } from '@/features/productsSlice';
import { useAppDispatch } from '@/store/hook';
import { useNavigate } from 'react-router-dom';
import { Typography } from 'antd';
const { Title } = Typography;
export function NewProductForm() {
const dispatch = useAppDispatch();
const navigate = useNavigate();
const onProductFormSubmit = async (product: FormData) => {
await dispatch(createProduct(product));
navigate('/');
};
return (
<>
<Title level={3}>New product</Title>
<ProductForm onProductFormSubmit={onProductFormSubmit} />
</>
);
}
import { IProduct } from './Products';
import imageNotAvalable from '../assets/images/image_not_available.jpg';
import { apiUrl } from '@/helpers/axiosApiClient';
import { Card } from 'antd'
import { EllipsisOutlined } from '@ant-design/icons';
const { Meta } = Card;
interface Props {
product: IProduct;
}
export function ProductItem({ product }: Props) {
const { title, price, description, image } = product;
let cardImage = imageNotAvalable;
if (image) {
cardImage = image.startsWith('http') ? image : `${apiUrl}/uploads/${image}`;
}
return (
<Card
hoverable
style={{ width: 240 }}
cover={<img alt="example" src={cardImage} />}
actions={[<EllipsisOutlined key="ellipsis" />]}
>
<Meta title={title} description={description} />
<span>{price}</span>
</Card>
);
}
import { fetchProducts } from '@/features/productsSlice';
import { useAppDispatch, useAppSelector } from '@/store/hook';
import { useEffect } from 'react';
import { ProductItem } from './ProductItem';
import { Flex, Typography } from 'antd';
import { Link } from 'react-router-dom';
const { Title } = Typography;
export function Products() {
const dispatch = useAppDispatch();
const { products } = useAppSelector((state) => state.products);
useEffect(() => {
dispatch(fetchProducts());
}, [dispatch]);
return (
<>
<Title level={3}>Products</Title>
<Flex wrap="wrap" gap="large" justify="center">
{products.map((product) => (
<ProductItem key={product.id} product={product} />
))}
</Flex>
<Link to={'/products/new'}>Add product</Link>
</>
);
}
export interface IProduct {
id: string;
title: string;
description: string;
price: number;
image: string;
userId?: number;
user: { displayName: string };
}
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { IProduct } from "@/containers/Products";
import { axiosApiClient } from "../helpers/axiosApiClient";
interface State {
products: IProduct[];
error: Error | null;
loading: boolean;
}
const initialState: State = {
products: [],
error: null,
loading: false
};
export const fetchProducts = createAsyncThunk('fetch/products', async () => {
return await axiosApiClient.get<IProduct[]>('/products').then(res => res.data);
});
export const createProduct = createAsyncThunk('create/product',
async (payload: FormData) => {
const token = localStorage.getItem('token');
return axiosApiClient.post<IProduct>("/products/create", payload, {headers: {'Authorization': token}})
.then(res => res.data);
});
const productsSlice = createSlice(
{
name: 'products',
initialState,
reducers: {},
extraReducers(builder) {
builder.addCase(fetchProducts.fulfilled, (state, action) => {
state.products = action.payload;
state.loading = false;
}).addCase(fetchProducts.rejected, (state, action) => {
state.loading = false;
state.error = action.error as Error;
})
.addCase(fetchProducts.pending, (state) => {
state.loading = true;
})
},
}
)
export default productsSlice.reducer;
import { axiosApiClient } from "@/helpers/axiosApiClient";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { AxiosError, isAxiosError } from "axios";
interface IUser {
id: number;
username: string;
displayName?: string;
password?: string;
}
interface UserState {
user: IUser | null;
loading: boolean;
registerError: string | null | UserResponseValidateError;
loginError: string | null;
}
export type UserRequest = {
username: string;
displayName?: string;
password: string;
}
type UserResponseError = {
error: { message: string };
}
type UserResponseValidateError = {
type: string;
message: string[]
}[];
export const registerUser = createAsyncThunk<IUser, UserRequest, {rejectValue: UserResponseError | UserResponseValidateError}>("auth/register",
async(userData: UserRequest, {rejectWithValue}) => {
try {
const response = await axiosApiClient.post<IUser>("auth/register",userData);
localStorage.setItem("token", response.headers["authorization"]);
return response.data;
} catch(e) {
if (isAxiosError(e)) {
const error: AxiosError<UserResponseError> = e;
return rejectWithValue(error?.response?.data ||
{ error:{message:'An error occured'}
});
}
throw e;
}
}
);
export const loginUser = createAsyncThunk<IUser, UserRequest, {rejectValue: string}>("auth/login",
async(userData: UserRequest, {rejectWithValue}) => {
try{
const response = await axiosApiClient.post<IUser>("auth/sign-in", userData);
localStorage.setItem("token", response.headers["authorization"]);
return response.data;
} catch(e) {
if (isAxiosError(e)) {
const error: AxiosError<UserResponseError> = e;
return rejectWithValue(error?.response?.data?.error?.message ||
'An error occured'
);
}
throw e;
}
}
);
export const logoutUser = createAsyncThunk("auth/logout", async(_, { rejectWithValue })=>{
const token = localStorage.getItem('token');
try {
const response = await axiosApiClient.delete('auth.logout', { headers: { 'Authorization': token } });
return response.data
} catch(e){
if (isAxiosError(e)) {
const error: AxiosError<UserResponseError> = e;
return rejectWithValue(error?.response?.data?.error?.message ||
'An error occured'
);
}
throw e
}
})
const initialState: UserState = {
user: null,
loading: false,
loginError: null,
registerError: null,
}
const userSlice = createSlice({
name: "user",
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(registerUser.pending, (state) => {
state.loading = true;
state.registerError = null;
})
.addCase(registerUser.fulfilled, (state, action) => {
state.user = action.payload ?? null;
state.loading = false;
})
.addCase(registerUser.rejected, (state, action) => {
if (Array.isArray(action.payload)) {
state.registerError = action.payload;
} else {
state.registerError = action?.payload?.error.message ?? "Something went wrong";
}
state.loading = false;
})
.addCase(loginUser.pending, (state) => {
state.loading = true;
state.loginError = null;
})
.addCase(loginUser.fulfilled, (state, action) => {
state.user = action.payload ?? null;
state.loading = false;
})
.addCase(loginUser.rejected, (state, action) => {
// if (Array.isArray(action.payload)) {
// state.loginError = action.payload;
// } else {
state.loginError = action?.payload ?? "Something went wrong";
// }
state.loading = false;
})
.addCase(logoutUser.fulfilled, (state)=>{
state.user = initialState.user
})
}
});
export default userSlice.reducer;
\ No newline at end of file
import axios from "axios";
export const apiUrl = "http://localhost:8000";
export const axiosApiClient = axios.create({
baseURL: apiUrl
});
\ No newline at end of file
import { createContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
interface Props {
children: React.ReactNode;
}
interface IUserContext {
token?: string;
setToken: (token: string) => void;
loading?: boolean;
}
export const UserContext = createContext<IUserContext>({});
export function UserProvider({ children }: Props) {
const [token, setToken] = useState<string | undefined>(undefined);
const [loading, setLoading] = useState(true);
// const navigate = useNavigate();
useEffect(() => {
const storedToken = localStorage.getItem('token');
if (storedToken) {
setToken(storedToken as string);
setLoading(false);
} else {
// navigate('/login');
}
}, []);
return (
<UserContext.Provider value={{ token, setToken, loading }}>{children}</UserContext.Provider>
);
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu',
'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
}
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import App from './App.tsx';
import store from './store';
import { UserProvider } from './hooks/auth.tsx';
import './index.css';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
<UserProvider>
<App />
</UserProvider>
</BrowserRouter>
</Provider>
</React.StrictMode>
);
import { useDispatch, useSelector } from 'react-redux';
import type { TypedUseSelectorHook } from 'react-redux';
import { AppDispatch, RootState } from '.';
export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
\ No newline at end of file
import { configureStore } from '@reduxjs/toolkit';
import productsReducer from '../features/productsSlice.ts';
import userReducer from "../features/userSlice.ts";
const store = configureStore({
reducer: {
products: productsReducer,
user: userReducer,
}
})
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export default store;
/// <reference types="vite/client" />
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": [
"ES2020",
"DOM",
"DOM.Iterable"
],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"paths": {
"@/*": [
"./src/*"
],
"@components/*": ["./src/components/*"],
"@features/*": ["./src/features/*"],
}
},
"include": [
"src"
],
"references": [
{
"path": "./tsconfig.node.json"
}
]
}
\ No newline at end of file
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@features': path.resolve(__dirname, './src/features'),
'@components': path.resolve(__dirname, './src/components'),
},
},
})
This source diff could not be displayed because it is too large. You can view the blob instead.
{
"name": "webinar_42",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "npm i & ultra -r npm i & ultra -r dev",
"install": "ultra -r npm i",
"check": "npm-check -uE"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^6.20.0",
"@typescript-eslint/parser": "^6.14.0",
"eslint": "^8.55.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
"prettier": "^3.2.5",
"typescript": "5.4.5",
"ultra-runner": "^3.10.5"
}
}
module.exports = {
parser: '@typescript-eslint/parser',
extends: ['eslint:recommended', 'prettier'],
parserOptions: {
ecmaVersion: 2020,
sourceType: 'module',
},
env: {
es6: true,
node: true,
},
rules: {
'no-var': 'error',
semi: 'error',
indent: ['error', 2, { SwitchCase: 1 }],
'no-multi-spaces': 'error',
'space-in-parens': 'error',
'no-multiple-empty-lines': 'error',
'prefer-const': 'error',
},
};
node_modules
\ No newline at end of file
{
"semi": true,
"trailingComma": "all",
"singleQuote": true,
"printWidth": 150,
"tabWidth": 2
}
module.exports = {
presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript'],
plugins: [
['@babel/plugin-proposal-decorators', { legacy: true }],
['@babel/plugin-transform-flow-strip-types'],
['@babel/plugin-proposal-class-properties', { loose: true }],
],
};
[
{
"title": "Lorem ipsum",
"description": "Dolor si amet",
"price": 500,
"id": "0.9133269846292313"
},
{
"title": "Lorem ipsum 2",
"description": "Dolor si amet",
"price": 500,
"id": "0.09792516360811865"
},
{
"title": "Lorem ipsum 3",
"description": "Dolor si amet",
"price": 500,
"id": "0.5230269041392861"
},
{
"description": "Ideal for a zombie",
"price": "687645",
"title": "Griffiths-grr",
"id": "0.7259402088168749"
},
{
"description": "Lorem ipsum",
"price": "787",
"title": "Fedora",
"id": "0.46771740109606696"
},
{
"description": "lorem ipsum",
"price": "12345",
"title": "fedora 2",
"image": "ec325ffe-c219-4940-a60a-8e9210d32ab2.png",
"id": "0.5004988745850678"
}
]
import * as fs from 'fs';
const fileName = 'test.txt';
fs.writeFile(fileName, 'Hello world', (err) => {
if (err) {
console.log(err);
}
console.log('File was created');
});
{
"watch": ["src"],
"ignore": ["**/*.test.ts", "**/*.spec.ts", ".git", "node_modules"],
"ext": "ts",
"exec": "node -r tsconfig-paths/register -r ts-node/register ./src/index.ts"
}
This diff is collapsed.
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest",
"dev": "nodemon",
"lint": "eslint",
"lint:fix": "eslint --fix",
"check": "npm-check -uE",
"format:check": "prettier --check .",
"format:write": "prettier --write .",
"lint:check": "eslint .",
"seed": "node -r tsconfig-paths/register -r ts-node/register src/database/init.seeds.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.1.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"cors": "^2.8.5",
"express": "^4.18.2",
"lodash": "^4.17.21",
"multer": "^1.4.5-lts.1",
"mysql2": "^3.9.4",
"nanoid": "^5.0.7",
"reflect-metadata": "^0.2.1",
"ts-node": "^10.9.1",
"tslib": "^2.6.0",
"typeorm": "^0.3.20",
"typeorm-extension": "^3.5.1"
},
"devDependencies": {
"@babel/plugin-proposal-class-properties": "^7.18.6",
"@babel/plugin-proposal-decorators": "^7.24.1",
"@babel/plugin-transform-flow-strip-types": "^7.24.1",
"@babel/preset-env": "^7.24.4",
"@babel/preset-typescript": "^7.24.1",
"@faker-js/faker": "^8.4.1",
"@jest/globals": "^29.7.0",
"@types/bcrypt": "^5.0.2",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.17",
"@types/jest": "^29.5.12",
"@types/lodash": "^4.17.0",
"@types/multer": "^1.4.11",
"@types/node": "20.12.7",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"eslint": "^8.57.0",
"eslint-config-prettier": "^8.10.0",
"eslint-plugin-prettier": "^5.0.0",
"jest": "^29.7.0",
"nodemon": "^3.0.1",
"prettier": "^3.2.5",
"tsconfig-paths": "^4.2.0"
},
"jest": {
"moduleNameMapper": {
"^@/(.*)$": "<rootDir>/src/$1"
}
}
}
<svg width="2500" height="2100" viewBox="0 0 256 215" xmlns="http://www.w3.org/2000/svg"><g fill="none" fill-rule="evenodd"><path d="M38.617 173.984v-16.362c0-2.15 1.344-3.877 3.57-3.877h.616c2.225 0 3.563 1.729 3.563 3.877v34.447c0 8.4-4.15 15.084-11.382 19.342a21.374 21.374 0 0 1-10.945 2.985h-1.537c-8.402 0-15.077-4.153-19.342-11.38a21.314 21.314 0 0 1-2.984-10.947v-1.535c0-8.403 4.152-15.083 11.378-19.349a21.298 21.298 0 0 1 10.948-2.985h1.537c5.686 0 10.51 2.204 14.578 5.784zM7.924 191.3c0 6.068 2.941 10.63 8.258 13.54 2.15 1.176 4.484 1.808 6.937 1.808 5.956 0 10.374-2.81 13.421-7.857 1.417-2.348 2.077-4.917 2.077-7.648 0-5.26-2.49-9.365-6.729-12.414-2.57-1.848-5.463-2.775-8.618-2.775-6.492 0-11.164 3.28-13.968 9.106-.946 1.97-1.378 4.061-1.378 6.24zm65.324-23.1h1.074c8.978 0 15.806 4.355 20.133 12.192 1.73 3.135 2.656 6.557 2.656 10.142v1.535c0 8.4-4.142 15.093-11.385 19.343-3.353 1.967-7.057 2.984-10.943 2.984h-1.535c-8.402 0-15.079-4.153-19.342-11.38a21.316 21.316 0 0 1-2.987-10.947v-1.535c0-8.404 4.169-15.062 11.377-19.347 3.351-1.991 7.058-2.987 10.952-2.987zm-14.58 23.1c0 5.89 2.89 10.223 7.865 13.27 2.336 1.43 4.909 2.078 7.638 2.078 5.82 0 10.122-2.951 13.116-7.863 1.428-2.342 2.074-4.915 2.074-7.642 0-5.477-2.638-9.661-7.148-12.693-2.471-1.663-5.222-2.496-8.198-2.496-6.492 0-11.164 3.28-13.967 9.106-.948 1.97-1.38 4.061-1.38 6.24zm70.656-14.727c-1.17-.548-3.36-.73-4.624-.778-6.474-.244-11.158 3.402-13.906 9.113-.949 1.97-1.382 4.055-1.382 6.235 0 6.637 3.485 11.284 9.409 14.117 2.164 1.034 4.958 1.23 7.323 1.23 2.08 0 5.02-1.274 6.866-2.151l.32-.152h1.433l.158.032c1.762.367 3.092 1.484 3.092 3.38v.767c0 4.718-8.622 5.798-11.912 6.028-11.61.803-20.293-5.573-23.603-16.647-.575-1.923-.834-3.833-.834-5.837v-1.533c0-8.403 4.17-15.059 11.377-19.34 3.351-1.99 7.057-2.99 10.95-2.99h1.536c4.13 0 7.934 1.173 11.344 3.502l.28.194.177.292c.368.61.685 1.316.685 2.042v.767c0 1.978-1.48 3.042-3.266 3.386l-.148.026h-.458c-1.156 0-3.785-1.197-4.817-1.683zm25.134 5.247c3.01-3.014 6.03-6.022 9.085-8.986.851-.827 4.074-4.327 5.343-4.327h1.388l.158.033c1.768.367 3.092 1.486 3.092 3.386v.766c0 1.296-1.518 2.802-2.355 3.689-1.78 1.887-3.654 3.712-5.476 5.56l-9.362 9.504c4.031 4.04 8.058 8.083 12.056 12.154a313.304 313.304 0 0 1 3.301 3.396c.385.405.953.909 1.276 1.47.347.526.56 1.119.56 1.752v.8l-.045.185c-.435 1.768-1.557 3.194-3.516 3.194h-.617c-1.282 0-2.73-1.45-3.608-2.279-1.81-1.706-3.557-3.5-5.331-5.243l-5.949-5.84v9.334c0 2.15-1.346 3.878-3.569 3.878h-.61c-2.226 0-3.57-1.728-3.57-3.878v-52.596c0-2.15 1.345-3.87 3.57-3.87h.61c2.223 0 3.569 1.72 3.569 3.87v24.048zm96.577-13.313h.77c2.324 0 3.875 1.566 3.875 3.877 0 3.208-3.067 4.029-5.72 4.029-3.48 0-6.803 2.107-9.202 4.47-2.991 2.949-4.3 6.726-4.3 10.878v18.759c0 2.15-1.343 3.876-3.57 3.876h-.612c-2.227 0-3.569-1.725-3.569-3.876v-19.836c0-7.617 3.708-13.835 9.89-18.196 3.691-2.605 7.919-3.98 12.438-3.98zm-55.074 37.176c2.82.985 6.035.844 8.928.34 1.48-.629 5.264-2.28 6.656-2.038l.217.037.2.098c.85.412 1.661.995 2.095 1.86 1.014 2.027.527 4.065-1.465 5.216l-.663.383c-7.35 4.242-15.168 3.654-22.495-.308-3.503-1.894-6.183-4.705-8.16-8.132l-.462-.801c-4.719-8.172-4.082-16.768 1.24-24.539 1.837-2.686 4.238-4.761 7.045-6.384l1.062-.613c6.922-3.996 14.341-3.722 21.45-.215 3.823 1.886 6.92 4.697 9.054 8.394l.384.666c1.55 2.686-.458 5.026-2.531 6.626-2.406 1.856-4.835 4.09-7.141 6.08-5.142 4.439-10.276 8.888-15.414 13.33zm-6.655-4.674c5.75-4.93 11.502-9.865 17.237-14.816 1.96-1.69 4.109-3.444 6.053-5.221-1.56-1.966-4.166-3.383-6.38-4.228-4.47-1.703-8.877-1.131-12.976 1.235-5.365 3.098-7.65 8.031-7.45 14.17.08 2.418.73 4.748 2.013 6.805.452.725.957 1.406 1.503 2.055zM147.488 45.732h22.866v23.375h11.561c5.34 0 10.831-.951 15.887-2.664 2.485-.843 5.273-2.015 7.724-3.49-3.228-4.214-4.876-9.535-5.36-14.78-.66-7.135.78-16.421 5.608-22.005l2.404-2.78 2.864 2.303c7.211 5.793 13.276 13.889 14.345 23.118 8.683-2.554 18.878-1.95 26.531 2.467l3.14 1.812-1.652 3.226C246.933 68.946 233.4 72.86 220.17 72.167c-19.797 49.309-62.898 72.653-115.157 72.653-27 0-51.77-10.093-65.876-34.047l-.231-.39-2.055-4.182c-4.768-10.544-6.352-22.095-5.278-33.637l.323-3.457H51.45V45.732h22.865V22.866h45.733V0h27.44v45.732" fill="#364548"/><path d="M221.57 54.38c1.533-11.916-7.384-21.275-12.914-25.719-6.373 7.368-7.363 26.678 2.635 34.808-5.58 4.956-17.337 9.448-29.376 9.448H35.37c-1.17 12.567 1.036 24.14 6.075 34.045l1.667 3.05a56.536 56.536 0 0 0 3.455 5.184c6.025.387 11.58.52 16.662.408h.002c9.987-.22 18.136-1.4 24.312-3.54a1.761 1.761 0 0 1 1.153 3.326c-.822.286-1.678.552-2.562.805h-.003c-4.863 1.389-10.078 2.323-16.806 2.738.4.007-.416.06-.418.06-.229.015-.517.048-.747.06-2.648.149-5.506.18-8.428.18-3.196 0-6.343-.06-9.862-.24l-.09.06c12.21 13.724 31.302 21.955 55.234 21.955 50.648 0 93.608-22.452 112.632-72.857 13.496 1.385 26.467-2.057 32.367-13.575-9.398-5.423-21.484-3.694-28.443-.196" fill="#22A0C8"/><path d="M221.57 54.38c1.533-11.916-7.384-21.275-12.914-25.719-6.373 7.368-7.363 26.678 2.635 34.808-5.58 4.956-17.337 9.448-29.376 9.448H44.048c-.598 19.246 6.544 33.855 19.18 42.687h.003c9.987-.22 18.136-1.4 24.312-3.54a1.761 1.761 0 0 1 1.153 3.326c-.822.286-1.678.552-2.562.805h-.003c-4.863 1.389-10.526 2.443-17.254 2.858-.002 0-.163-.155-.165-.155 17.237 8.842 42.23 8.81 70.885-2.197 32.13-12.344 62.029-35.86 82.89-62.757-.314.142-.62.287-.917.436" fill="#37B1D9"/><path d="M35.645 88.186c.91 6.732 2.88 13.035 5.8 18.776l1.667 3.05a56.432 56.432 0 0 0 3.455 5.184c6.026.387 11.581.52 16.664.408 9.987-.22 18.136-1.4 24.312-3.54a1.761 1.761 0 0 1 1.153 3.326c-.822.286-1.678.552-2.562.805h-.003c-4.863 1.389-10.496 2.383-17.224 2.799-.231.014-.634.017-.867.03-2.646.148-5.475.239-8.398.239-3.195 0-6.463-.061-9.98-.24 12.21 13.724 31.42 21.985 55.352 21.985 43.36 0 81.084-16.458 102.979-52.822H35.645" fill="#1B81A5"/><path d="M45.367 88.186c2.592 11.82 8.821 21.099 17.864 27.418 9.987-.22 18.136-1.4 24.312-3.54a1.761 1.761 0 0 1 1.153 3.326c-.822.286-1.678.552-2.562.805h-.003c-4.863 1.389-10.615 2.383-17.344 2.799 17.236 8.84 42.157 8.713 70.81-2.293 17.334-6.66 34.017-16.574 48.984-28.515H45.367" fill="#1D91B4"/><path d="M55.26 49.543h19.818v19.818H55.26V49.543zm1.651 1.652h1.564V67.71h-1.564V51.195zm2.94 0h1.627V67.71h-1.626V51.195zm3.002 0h1.627V67.71h-1.627V51.195zm3.004 0h1.626V67.71h-1.626V51.195zm3.003 0h1.626V67.71H68.86V51.195zm3.002 0h1.565V67.71h-1.565V51.195zM78.126 26.677h19.819v19.817h-19.82V26.677zm1.652 1.652h1.563v16.514h-1.563V28.329zm2.94 0h1.626v16.514h-1.625V28.329zm3.002 0h1.626v16.514H85.72V28.329zm3.003 0h1.626v16.514h-1.626V28.329zm3.003 0h1.627v16.514h-1.627V28.329zm3.002 0h1.566v16.514h-1.566V28.329z" fill="#23A3C2"/><path d="M78.126 49.543h19.819v19.818h-19.82V49.543zm1.652 1.652h1.563V67.71h-1.563V51.195zm2.94 0h1.626V67.71h-1.625V51.195zm3.002 0h1.626V67.71H85.72V51.195zm3.003 0h1.626V67.71h-1.626V51.195zm3.003 0h1.627V67.71h-1.627V51.195zm3.002 0h1.566V67.71h-1.566V51.195z" fill="#34BBDE"/><path d="M100.993 49.543h19.818v19.818h-19.818V49.543zm1.651 1.652h1.563V67.71h-1.563V51.195zm2.94 0h1.626V67.71h-1.626V51.195zm3.003 0h1.626V67.71h-1.626V51.195zm3.003 0h1.626V67.71h-1.626V51.195zm3.002 0h1.628V67.71h-1.628V51.195zm3.003 0h1.564V67.71h-1.564V51.195z" fill="#23A3C2"/><path d="M100.993 26.677h19.818v19.817h-19.818V26.677zm1.651 1.652h1.563v16.514h-1.563V28.329zm2.94 0h1.626v16.514h-1.626V28.329zm3.003 0h1.626v16.514h-1.626V28.329zm3.003 0h1.626v16.514h-1.626V28.329zm3.002 0h1.628v16.514h-1.628V28.329zm3.003 0h1.564v16.514h-1.564V28.329zM123.859 49.543h19.818v19.818h-19.818V49.543zm1.652 1.652h1.563V67.71h-1.563V51.195zm2.94 0h1.626V67.71h-1.626V51.195zm3.002 0h1.626V67.71h-1.626V51.195zm3.003 0h1.627V67.71h-1.627V51.195zm3.003 0h1.627V67.71h-1.627V51.195zm3.003 0h1.564V67.71h-1.564V51.195z" fill="#34BBDE"/><path d="M123.859 26.677h19.818v19.817h-19.818V26.677zm1.652 1.652h1.563v16.514h-1.563V28.329zm2.94 0h1.626v16.514h-1.626V28.329zm3.002 0h1.626v16.514h-1.626V28.329zm3.003 0h1.627v16.514h-1.627V28.329zm3.003 0h1.627v16.514h-1.627V28.329zm3.003 0h1.564v16.514h-1.564V28.329z" fill="#23A3C2"/><path d="M123.859 3.81h19.818V23.63h-19.818V3.81zm1.652 1.651h1.563v16.516h-1.563V5.46zm2.94 0h1.626v16.516h-1.626V5.46zm3.002 0h1.626v16.516h-1.626V5.46zm3.003 0h1.627v16.516h-1.627V5.46zm3.003 0h1.627v16.516h-1.627V5.46zm3.003 0h1.564v16.516h-1.564V5.46z" fill="#34BBDE"/><path d="M146.725 49.543h19.818v19.818h-19.818V49.543zm1.65 1.652h1.565V67.71h-1.564V51.195zm2.94 0h1.627V67.71h-1.626V51.195zm3.004 0h1.627V67.71h-1.627V51.195zm3.002 0h1.627V67.71h-1.627V51.195zm3.004 0h1.626V67.71h-1.626V51.195zm3.002 0h1.564V67.71h-1.564V51.195z" fill="#23A3C2"/><path d="M96.704 101.492a5.468 5.468 0 1 1-.002 10.935 5.468 5.468 0 0 1 .002-10.935" fill="#D3ECEC"/><path d="M96.704 103.043c.5 0 .977.094 1.417.265a1.598 1.598 0 0 0 .798 2.98c.605 0 1.13-.335 1.402-.831a3.915 3.915 0 1 1-3.617-2.414M0 90.162h254.327c-5.537-1.404-17.52-3.302-15.544-10.56-10.07 11.652-34.353 8.175-40.482 2.43-6.824 9.898-46.554 6.135-49.325-1.576-8.556 10.041-35.067 10.041-43.623 0-2.773 7.711-42.502 11.474-49.327 1.575-6.128 5.746-30.41 9.223-40.48-2.428C17.522 86.86 5.539 88.758 0 90.163" fill="#364548"/><path d="M111.237 140.89c-13.54-6.425-20.971-15.16-25.106-24.694-5.03 1.435-11.075 2.353-18.1 2.747-2.646.148-5.43.224-8.35.224-3.368 0-6.917-.1-10.643-.297 12.417 12.41 27.692 21.964 55.976 22.138 2.088 0 4.16-.04 6.223-.118" fill="#BDD9D7"/><path d="M91.16 124.994c-1.873-2.543-3.69-5.739-5.026-8.8-5.03 1.437-11.077 2.355-18.103 2.75 4.826 2.619 11.727 5.046 23.13 6.05" fill="#D3ECEC"/></g></svg>
\ No newline at end of file
import express from 'express';
import { Application, RequestHandler } from 'express';
import { AppInit } from './interfaces/AppInit.interface';
import { IRoute } from './interfaces/IRoute.interface';
// import { connect, disconnect } from './config/mysqlDB';
import { appDataSource } from './config/dataSource';
class App {
public app: Application;
public port: number;
constructor(appInit: AppInit) {
this.app = express();
this.port = appInit.port;
this.initAssets();
this.initMiddlewares(appInit.middlewares);
this.initRoutes(appInit.controllers);
}
private initMiddlewares(middlewares: RequestHandler[]) {
middlewares.forEach((middleware) => {
this.app.use(middleware);
});
}
private initRoutes(routes: IRoute[]) {
routes.forEach((route) => {
this.app.use(route.path, route.router);
});
}
private initAssets() {
this.app.use(express.json());
this.app.use(express.static('public'));
}
public listen() {
// connect();
appDataSource.initialize();
this.app.listen(this.port, () => {
console.log(`App listening on the http://localhost:${this.port}`);
process.on("exit", () => {
// disconnect();
appDataSource.destroy();
});
});
}
}
export default App;
import { CategoryFactory } from '@/database/factories/category.factory';
import { ProductFactory } from '@/database/factories/product.factory';
import { UserFactory } from '@/database/factories/user.factory';
import MainSeeder from '@/database/seeds/main.seeder';
import { DataSource, DataSourceOptions } from 'typeorm';
import { SeederOptions } from 'typeorm-extension';
const options: DataSourceOptions & SeederOptions = {
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: '1111',
database: 'classwork_92',
synchronize: false,
logging: true,
entities: ['src/entities/*{.ts,.js}'],
seeds: [MainSeeder],
factories: [UserFactory, ProductFactory,CategoryFactory],
}
export const appDataSource = new DataSource(options);
import path from 'path';
const rootPath = path.join(__dirname, '..', '..');
const config = {
rootPath,
uploadPath: path.join(rootPath, 'public/uploads'),
};
export default config;
import mysql, { Pool } from 'mysql2/promise';
let pool: Pool;
export function connect() {
// Create the connection pool. The pool-specific settings are the defaults
pool = mysql.createPool({
host: '77.243.81.95',
user: 'admin',
password: 'TUot/Y+C//xu3cMJeOzm/0M=',
database: 'lesson_86',
});
}
export async function disconnect() {
await pool.end();
}
export function getDb() {
return pool;
}
\ No newline at end of file
import { RequestHandler } from 'express';
import { ArticleService } from '../services/article.service';
export class ArticleController {
private service: ArticleService;
constructor() {
this.service = new ArticleService();
}
getAllArticles: RequestHandler = (req, res): void => {
const articles = this.service.getAllArticles();
res.send(articles);
};
getArticle: RequestHandler = (req, res): void => {
const article = this.service.getArticle(req.params.id);
res.send(article);
};
createArticle: RequestHandler = (req, res): void => {
const article = this.service.createArticle(req.body);
res.send(article);
};
}
import { RegisterUserDto } from "@/dto/register-user.dto";
import { SignInUserDto } from "@/dto/sign-in-user.dto";
import { formatErrors } from "@/helpers/formatErrors";
import { AuthService } from "@/services/auth.service";
import { plainToInstance } from "class-transformer";
import { validate } from "class-validator";
import { RequestHandler } from "express";
export class AuthController {
private service: AuthService;
constructor() {
this.service = new AuthService();
}
signIn: RequestHandler = async (req, res) => {
try {
const signInDto = plainToInstance(SignInUserDto, req.body);
const user = await this.service.signIn(signInDto);
return res.setHeader("Authorization", user.token || '').send(user);
} catch(e) {
return res.status(401).send((e as Error).message);
}
};
register: RequestHandler = async (req, res) => {
try {
const registerUserDto = plainToInstance(RegisterUserDto, req.body);
const errors = await validate(registerUserDto, { whitelist: true, validationError: { target: false, value: false } });
if (errors.length > 0) {
return res.status(400).send(formatErrors(errors));
}
const user = await this.service.register(registerUserDto);
return res.setHeader("Authorization", user.token || '').send(user);
} catch(e) {
if ((e as {code: string}).code === 'ER_DUP_ENTRY'){
return res.send({error: { message: 'User already exists'}});
} else {
return res.status(500).send({error: { message: 'Oops something went wrong'}});
}
}
};
secret: RequestHandler = async (req, res) => {
try {
const token = req.header('Authorization');
if (!token) {
return res.status(401).send({ error: { message: 'No token present' } });
}
const user = await this.service.getUserByToken(token);
if (!user) {
return res.status(401).send({ error: { message: 'Wrong token' } });
}
return res.send({ message: `some secret message` });
} catch (e) {
return res.status(500).send({ error: { message: 'Internal server error'+`${e ? JSON.stringify(e): ''}` } });
}
};
logout: RequestHandler = async (req, res) => {
const token = req.header('Authorization');
if (!token) {
return res.send({ message: 'success' });
}
try {
await this.service.logout(token);
} catch(e) {
console.log(e);
return res.status(500).send({ error: { message: 'Internal server error' } })
}
return res.send({ message: 'Success' })
}
}
\ No newline at end of file
import { plainToInstance } from "class-transformer";
import { RequestHandler } from "express";
import { CategoryDto } from "@/dto/category.dto";
import { CategoryService } from "@/services/category.service";
export class CategoryController {
private service: CategoryService;
constructor() {
this.service = new CategoryService();
}
getCategories: RequestHandler = async (_, res): Promise<void> => {
const categories = await this.service.getCategories();
res.send(categories);
};
createCategory: RequestHandler = async (req, res): Promise<void> => {
const categoryDto = plainToInstance(CategoryDto, req.body);
const category = await this.service.createCategory(categoryDto);
res.send(category);
};
}
\ No newline at end of file
import { ProductService } from '@/services/product.service';
import { RequestHandler } from 'express';
import { plainToInstance } from 'class-transformer';
import { ProductDto } from '@/dto/product.dto';
import { AuthService } from '@/services/auth.service';
export class ProductController {
private service: ProductService;
private authService: AuthService;
constructor() {
this.service = new ProductService();
this.authService = new AuthService();
}
getAllProducts: RequestHandler = async (req, res) => {
const products = await this.service.getAllProducts();
return res.send(products);
};
getProduct: RequestHandler = async (req, res): Promise<void> => {
try {
const product = await this.service.getProduct(parseInt(req.params.id, 10));
res.send(product);
} catch(e) {
res.status(400).send({ message: 'Product not found', detailedMessage: (e as Error)?.message});
}
};
createProduct: RequestHandler = async (req, res) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).send({ error: { message: 'No token present' } });
}
const user = await this.authService.getUserByToken(token);
if (!user) {
return res.status(401).send({ error: { message: 'Wrong token' } });
}
try {
const productDto = plainToInstance(ProductDto, req.body);
if (req.file) {
productDto.image = req.file.filename;
}
const product = await this.service.createProduct(productDto, user.id);
return res.send(product);
} catch(e) {
if (Array.isArray(e)) {
console.log(e);
return res.status(400).send(e);
} else {
return res.status(500).send(e);
}
}
};
}
import { Category } from "@/entities/category.entity";
import { Faker } from "@faker-js/faker";
import { setSeederFactory } from "typeorm-extension";
export const CategoryFactory = setSeederFactory(Category, (faker: Faker)=>{
const category = new Category()
category.title = faker.commerce.department();
category.description = faker.lorem.sentence();
return category;
})
\ No newline at end of file
import { Product } from "@/entities/product.entity";
import { Faker } from "@faker-js/faker";
import { setSeederFactory } from "typeorm-extension";
export const ProductFactory = setSeederFactory(Product, (faker: Faker)=>{
const product = new Product();
product.title = faker.commerce.productName();
product.price = faker.number.int({ min: 100, max: 2000 });
product.description = faker.lorem.sentence();
product.image = faker.image.url();
return product;
})
\ No newline at end of file
import { RegisterUserDto } from "@/dto/register-user.dto";
import { User } from "@/entities/user.entity";
import { UserRepository } from "@/repositories/user.repository";
import { Faker } from "@faker-js/faker";
import { setSeederFactory } from "typeorm-extension";
export const UserFactory = setSeederFactory(User, (faker: Faker)=>{
const userRepository = new UserRepository();
const registerUserDto: RegisterUserDto = {
username: faker.internet.userName(),
displayName: faker.person.firstName(),
password: 'password'
};
const user = userRepository.register(registerUserDto);
return user
});
import { appDataSource } from "@/config/dataSource";
import { runSeeders } from "typeorm-extension";
appDataSource.initialize().then(async()=>{
await appDataSource.synchronize(true)
await runSeeders(appDataSource)
process.exit()
})
\ No newline at end of file
import { Category } from "@/entities/category.entity";
import { Product } from "@/entities/product.entity";
import { User } from "@/entities/user.entity";
import { faker } from "@faker-js/faker";
import { DataSource } from "typeorm";
import { Seeder, SeederFactoryManager } from "typeorm-extension";
export default class MainSeeder implements Seeder {
async run(dataSource: DataSource, factoryManager: SeederFactoryManager): Promise<void> {
const userFactory = factoryManager.get(User)
const productFactory = factoryManager.get(Product)
const categoryFactory = factoryManager.get(Category);
await userFactory.saveMany(10);
const categories = await categoryFactory.saveMany(3);
await productFactory.saveMany(4, { category: faker.helpers.arrayElement(categories) });
await productFactory.saveMany(4, { category: faker.helpers.arrayElement(categories) });
await productFactory.saveMany(4, { category: faker.helpers.arrayElement(categories) });
}
}
\ No newline at end of file
import { Seeder, SeederFactoryManager } from "typeorm-extension";
import { DataSource } from "typeorm";
import { User } from "@/entities/user.entity";
export default class UserSeeder implements Seeder {
async run(dataSource: DataSource, factoryManager: SeederFactoryManager): Promise<void> {
const userFactory = factoryManager.get(User);
await userFactory.saveMany(10);
}
}
\ No newline at end of file
import { Expose } from "class-transformer";
export class CategoryDto {
@Expose() title!: string;
@Expose() description?: string;
}
\ No newline at end of file
import { Expose } from 'class-transformer';
import { IsNotEmpty, IsOptional, IsString, IsNumberString } from 'class-validator';
export class ProductDto {
@IsNotEmpty({message: "Продукт не может быть создан без названия"})
@IsString({message: "Название должно быть строкой"})
@Expose()
title!: string;
@IsOptional()
@Expose()
description?: string;
@IsNotEmpty({message: "Укажите цену продукта"})
@IsNumberString({}, {message: "Укажите корректную цену"})
@Expose()
price!: number;
@IsOptional()
@Expose()
image?: string;
@IsNotEmpty({message: "Не указана категория товара"})
@IsNumberString({}, {message: "Укажите корректную категорию"})
@Expose()
categoryId!: number;
}
import { Expose } from "class-transformer";
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
export class RegisterUserDto {
@Expose()
@IsString({message: "Пароль должен быть строкой"})
@IsNotEmpty({message: "Укажите пароль"})
password!: string;
@Expose()
@IsString({message: "Имя пользователя должно быть строкой"})
@IsNotEmpty({message: "Укажите имя пользователя"})
username!: string;
@Expose()
@IsString({message: "Псевдоним должен быть строкой"})
@IsOptional()
displayName?: string;
}
\ No newline at end of file
import { Expose } from "class-transformer";
import { IsNotEmpty, IsString } from "class-validator";
export class SignInUserDto {
@Expose()
@IsString({message: "Пароль должен быть строкой"})
@IsNotEmpty({message: "Укажите пароль"})
password!: string;
@Expose()
@IsString({message: "Имя пользователя должно быть строкой"})
@IsNotEmpty({message: "Укажите имя пользователя"})
username!: string;
}
\ No newline at end of file
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity({ name: "categories" })
export class Category {
@PrimaryGeneratedColumn()
id!: number;
@Column()
title!: string;
@Column({ nullable: true})
description?: string;
}
\ No newline at end of file
import { Entity, PrimaryGeneratedColumn, Column, JoinColumn, ManyToOne } from "typeorm";
import { Category } from "./category.entity";
import { User } from "./user.entity";
@Entity()
export class Product {
@PrimaryGeneratedColumn()
id!: number;
@Column()
title!: string;
@Column()
price!: number;
@Column({ nullable: true })
description?: string;
@Column({ nullable: true })
image?: string;
@Column({ nullable: true })
userId?: number;
@Column()
categoryId!: number;
@ManyToOne(() => Category)
@JoinColumn({ name: "categoryId"})
category!: Category;
@ManyToOne(() => User)
@JoinColumn({ name: "userId"})
user!: User;
}
\ No newline at end of file
import bcrypt from "bcrypt";
import { Column, Entity, PrimaryGeneratedColumn, Unique } from "typeorm";
@Entity('users')
@Unique(['username'])
export class User {
@PrimaryGeneratedColumn()
id!: number;
@Column()
username!: string;
@Column({ nullable: true })
displayName?: string;
@Column()
password!: string;
@Column({nullable: true})
token?: string;
public async comparePassword(password: string): Promise<boolean> {
return await bcrypt.compare(password, this.password);
}
public generateToken() {
this.token = crypto.randomUUID();
}
}
\ No newline at end of file
import { ValidationError } from "class-validator";
export interface IUpdatedError {
type: string;
message: string[];
}
export function formatErrors(errors: ValidationError[]) {
const updatedErrors: IUpdatedError[] = [];
errors.forEach(error => {
if(error.constraints) {
const updatedError: IUpdatedError = {
type: error.property,
message: Object.values(error.constraints),
};
updatedErrors.push(updatedError);
}
});
return updatedErrors;
}
\ No newline at end of file
import cors from 'cors';
import App from './app';
import logger from './middlewares/logger';
import { ArticleRoute } from './routes/article.route';
import { ProductRoute } from './routes/product.route';
import { CategoryRoute } from './routes/category.route';
import { AuthRoute } from './routes/auth.route';
const app = new App({
port: 8000,
middlewares: [logger(), cors({
exposedHeaders: 'Authorization',
})],
controllers: [
new ArticleRoute(),
new ProductRoute(),
new CategoryRoute(),
new AuthRoute()
],
});
app.listen();
import { RequestHandler } from 'express';
import { IRoute } from './IRoute.interface';
export interface AppInit {
port: number;
middlewares: RequestHandler[];
controllers: IRoute[];
}
export interface IArticle {
id: string;
title: string;
description: string;
}
export interface ICategory {
id: number;
title: string;
description?: string;
}
\ No newline at end of file
export interface IProduct {
id: string;
title: string;
description: string;
price: number;
image?: string;
}
import { Router } from 'express';
export interface IRoute {
path: string;
router: Router;
}
export interface IUser {
id: number;
username: string;
displayName?: string;
password?: string;
token?: string;
}
\ No newline at end of file
import { RequestHandler } from 'express';
const logger = (): RequestHandler => (req, res, next) => {
console.log(`Request logged: ${req.method}, ${req.path}`);
next();
};
export default logger;
import config from '@/config';
import { randomUUID } from 'crypto';
import multer from 'multer';
import path from 'path';
const storage = multer.diskStorage({
destination: (_, __, callback) => {
callback(null, config.uploadPath);
},
filename: (_, file, callback) => {
callback(null, randomUUID() + path.extname(file.originalname));
},
});
export const upload = multer({ storage });
import { Repository } from "typeorm";
import { appDataSource } from "@/config/dataSource";
import { Category } from "@/entities/category.entity";
import { CategoryDto } from "@/dto/category.dto";
export class CategoryRepository extends Repository<Category> {
constructor() {
super(Category, appDataSource.createEntityManager());
}
async getCategories(): Promise<Category[]> {
return await this.find();
}
async createCategory(categoryDto: CategoryDto) {
const category = new Category();
category.title = categoryDto.title;
category.description = categoryDto.description;
await this.save(category);
return category;
}
}
\ No newline at end of file
import { appDataSource } from "@/config/dataSource";
// import { getDb } from "@/config/mysqlDB";
import { ProductDto } from "@/dto/product.dto";
import { Product } from "@/entities/product.entity";
// import { IProduct } from "@/interfaces/IProduct.interface";
// import { ResultSetHeader } from "mysql2";
import { Repository } from "typeorm";
// interface IProductData extends ResultSetHeader, IProduct {}
export class ProductRepository extends Repository<Product> {
constructor() {
super(Product, appDataSource.createEntityManager());
}
async getProducts(): Promise<Product[]> {
return await this.find({ relations: { category: true, user: true }});
}
async getProduct(id: number) {
return await this.findOne({ where:{ id }, relations: { category: true } });
}
async createProduct(productDto: ProductDto, userId: number) {
return await this.save({...productDto, userId });
}
}
\ No newline at end of file
import bcrypt from "bcrypt";
import { Repository } from "typeorm";
import { User } from "@/entities/user.entity";
import { appDataSource } from "@/config/dataSource";
import { SignInUserDto } from "@/dto/sign-in-user.dto";
import { RegisterUserDto } from "@/dto/register-user.dto";
import { IUser } from "@/interfaces/IUser.interface";
import _ from "lodash";
export class UserRepository extends Repository<User> {
constructor() {
super(User, appDataSource.createEntityManager());
}
async signIn(signInUserDto: SignInUserDto): Promise<IUser> {
const user = await this.findOne({
where: {username: signInUserDto.username}
});
if (!user) {
throw new Error('Invalid username or password');
}
const isMatch = await user.comparePassword(signInUserDto.password);
if (!isMatch) {
throw new Error('Invalid username or password');
}
user.generateToken();
const userWithToken: IUser = await this.save(user);
const userWithoutPassword = _.omit(userWithToken, "password");
return userWithoutPassword;
}
async register(registerUserDto: RegisterUserDto): Promise<IUser> {
const salt = await bcrypt.genSalt(10);
registerUserDto.password = await bcrypt.hash(registerUserDto.password, salt);
const user = await this.create(registerUserDto);
user.generateToken();
const userWithToken: IUser = await this.save(user);
const userWithoutPassword = _.omit(userWithToken, "password");
return userWithoutPassword;
}
async getUserByToken(token: string): Promise<User|null> {
return await this.findOneBy({ token });
}
async clearToken(token: string) {
const user = await this.getUserByToken(token);
if (user) {
user.generateToken()
}
}
}
\ No newline at end of file
import { Router } from 'express';
import { ArticleController } from '../controllers/article.controller';
import { IRoute } from '../interfaces/IRoute.interface';
export class ArticleRoute implements IRoute {
public path = '/articles';
public router = Router();
private controller: ArticleController;
constructor() {
this.controller = new ArticleController();
this.init();
}
private init() {
this.router.get('/', this.controller.getAllArticles);
this.router.get('/:id', this.controller.getArticle);
this.router.post('/create', this.controller.createArticle);
}
}
import { Router } from 'express';
import { IRoute } from '../interfaces/IRoute.interface';
import { AuthController } from '@/controllers/auth.controller';
export class AuthRoute implements IRoute {
public path = '/auth';
public router = Router();
private controller: AuthController;
constructor() {
this.controller = new AuthController();
this.init();
}
private init() {
this.router.post('/sign-in', this.controller.signIn);
this.router.post('/register', this.controller.register);
this.router.get('/secret', this.controller.secret);
this.router.delete('/logout', this.controller.logout)
}
}
\ No newline at end of file
import { Router } from "express";
import { CategoryController } from "@/controllers/category.controller";
import { IRoute } from "@/interfaces/IRoute.interface";
export class CategoryRoute implements IRoute {
public path = "/categories";
public router = Router();
private controller: CategoryController;
constructor() {
this.controller = new CategoryController();
this.init();
}
private init() {
this.router.get('/', this.controller.getCategories);
this.router.post('/create', this.controller.createCategory);
}
}
\ No newline at end of file
import { ProductController } from '@/controllers/product.controller';
import { IRoute } from '@/interfaces/IRoute.interface';
import { upload } from '@/middlewares/upload';
import { Router } from 'express';
export class ProductRoute implements IRoute {
public path = '/products';
public router = Router();
private controller: ProductController;
constructor() {
this.controller = new ProductController();
this.init();
}
private init() {
this.router.get('/', this.controller.getAllProducts);
this.router.get('/:id', this.controller.getProduct);
this.router.post('/create', upload.single('image'), this.controller.createProduct);
}
}
import {describe, expect, test, jest } from '@jest/globals';
import { ProductService } from '../product.service';
import { ProductDto } from '@/dto/product.dto';
import { ProductRepository } from '../../repositories/product.repository';
const productDto = new ProductDto();
productDto.categoryId = 1;
productDto.price = 1000;
productDto.title = "Lorem";
jest.mock('../../repositories/product.repository');
(ProductRepository as any).mockImplementation(() => {
return {
createProduct: jest.fn(() => productDto),
};
});
describe('product.service', () => {
const productService = new ProductService();
test('Успешное создание продукта', async () => {
const result = await productService.createProduct(productDto);
expect(result).toStrictEqual(productDto);
});
test('Ошибка при отсутствии цены', async () => {
const productDtoForError = new ProductDto();
productDtoForError.title = "Lorem";
productDtoForError.categoryId = 1;
const throwingFunction = () => productService.createProduct(productDtoForError);
await throwingFunction().catch(error => {
expect(error[0]).toMatchObject({
message: [
"Укажите корректную цену",
"Укажите цену продукта",
],
type: "price",
});
});
});
});
\ No newline at end of file
import { IArticle } from '../interfaces/IArticle.interface';
export class ArticleService {
private articles: IArticle[] = [];
getAllArticles = (): IArticle[] => {
return this.articles;
};
getArticle = (id: string): IArticle => {
const article = this.articles.find((article) => article.id === id);
if (article) return article;
else throw new Error('invalid id');
};
createArticle = (data: IArticle): IArticle => {
const newArticle = {
id: Math.random().toString(),
title: data.title,
description: data.description,
};
this.articles.push(newArticle);
return newArticle;
};
}
import { RegisterUserDto } from "@/dto/register-user.dto";
import { SignInUserDto } from "@/dto/sign-in-user.dto";
import { IUser } from "@/interfaces/IUser.interface";
import { UserRepository } from "@/repositories/user.repository";
export class AuthService{
private repository: UserRepository;
constructor() {
this.repository = new UserRepository();
}
async signIn(signInUserDto: SignInUserDto): Promise<IUser> {
return await this.repository.signIn(signInUserDto);
}
async register(registerUserDto: RegisterUserDto): Promise<IUser> {
return await this.repository.register(registerUserDto);
}
async getUserByToken (token: string): Promise<IUser | null> {
return await this.repository.getUserByToken(token);
};
async logout(token: string): Promise<void> {
await this.repository.clearToken(token)
}
}
\ No newline at end of file
import { CategoryDto } from "@/dto/category.dto";
import { CategoryRepository } from "@/repositories/category.repository";
export class CategoryService {
private repository: CategoryRepository;
constructor() {
this.repository = new CategoryRepository();
}
async getCategories() {
return await this.repository.getCategories();
}
async createCategory(categoryDto: CategoryDto) {
return await this.repository.createCategory(categoryDto);
}
}
\ No newline at end of file
import { IProduct } from '@/interfaces/IProduct.interface';
import path from 'path';
import * as fs from 'fs';
import { ProductDto } from '@/dto/product.dto';
import { ProductRepository } from '@/repositories/product.repository';
import { Product } from '@/entities/product.entity';
import { validate } from 'class-validator';
import { formatErrors } from '@/helpers/formatErrors';
const filePath = path.join(__dirname, '../../data');
export class ProductService {
private products: IProduct[] = [];
private repository: ProductRepository;
constructor() {
this.init();
this.repository = new ProductRepository();
}
init(): void {
try {
const fileContent = fs.readFileSync(`${filePath}/products.json`);
this.products = JSON.parse(fileContent.toString());
} catch (e) {
this.products = [];
}
}
save(): void {
fs.writeFileSync(`${filePath}/products.json`, JSON.stringify(this.products, null, 2));
}
getAllProducts = async (): Promise<Product[]> => {
const res = await this.repository.getProducts();
return res;
};
getProduct = async (id: number): Promise<Product> => {
const product = await this.repository.getProduct(id);
if (!product){
throw new Error('Invalid id');
}
return product;
};
createProduct = async (data: ProductDto, userId: number): Promise<Product> => {
const errors = await validate(data, {
whitelist: true,
validationError:{value: false, target: false}
});
if (errors?.length) {
throw formatErrors(errors);
}
return await this.repository.createProduct(data, userId);
};
}
Hello world
\ No newline at end of file
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"pretty": true,
"sourceMap": true,
"outDir": "dist",
"importHelpers": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"paths": {
"@/*": ["./src/*"]
},
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"resolveJsonModule": true,
"esModuleInterop": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": [
"ES2020",
"DOM",
"DOM.Iterable"
],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
},
"include": [
"src"
],
"references": [
{
"path": "./tsconfig.node.json"
}
]
}
\ No newline at end of file
This diff is collapsed.
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