react-posts

This commit is contained in:
Sergey Yarkov 2020-06-17 20:32:48 +03:00
commit 582bf83be1
25 changed files with 27336 additions and 0 deletions

23
client/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

68
client/README.md Normal file
View File

@ -0,0 +1,68 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `yarn build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

14092
client/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

37
client/package.json Normal file
View File

@ -0,0 +1,37 @@
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"apollo-boost": "^0.4.9",
"graphql": "^15.1.0",
"react": "^16.13.1",
"react-apollo": "^3.1.5",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

BIN
client/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

18
client/public/index.html Normal file
View File

@ -0,0 +1,18 @@
<!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"
/>
<title>React Posts</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

3
client/public/robots.txt Normal file
View File

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

17
client/src/App.js Normal file
View File

@ -0,0 +1,17 @@
import React from 'react';
import client from './apolloClient'
import { ApolloProvider } from 'react-apollo'
import Layout from './components/Layout/Layout';
import PostContainer from './components/containers/PostContainer/PostContainer'
const App = () => {
return (
<ApolloProvider client={client}>
<Layout>
<PostContainer />
</Layout>
</ApolloProvider>
)
}
export default App

View File

@ -0,0 +1,13 @@
import gql from 'graphql-tag'
const ADD_POST = gql`
mutation($title: String! $description: String!) {
addPost(title: $title description: $description) {
id
title
description
}
}
`
export default ADD_POST

View File

@ -0,0 +1,13 @@
import gql from 'graphql-tag'
const DEL_POST = gql`
mutation($id: ID!) {
delPost(id: $id) {
id
title
description
}
}
`
export default DEL_POST

View File

@ -0,0 +1,13 @@
import gql from 'graphql-tag'
const GET_POSTS = gql`
query getPosts {
posts {
id
title
description
}
}
`
export default GET_POSTS

View File

@ -0,0 +1,7 @@
import ApolloClient from 'apollo-boost'
const client = new ApolloClient({
uri: 'http://localhost:3001'
})
export default client

View File

@ -0,0 +1,12 @@
import React from 'react';
const Layout = ({ children }) => {
return (
<main>
{children}
</main>
)
}
export default Layout

View File

@ -0,0 +1,51 @@
import React from 'react';
import { useMutation } from '@apollo/react-hooks'
import classes from './Posts.module.css'
import GET_POSTS from '../../apollo/queries/posts'
import DEL_POST from '../../apollo/mutations/delPost'
const Posts = ({ data }) => {
const [isError, setIsError] = React.useState({ status: false, error: null })
const [delPost] = useMutation(DEL_POST, {
update(cache, { data: { delPost } }) {
const { posts } = cache.readQuery({ query: GET_POSTS })
cache.writeQuery({
query: GET_POSTS,
data: { posts: posts.filter(post => post.id !== delPost.id) }
})
}
})
const btnHandlerDel = id => {
delPost({ variables: { id } }).catch(error => {
console.log(error)
setIsError({ status: true, error })
})
}
if (data.length <= 0) return "No posts..."
return (
<>
{isError.status
? <div>{`${isError.error }`}</div>
: null}
{data.map((post, i) => {
return (
<div className={classes.Post} key={i}>
<div>
<h2>{post.title}</h2>
<p>{post.description}</p>
</div>
<div className={classes.actions}>
<svg onClick={() => btnHandlerDel(post.id)} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="black" width="24px" height="24px"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M16 9v10H8V9h8m-1.5-6h-5l-1 1H5v2h14V4h-3.5l-1-1zM18 7H6v12c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7z"/></svg>
</div>
</div>
)
})}
</>
)
}
export default Posts

View File

@ -0,0 +1,13 @@
.error {
margin: 10px 0;
}
.Post {
display: flex;
justify-content: space-between;
align-items: center;
}
.actions > svg {
cursor: pointer;
}

View File

@ -0,0 +1,65 @@
import React from 'react';
import { Query } from 'react-apollo'
import { useMutation } from '@apollo/react-hooks'
import Posts from '../../Posts/Posts'
import classes from './PostContainer.module.css'
import GET_POSTS from '../../../apollo/queries/posts'
import ADD_POST from '../../../apollo/mutations/addPost'
const PostContainer = () => {
const [addPost] = useMutation(ADD_POST, {
update(cache, { data: { addPost } }) {
const { posts } = cache.readQuery({ query: GET_POSTS })
cache.writeQuery({
query: GET_POSTS,
data: { posts: posts.concat([addPost]) }
})
}
})
const formHandlerAdd = e => {
try {
e.preventDefault()
const target = e.target
addPost({variables: {
title: target.elements.title.value,
description: target.elements.description.value
}})
target.elements.title.value = ''
target.elements.description.value = ''
} catch (error) {
console.log(error)
}
}
return (
<div className={classes.PostContainer}>
<h1 className={classes.heading}><span role='img' aria-label='react'>⚛️</span> React Posts</h1>
<form onSubmit={formHandlerAdd} className={classes.form}>
<div className={classes.formInputs}>
<input placeholder='title' name='title' type="text"/>
<input placeholder='description...' name='description' type="text" />
</div>
<div>
<button className={classes.formButton} type='submit'>Add Post</button>
</div>
</form>
<div className={classes.posts}>
<Query query={GET_POSTS }>
{({ loading, error, data }) => {
if (loading) return 'Loading...'
if (error) return `Error: ${error}`
return <Posts data={data.posts} />
}}
</Query>
</div>
</div>
)
}
export default PostContainer

View File

@ -0,0 +1,64 @@
.PostContainer {
margin-top: 3rem;
}
.heading {
text-align: center;
margin-bottom: 30px;
}
.form {
margin-bottom: 30px;
display: flex;
justify-content: center;
flex-wrap: wrap;
}
.formInputs {
display: flex;
justify-content: center;
flex-wrap: wrap;
}
.formInputs > input {
margin-top: 10px;
margin-right: 5px;
padding: 12px;
border-radius: 3px;
line-height: 1;
font-family: 'Inter', sans-serif;
border: 2px solid #ccc;
font-weight: 500;
outline: none;
width: 200px;
}
.formButton {
margin-top: 10px;
padding: 12px 45px;
height: 44px;
border: none;
background: #608bf1;
color: #fff;
font-size: 14px;
font-weight: bold;
border-radius: 3px;
cursor: pointer;
transition: all 0.1s;
}
.formButton:hover {
background: hsl(222, 74%, 71%);
}
.posts > div {
border: 1px solid transparent;
border-bottom-color: #ebebeb;
transition: all 0.1s;
margin-bottom: 2px;
padding: 10px 15px;
}
.posts > div:hover {
background: #fafafa;
}

34
client/src/index.css Normal file
View File

@ -0,0 +1,34 @@
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500&display=swap');
* {
box-sizing: border-box;
}
body {
margin: 0;
max-width: 900px;
margin-left: auto;
margin-right: auto;
font-family: 'Inter', sans-serif;
}
input {
padding: 0;
}
h1,h2,h3,h4,h5,h6 {
font-weight: bold;
padding: 0;
margin: 10px;
}
p,a {
font-weight: 400;
padding: 0;
margin: 10px;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

7
client/src/index.js Normal file
View File

@ -0,0 +1,7 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(<App />,document.getElementById('root'));

11339
client/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

1
server/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
node_modules

7
server/db/posts.js Normal file
View File

@ -0,0 +1,7 @@
const posts = [
{ id: "1592407903966", title: "Post 1", description: "Description 1" },
{ id: "1592407904271", title: "Post 2", description: "Description 2" },
{ id: "1592407904419", title: "Post 3", description: "Description 3" }
]
module.exports = posts

1367
server/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

18
server/package.json Normal file
View File

@ -0,0 +1,18 @@
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"dependencies": {
"apollo-server": "^2.14.5",
"graphql": "^15.1.0"
},
"devDependencies": {},
"scripts": {
"dev": "nodemon server.js",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}

54
server/server.js Normal file
View File

@ -0,0 +1,54 @@
const { ApolloServer } = require('apollo-server')
const { gql } = require('apollo-server')
const posts = require('./db/posts')
const startServer = ({ port }) => {
const typeDefs = gql`
type Query {
posts: [Post]
}
type Mutation {
addPost(title: String! description: String!): Post
delPost(id: ID!): Post
}
type Post {
id: ID
title: String
description: String
}
`
const resolvers = {
Query: {
posts: () => posts
},
Mutation: {
addPost: (_, { title, description }) => {
const newPost = { id: Date.now().toString(), title, description }
posts.push(newPost)
return newPost
},
delPost: (_, { id }) => {
const index = posts.findIndex(post => post.id === id)
const deletedPost = posts[index]
if (index > -1) {
posts.splice(index, 1)
return deletedPost
} else {
throw new Error('Post not found')
}
}
}
}
const server = new ApolloServer({ typeDefs, resolvers })
server.listen(port, () => console.log(`Apollo server is running on port: ${port}`))
}
startServer({ port: 3001 })