Skip to content

Commit

Permalink
load public articles on homepage
Browse files Browse the repository at this point in the history
  • Loading branch information
yannicklescure committed Apr 18, 2022
1 parent 5377d8d commit 25c45a7
Show file tree
Hide file tree
Showing 6 changed files with 77 additions and 34 deletions.
40 changes: 40 additions & 0 deletions client/src/components/PublicArticles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { useEffect, useState } from "react";
import styled from "styled-components";
import Loading from "./Loading";
import Article from "../components/cards/Article";

const PublicArticles = () => {

const [articles, setArticles] = useState([]);
const [loading, setLoading] = useState(true);

useEffect(() => {
setLoading(true);
fetch(`/api/articles`)
.then((res) => res.json())
.then((response) => {
// console.log(response.data);
setArticles(response.data);
setLoading(false);
});
// eslint-disable-next-line
}, []);

if (loading) return <Loading size="32" />;

return (
<Wrapper>
{
articles.map(article => (
<Article key={article._id} article={article} />
))
}
</Wrapper>
)
}

const Wrapper = styled.div`
margin: 48px 0;
`;

export default PublicArticles;
1 change: 1 addition & 0 deletions client/src/components/cards/Article.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ const Main = styled.button`
margin: 0 0 16px 0;
cursor: pointer;
border-bottom: 1px solid ${COLORS.grey};
width: 100%;
&:last-child {
border: none;
Expand Down
2 changes: 1 addition & 1 deletion client/src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const readingTime = (text) => {
};

export const makeTextIntro = (text) => {
const arr = text.split(/\n/).filter(el => !(new RegExp('[#`]').test(el)) && el.length > 0);
const arr = text.split(/\n/).filter(el => !(new RegExp('[#`*-]').test(el)) && el.length > 0);
let result = arr[0];
if (result.split(' ').length > 50) result = result.split(' ').slice(0, 50).join(' ') + '...';
// console.log(result);
Expand Down
2 changes: 2 additions & 0 deletions client/src/pages/Homepage.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useContext } from "react";
import Banner from "../components/Banner";
import Trending from "../components/Trending";
import PublicArticles from "../components/PublicArticles";
import { UserContext } from "../contexts/UserContext";

const Homepage = () => {
Expand All @@ -12,6 +13,7 @@ const Homepage = () => {
<>
{ !user._id && <Banner /> }
<Trending />
<PublicArticles />
</>
)
}
Expand Down
60 changes: 29 additions & 31 deletions server/handlers.js
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,7 @@ const updateStory = async (req, res) => {
if (req.query.delete === 'true') {
updatedStory = {
...updatedStory,
visibility: 'unlisted',
deleted: true
}

Expand Down Expand Up @@ -401,7 +402,7 @@ const getTagStories = async (req, res) => {
try {
await client.connect();
const db = client.db(DB_NAME);
const result = await db.collection("stories").find({ tags: { $exists: true, $eq: req.params.tagName } }).toArray();
const result = await db.collection("stories").find({ visibility: 'public', tags: { $exists: true, $eq: req.params.tagName } }).toArray();
// console.log(result);
console.log(req.params.tagName);
let data = {};
Expand Down Expand Up @@ -497,7 +498,29 @@ const getStory = async (req, res) => {
}
};

const getStories = async (req, res) => {
const getArticles = async (req, res) => {
console.log(req.params);
console.log(req.query);

const client = new MongoClient(MONGO_URI, option);
try {
await client.connect();
const db = client.db(DB_NAME);
let data = await db.collection("stories").find({ visibility: 'public' }).toArray();
data = data.filter(el => !el.deleted).sort((a,b) => b.createdAt - a.createdAt);
console.log(data.length + 'items');
const arr = [];

res.status(200).json({ status: 200, data, message: "success" });
} catch (err) {
console.log("Error", err);
res.status(500).json({ status: 500, message: err });
} finally {
client.close();
}
};

const getUserStories = async (req, res) => {
console.log(req.params);
console.log(req.query);

Expand All @@ -508,35 +531,9 @@ const getStories = async (req, res) => {
const userId = req.query._id;
if (userId) {
let data = await db.collection("stories").find({ userId }).toArray();
data = data.sort((a,b) => b.createdAt - a.createdAt);
data = data.filter(el => !el.deleted).sort((a,b) => b.createdAt - a.createdAt);
console.log(data.length + 'items');
const arr = [];
// data.forEach(async (item) => {
// console.log(item.userId);
// const { title, content, imageSrc, createdAt, updatedAt, _id, userId, slug, visibility, username, tags } = item;
// const views = item.views ? item.views : 1;
// const user = await db.collection("users").findOne({ _id: userId });
// console.log(user.username);
// arr.push({
// _id,
// content,
// createdAt,
// imageSrc,
// title,
// updatedAt,
// user: {
// _id: userId,
// firstName: user.firstName,
// lastName: user.lastName,
// imageSrc: user.imageSrc,
// username,
// },
// slug,
// visibility,
// views,
// tags
// });
// });

res.status(200).json({ status: 200, data, message: "success" });
}
Expand Down Expand Up @@ -568,7 +565,7 @@ const getTrending = async (req, res) => {
views: 1,
createdAt: 1,
content: 1,
tags: 1
tags: 1,
}).toArray();
console.log('received stories array');
// console.log(stories);
Expand Down Expand Up @@ -619,11 +616,12 @@ module.exports = {
updateUser,
createStory,
getStory,
getStories,
getUserStories,
updateStory,
updateStoryViews,
getTagStories,
getTrending,
getArticles,
// updateCart,
// updateBookmarks,
// updateOrdersHistory,
Expand Down
6 changes: 4 additions & 2 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ const {
updateUser,
createStory,
getStory,
getStories,
getUserStories,
updateStory,
updateStoryViews,
getTagStories,
getTrending,
getArticles,
// updateCart,
// updateBookmarks,
// updateOrdersHistory,
Expand Down Expand Up @@ -58,8 +59,9 @@ if (process.env.NODE_ENV === 'developement') {
app.get("/api/users", getUsers)
app.get("/api/users/:username", getUser)
app.get("/api/tag/:tagName", getTagStories)
app.get("/api/stories/:username", getStories)
app.get("/api/stories/:username", getUserStories)
app.get("/api/trending", getTrending)
app.get("/api/articles", getArticles)
app.get("/api/stories/:username/:slug", getStory)
app.put("/api/stories/:username/:slug", updateStory)
app.put("/api/views", updateStoryViews)
Expand Down

0 comments on commit 25c45a7

Please sign in to comment.