2 Commits
main ... demo

Author SHA1 Message Date
Riccardo
a40d04d138 Done 2021-08-29 10:35:05 +02:00
Riccardo
7939d15537 Fixes 2021-08-16 22:13:26 +02:00
23 changed files with 2202 additions and 2905 deletions

View File

@@ -1,6 +1,6 @@
{ {
"name": "client", "name": "client",
"version": "1.0.0", "version": "0.1.0",
"private": true, "private": true,
"dependencies": { "dependencies": {
"@apollo/client": "^3.3.6", "@apollo/client": "^3.3.6",

View File

@@ -1,13 +1,10 @@
// import logo from './../logo.svg'; import React from 'react';
// import './../styles/App.css';
import React, { Component } from 'react';
import LinkList from './LinkList'; import LinkList from './LinkList';
import CreateLink from './CreateLink' import CreateLink from './CreateLink'
import Header from './Header'; import Header from './Header';
import Login from './Login' import Login from './Login'
import Search from './Search'; import Search from './Search';
import { Redirect, Route, Switch } from 'react-router-dom'; import { Route, Switch } from 'react-router-dom';
const App = () => { const App = () => {
return ( return (
@@ -34,31 +31,4 @@ const App = () => {
); );
}; };
// class App extends Component {
// render() {
// return <CreateLink />;
// }
// }
// function App() {
// return (
// <div className="App">
// <header className="App-header">
// <img src={logo} className="App-logo" alt="logo" />
// <p>
// Edit <code>src/App.js</code> and save to reload.
// </p>
// <a
// className="App-link"
// href="https://reactjs.org"
// target="_blank"
// rel="noopener noreferrer"
// >
// Learn React
// </a>
// </header>
// </div>
// );
// }
export default App; export default App;

View File

@@ -1,8 +0,0 @@
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

View File

@@ -1,8 +1,8 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { useHistory } from 'react-router'; import { useHistory } from 'react-router';
import { useMutation, gql } from '@apollo/client'; import { useMutation, gql } from '@apollo/client';
import { LINKS_PER_PAGE } from '../constants'; // import { LINKS_PER_PAGE } from '../constants';
import { FEED_QUERY } from './LinkList'; // import { FEED_QUERY } from './LinkList';
const CREATE_LINK_MUTATION = gql` const CREATE_LINK_MUTATION = gql`
mutation PostMutation( mutation PostMutation(
@@ -31,34 +31,34 @@ const CreateLink = () => {
description: formState.description, description: formState.description,
url: formState.url url: formState.url
}, },
update: (cache, { data: { post } }) => { // update: (cache, { data: { post } }) => {
const take = LINKS_PER_PAGE; // const take = LINKS_PER_PAGE;
const skip = 0; // const skip = 0;
const orderBy = { createdAt: 'desc' }; // const orderBy = { createdAt: 'desc' };
const data = cache.readQuery({ // const { data } = cache.readQuery({
query: FEED_QUERY, // query: FEED_QUERY,
variables: { // variables: {
take, // take,
skip, // skip,
orderBy // orderBy
} // }
}); // });
cache.writeQuery({ // cache.writeQuery({
query: FEED_QUERY, // query: FEED_QUERY,
data: { // data: {
feed: { // feed: {
links: [post, ...data.feed.links] // links: [post, ...data.feed.links]
} // }
}, // },
variables: { // variables: {
take, // take,
skip, // skip,
orderBy // orderBy
} // }
}); // });
}, // },
onCompleted: () => history.push('/new/1') onCompleted: () => history.push('/new/1')
}); });

View File

@@ -9,79 +9,34 @@ const Header = () => {
return ( return (
<div className="flex pa1 justify-between nowrap orange"> <div className="flex pa1 justify-between nowrap orange">
<div className="flex flex-fixed black"> <div className="flex flex-fixed black">
<div className="fw7 mr1">Hacker News</div> <div className="fw7 mr1">News</div>
<Link to="/" className="ml1 no-underline black"> <Link to="/" className="ml1 no-underline black">Top</Link>
new
</Link>
<div className="ml1">|</div> <div className="ml1">|</div>
<Link to="/top" className="ml1 no-underline black"> <Link to="/new/1" className="ml1 no-underline black">New</Link>
top
</Link>
<div className="ml1">|</div> <div className="ml1">|</div>
<Link to="/search" className="ml1 no-underline black"> <Link to="/search" className="ml1 no-underline black">Search</Link>
search
</Link>
{authToken && ( {authToken && (
<div className="flex"> <div className="flex">
<div className="ml1">|</div> <div className="ml1">|</div>
<Link <Link to="/create" className="ml1 no-underline black">Create</Link>
to="/create"
className="ml1 no-underline black"
>
submit
</Link>
</div> </div>
)} )}
</div> </div>
<div className="flex flex-fixed"> <div className="flex flex-fixed">
{authToken ? ( {authToken ? (
<div <div className="ml1 pointer black" onClick={() => {
className="ml1 pointer black"
onClick={() => {
localStorage.removeItem(AUTH_TOKEN); localStorage.removeItem(AUTH_TOKEN);
history.push(`/`); history.push(`/`);
}} }}
> >
logout Logout
</div> </div>
) : ( ) : (
<Link <Link to="/login" className="ml1 no-underline black">Login</Link>
to="/login"
className="ml1 no-underline black"
>
login
</Link>
)} )}
</div> </div>
</div> </div>
); );
}; };
export default Header; export default Header;
// import React from 'react';
// import { useHistory } from 'react-router';
// import { Link, withRouter } from 'react-router-dom';
// const Header = () => {
// const history = useHistory();
// return (
// <div className="flex pa1 justify-between nowrap orange">
// <div className="flex flex-fixed black">
// <div className="fw7 mr1">Hacker News</div>
// <Link to="/" className="ml1 no-underline black">
// new
// </Link>
// <div className="ml1">|</div>
// <Link
// to="/create"
// className="ml1 no-underline black"
// >
// submit
// </Link>
// </div>
// </div>
// );
// };
// export default Header;

View File

@@ -1,8 +1,8 @@
import React from 'react'; import React from 'react';
import { useMutation, gql } from '@apollo/client'; import { useMutation, gql } from '@apollo/client';
import { AUTH_TOKEN, LINKS_PER_PAGE } from '../constants'; import { AUTH_TOKEN } from '../constants';
import { timeDifferenceForDate } from '../utils' import { timeDifferenceForDate } from '../utils'
import { FEED_QUERY } from './LinkList' // import { FEED_QUERY } from './LinkList'
const VOTE_MUTATION = gql` const VOTE_MUTATION = gql`
mutation VoteMutation($linkId: ID!) { mutation VoteMutation($linkId: ID!) {
@@ -24,45 +24,38 @@ const VOTE_MUTATION = gql`
} }
`; `;
const take = LINKS_PER_PAGE;
const skip = 0;
const orderBy = { createdAt: 'desc' };
const Link = (props) => { const Link = (props) => {
const { link } = props; const { link } = props;
const authToken = localStorage.getItem(AUTH_TOKEN); const authToken = localStorage.getItem(AUTH_TOKEN);
const take = LINKS_PER_PAGE;
const skip = 0;
const orderBy = { createdAt: 'desc' };
const [vote] = useMutation(VOTE_MUTATION, { const [vote] = useMutation(VOTE_MUTATION, {
variables: { variables: {
linkId: link.id linkId: link.id
}, },
update(cache, { data: { vote } }) { // update(cache, { data: { vote } }) {
const { feed } = cache.readQuery({ // const { feed } = cache.readQuery({
query: FEED_QUERY // query: FEED_QUERY
}); // });
const updatedLinks = feed.links.map((feedLink) => { // const updatedLinks = feed.links.map((feedLink) => {
if (feedLink.id === link.id) { // if (feedLink.id === link.id) {
return { // return {
...feedLink, // ...feedLink,
votes: [...feedLink.votes, vote] // votes: [...feedLink.votes, vote]
}; // };
} // }
return feedLink; // return feedLink;
}); // });
cache.writeQuery({ // cache.writeQuery({
query: FEED_QUERY, // query: FEED_QUERY,
data: { // data: {
feed: { // feed: {
links: updatedLinks // links: updatedLinks
} // }
} // }
}); // });
} // }
}); });
return ( return (
@@ -70,22 +63,16 @@ const Link = (props) => {
<div className="flex items-center"> <div className="flex items-center">
<span className="gray">{props.index + 1}.</span> <span className="gray">{props.index + 1}.</span>
{authToken && ( {authToken && (
<div <div className="ml1 gray f11" style={{ cursor: 'pointer' }} onClick={vote}></div>
className="ml1 gray f11"
style={{ cursor: 'pointer' }}
onClick={vote}
>
</div>
)} )}
</div> </div>
<div className="ml1"> <div className="ml1">
<div> <div>
{link.description} ({link.url}) {link.description} ({link.url})
</div> </div>
{authToken && ( {authToken && (
<div className="f6 lh-copy gray"> <div className="f6 lh-copy gray">
{link.votes.length} votes | by{' '} {link.votes.length} votes, submitted by{' '}
{link.postedBy ? link.postedBy.name : 'Unknown'}{' '} {link.postedBy ? link.postedBy.name : 'Unknown'}{' '}
{timeDifferenceForDate(link.createdAt)} {timeDifferenceForDate(link.createdAt)}
</div> </div>
@@ -95,15 +82,4 @@ const Link = (props) => {
); );
}; };
// const Link = (props) => {
// const { link } = props;
// return (
// <div>
// <div>
// {link.id} - {link.description} ({link.url})
// </div>
// </div>
// );
// };
export default Link; export default Link;

View File

@@ -11,7 +11,6 @@ export const FEED_QUERY = gql`
$orderBy: LinkOrderByInput $orderBy: LinkOrderByInput
) { ) {
feed(take: $take, skip: $skip, orderBy: $orderBy) { feed(take: $take, skip: $skip, orderBy: $orderBy) {
id
links { links {
id id
createdAt createdAt
@@ -76,8 +75,6 @@ const LinkList = () => {
pageIndexParams[pageIndexParams.length - 1] pageIndexParams[pageIndexParams.length - 1]
); );
console.log(pageIndexParams.length, page);
const pageIndex = page ? (page - 1) * LINKS_PER_PAGE : 0; const pageIndex = page ? (page - 1) * LINKS_PER_PAGE : 0;
const { const {
@@ -89,8 +86,6 @@ const LinkList = () => {
variables: getQueryVariables(isNewPage, page) variables: getQueryVariables(isNewPage, page)
}); });
// const { data } = useQuery(FEED_QUERY);
const getLinksToRender = (isNewPage, data) => { const getLinksToRender = (isNewPage, data) => {
if (isNewPage) { if (isNewPage) {
return data.feed.links; return data.feed.links;
@@ -171,28 +166,4 @@ const LinkList = () => {
); );
}; };
// const LinkList = () => {
// const linksToRender = [
// {
// id: '1',
// description:
// 'Link first😎',
// url: 'https://prisma.io'
// },
// {
// id: '2',
// description: 'Link zwei',
// url: 'https://www.apollographql.com/docs/react/'
// }
// ];
//
// return (
// <div>
// {linksToRender.map((link) => (
// <Link key={link.id} link={link} />
// ))}
// </div>
// );
// };
export default LinkList; export default LinkList;

View File

@@ -1,5 +1,4 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { useMutation } from '@apollo/client';
import { useLazyQuery } from '@apollo/client'; import { useLazyQuery } from '@apollo/client';
import gql from 'graphql-tag'; import gql from 'graphql-tag';
import Link from './Link'; import Link from './Link';
@@ -7,7 +6,6 @@ import Link from './Link';
const FEED_SEARCH_QUERY = gql` const FEED_SEARCH_QUERY = gql`
query FeedSearchQuery($filter: String!) { query FeedSearchQuery($filter: String!) {
feed(filter: $filter) { feed(filter: $filter) {
id
links { links {
id id
url url

View File

@@ -1,2 +1,2 @@
export const AUTH_TOKEN = 'auth-token'; export const AUTH_TOKEN = 'auth-token';
export const LINKS_PER_PAGE = 3; export const LINKS_PER_PAGE = 5;

View File

@@ -2,28 +2,15 @@ import React from 'react';
import { BrowserRouter } from 'react-router-dom'; import { BrowserRouter } from 'react-router-dom';
import { setContext } from '@apollo/client/link/context'; import { setContext } from '@apollo/client/link/context';
import { AUTH_TOKEN } from './constants'; import { AUTH_TOKEN } from './constants';
import { split } from '@apollo/client'; import { split } from '@apollo/client';
import { WebSocketLink } from '@apollo/client/link/ws'; import { WebSocketLink } from '@apollo/client/link/ws';
import { getMainDefinition } from '@apollo/client/utilities'; import { getMainDefinition } from '@apollo/client/utilities';
// import LinkList from './components/LinkList';
// class App extends Component {
// render() {
// return <LinkList />;
// }
// }
// export default App;
// import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import './styles/index.css'; import './styles/index.css';
import './styles/tachyons.min.css' import './styles/tachyons.min.css'
import App from './components/App'; import App from './components/App';
// // import * as serviceWorker from './serviceWorker';
// // 1 // 1
import { import {
ApolloProvider, ApolloProvider,
ApolloClient, ApolloClient,

View File

@@ -1,5 +0,0 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
{ {
"name": "server", "name": "hackernews-node",
"version": "1.0.0", "version": "1.0.0",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
@@ -8,9 +8,10 @@
}, },
"dependencies": { "dependencies": {
"@prisma/client": "^2.12.1", "@prisma/client": "^2.12.1",
"apollo-server": "^3.13.0", "apollo-server": "^2.19.0",
"bcryptjs": "2.4.3", "bcryptjs": "2.4.3",
"jsonwebtoken": "9.0.2" "graphql-depth-limit": "^1.1.0",
"jsonwebtoken": "8.5.1"
}, },
"devDependencies": { "devDependencies": {
"@prisma/cli": "^2.12.1", "@prisma/cli": "^2.12.1",

Binary file not shown.

View File

@@ -1,5 +1,6 @@
const { ApolloServer, PubSub } = require('apollo-server'); const { ApolloServer, PubSub } = require('apollo-server');
const { PrismaClient } = require('@prisma/client'); const { PrismaClient } = require('@prisma/client');
const depthLimit = require('graphql-depth-limit');
const Query = require('./resolvers/Query'); const Query = require('./resolvers/Query');
const Mutation = require('./resolvers/Mutation'); const Mutation = require('./resolvers/Mutation');
const Subscription = require('./resolvers/Subscription'); const Subscription = require('./resolvers/Subscription');
@@ -31,6 +32,7 @@ const server = new ApolloServer({
'utf8' 'utf8'
), ),
resolvers, resolvers,
validationRules: [depthLimit(4)],
context: ({ req }) => { context: ({ req }) => {
return { return {
...req, ...req,

View File

@@ -1,11 +1,12 @@
const bcrypt = require('bcryptjs'); const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const utils = require('../utils');
const { APP_SECRET } = require('../utils'); const { APP_SECRET } = require('../utils');
function post(parent, args, context, info) { async function post(parent, args, context, info) {
const { userId } = context; const { userId } = context;
const newLink = context.prisma.link.create({ const newLink = await context.prisma.link.create({
data: { data: {
url: args.url, url: args.url,
description: args.description, description: args.description,
@@ -13,30 +14,19 @@ function post(parent, args, context, info) {
} }
}); });
context.pubsub.publish('NEW_LINK', newLink);
return newLink; return newLink;
} }
// async function post(parent, args, context, info) {
// const { userId } = context;
// const newLink = await context.prisma.link.create({
// data: {
// url: args.url,
// description: args.description,
// postedBy: { connect: { id: userId } }
// }
// });
// context.pubsub.publish('NEW_LINK', newLink);
// return newLink;
// }
async function signup(parent, args, context, info) { async function signup(parent, args, context, info) {
const password = await bcrypt.hash(args.password, 10); const password = await bcrypt.hash(args.password, 10);
const user = await context.prisma.user.create({ const user = await context.prisma.user.create({
data: { ...args, password } data: { ...args, password }
}); });
const token = jwt.sign({ userId: user.id }, APP_SECRET); const token = utils.setToken(user.id);
return { return {
token, token,
@@ -56,11 +46,12 @@ async function login(parent, args, context, info) {
args.password, args.password,
user.password user.password
); );
if (!valid) { if (!valid) {
throw new Error('Invalid password'); throw new Error('Invalid password');
} }
const token = jwt.sign({ userId: user.id }, APP_SECRET); const token = utils.setToken(user.id);
return { return {
token, token,

View File

@@ -18,7 +18,6 @@ async function feed(parent, args, context, info) {
const count = await context.prisma.link.count({ where }); const count = await context.prisma.link.count({ where });
return { return {
id: 'main-feed',
links, links,
count count
}; };

View File

@@ -1,26 +1,16 @@
type Query { type Query {
info: String! info: String!
feed( feed(filter: String, skip: Int, take: Int, orderBy: LinkOrderByInput): Feed!
filter: String
skip: Int
take: Int
orderBy: LinkOrderByInput
): Feed!
} }
type Feed { type Feed {
id: ID!
links: [Link!]! links: [Link!]!
count: Int! count: Int!
} }
type Mutation { type Mutation {
post(url: String!, description: String!): Link! post(url: String!, description: String!): Link!
signup( signup(email: String!, password: String!, name: String!): AuthPayload
email: String!
password: String!
name: String!
): AuthPayload
login(email: String!, password: String!): AuthPayload login(email: String!, password: String!): AuthPayload
vote(linkId: ID!): Vote vote(linkId: ID!): Vote
} }

View File

@@ -5,7 +5,11 @@ function getTokenPayload(token) {
return jwt.verify(token, APP_SECRET); return jwt.verify(token, APP_SECRET);
} }
function getUserId(req, authToken) { function setToken(user_id) {
return jwt.sign({ userId: user_id }, APP_SECRET);
}
function getUserId(req) {
if (req) { if (req) {
const authHeader = req.headers.authorization; const authHeader = req.headers.authorization;
if (authHeader) { if (authHeader) {
@@ -16,9 +20,6 @@ function getUserId(req, authToken) {
const { userId } = getTokenPayload(token); const { userId } = getTokenPayload(token);
return userId; return userId;
} }
} else if (authToken) {
const { userId } = getTokenPayload(authToken);
return userId;
} }
throw new Error('Not authenticated'); throw new Error('Not authenticated');
@@ -26,5 +27,6 @@ function getUserId(req, authToken) {
module.exports = { module.exports = {
APP_SECRET, APP_SECRET,
setToken,
getUserId getUserId
}; };

File diff suppressed because it is too large Load Diff