Upload 5.1 and 5.2

This commit is contained in:
Andrew Trieu
2023-06-19 14:39:25 +03:00
parent 26304676f1
commit 714cc5d171
14 changed files with 29615 additions and 0 deletions

29293
part5/bloglist-frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.2.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:3001/"
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@@ -0,0 +1,123 @@
import { useState, useEffect } from "react";
import Blog from "./components/Blog";
import Notification from "./components/Notification";
import blogService from "./services/blogs";
import loginService from "./services/login";
const App = () => {
const [blogs, setBlogs] = useState([]);
const [user, setUser] = useState(null);
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [errorMessage, setErrorMessage] = useState(null);
const [successMessage, setSuccessMessage] = useState(null);
useEffect(() => {
const loggedInUserLocal = window.localStorage.getItem("loggedInUser");
if (loggedInUserLocal) {
const user = JSON.parse(loggedInUserLocal);
setUser(user);
blogService.setToken(user.token);
}
}, []);
const handleLogin = async (event) => {
event.preventDefault();
try {
const user = await loginService.login({ username, password });
window.localStorage.setItem("loggedInUser", JSON.stringify(user));
setUser(user);
setUsername("");
setPassword("");
setSuccessMessage("Login successful");
setTimeout(() => {
setSuccessMessage(null);
}, 5000);
} catch (exception) {
setErrorMessage("Wrong credentials");
setTimeout(() => {
setErrorMessage(null);
}, 5000);
}
};
const handleLogout = async (event) => {
event.preventDefault()
try {
setSuccessMessage('Logout successful')
setTimeout(() => {
setSuccessMessage(null);
}, 5000);
window.localStorage.clear()
blogService.setToken(null)
setUser(null)
setUsername('')
setPassword('')
} catch (exception) {
setErrorMessage('Logout failed. Please try again later.')
setTimeout(() => {
setErrorMessage(null);
}, 5000);
}
}
const loginForm = () => (
<form onSubmit={handleLogin}>
<div>
username
<input
type="text"
value={username}
name="Username"
onChange={({ target }) => setUsername(target.value)}
/>
</div>
<div>
password
<input
type="password"
value={password}
name="Password"
onChange={({ target }) => setPassword(target.value)}
/>
</div>
<button type="submit">login</button>
</form>
);
const blogForm = () => (
<div>
<h2> All blogs</h2>
{blogs.map((blog) => (
<Blog key={blog.id} blog={blog} />
))}
</div>
);
return (
<div>
<h1>Bloglist</h1>
<Notification
errorMessage={errorMessage}
successMessage={successMessage}
/>
{user === null ? (
<div>
<p> Please log in </p>
{loginForm()}
</div>
) : (
<div>
<p> {user.name} logged in </p>
<button onClick={handleLogout}>Logout</button>
{blogForm()}
</div>
)}
</div>
);
};
export default App;

View File

@@ -0,0 +1,7 @@
const Blog = ({blog}) => (
<div>
{blog.title} {blog.author}
</div>
)
export default Blog

View File

@@ -0,0 +1,26 @@
const errorNotification = ({ message }) => {
if (message === null) {
return null;
} else {
return <div style={{ color: "red" }}>{message}</div>;
}
};
const successNotification = ({ message }) => {
if (message === null) {
return null;
} else {
return <div style={{ color: "green" }}>{message}</div>;
}
};
const Notification = ({ errorMessage, successMessage }) => {
return (
<div>
{errorNotification({ message: errorMessage })}
{successNotification({ message: successMessage })}
</div>
);
};
export default Notification;

View File

@@ -0,0 +1,5 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
ReactDOM.createRoot(document.getElementById('root')).render(<App />)

View File

@@ -0,0 +1,38 @@
import axios from "axios";
const baseUrl = "/api/blogs";
let token = null;
const setToken = (newToken) => {
token = `bearer ${newToken}`;
};
const getAll = async () => {
const request = axios.get(baseUrl);
const response = await request;
return response.data;
};
const create = async (newObject) => {
const config = {
headers: { Authorization: token },
};
const response = await axios.post(baseUrl, newObject, config);
return response.data;
};
const update = async (id, newObject) => {
const request = axios.put(`${baseUrl} /${id}`, newObject);
const response = await request;
return response.data;
};
const blogService = {
setToken,
getAll,
create,
update,
};
export default blogService;

View File

@@ -0,0 +1,12 @@
import axios from "axios";
const baseUrl = "/api/login";
const login = async (credentials) => {
const response = await axios.post(baseUrl, credentials);
console.log(response.data);
return response.data;
};
const loginService = { login };
export default loginService;