Merge pull request #109 from ClaytonWWilson/finalfix

fixed user and topic relationship. allow add topic directly
This commit is contained in:
Leon Liang 2019-12-05 17:25:53 -05:00 committed by GitHub
commit c7859e0f0a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 747 additions and 562 deletions

View File

@ -66,46 +66,77 @@ exports.getallPosts = (req, res) => {
// Get all the posts // Get all the posts
var postsPromise = new Promise((resolve, reject) => { var postsPromise = new Promise((resolve, reject) => {
db.collection("posts").get() db.collection("posts")
.then((allPosts) => { .get()
allPosts.forEach((post) => { .then(allPosts => {
allPosts.forEach(post => {
posts.push(post.data()); posts.push(post.data());
}); });
resolve(); resolve();
}) })
.catch((error) => { .catch(error => {
reject(error); reject(error);
}) });
}); });
// Get all users // Get all users
var usersPromise = new Promise((resolve, reject) => { var usersPromise = new Promise((resolve, reject) => {
db.collection("users").get() db.collection("users")
.then((allUsers) => { .get()
allUsers.forEach((user) => { .then(allUsers => {
allUsers.forEach(user => {
users[user.data().handle] = user.data(); users[user.data().handle] = user.data();
}) });
resolve(); resolve();
}) })
.catch((error) => { .catch(error => {
reject(error); reject(error);
}) });
}); });
// Wait for the two promises // Wait for the two promises
Promise.all([postsPromise, usersPromise]) Promise.all([postsPromise, usersPromise])
.then(() => { .then(() => {
let newPosts = [] let newPosts = [];
// Add the image url of the person who made the post to all of the post objects // Add the image url of the person who made the post to all of the post objects
posts.forEach((post) => { posts.forEach(post => {
post.profileImage = users[post.userHandle].imageUrl ? users[post.userHandle].imageUrl : null; post.profileImage = users[post.userHandle].imageUrl
? users[post.userHandle].imageUrl
: null;
newPosts.push(post); newPosts.push(post);
}); });
return res.status(200).json(newPosts); return res.status(200).json(newPosts);
}) })
.catch((error) => { .catch(error => {
return res.status(500).json({error}); return res.status(500).json({ error });
});
};
exports.getAlert = (req, res) => {
var post_query = admin
.firestore()
.collection("posts")
.where("microBlogTitle", "==", "Alert");
post_query
.get()
.then(function(myPosts) {
let posts = [];
myPosts.forEach(function(doc) {
posts.push(doc.data());
});
return res.status(200).json(posts);
}) })
.then(function() {
return res
.status(200)
.json("Successfully retrieved all user's posts from database.");
})
.catch(function(err) {
return res
.status(500)
.json("Failed to retrieve user's posts from database.", err);
});
}; };
exports.getOtherUsersPosts = (req, res) => { exports.getOtherUsersPosts = (req, res) => {
@ -136,23 +167,25 @@ exports.getOtherUsersPosts = (req, res) => {
}; };
exports.quoteWithPost = (req, res) => { exports.quoteWithPost = (req, res) => {
let quoteData; let quoteData;
const quoteDoc = admin.firestore().collection('quote'). const quoteDoc = admin
where('userHandle', '==', req.user.handle). .firestore()
where('quoteId', '==', req.params.postId).limit(1); .collection("quote")
.where("userHandle", "==", req.user.handle)
.where("quoteId", "==", req.params.postId)
.limit(1);
const postDoc = db.doc(`/posts/${req.params.postId}`); const postDoc = db.doc(`/posts/${req.params.postId}`);
postDoc.get() postDoc
.then((doc) => { .get()
if(doc.exists) { .then(doc => {
quoteData = doc.data(); if (doc.exists) {
return quoteDoc.get(); quoteData = doc.data();
} return quoteDoc.get();
else } else {
{ return res.status(404).json({ error: "Post not found" });
return res.status(404).json({error: 'Post not found'}); }
}
}) })
.then(data => { .then(data => {
if (data.empty) { if (data.empty) {
@ -200,23 +233,25 @@ exports.quoteWithPost = (req, res) => {
}; };
exports.quoteWithoutPost = (req, res) => { exports.quoteWithoutPost = (req, res) => {
let quoteData; let quoteData;
const quoteDoc = admin.firestore().collection('quote'). const quoteDoc = admin
where('userHandle', '==', req.user.handle). .firestore()
where('quoteId', '==', req.params.postId).limit(1); .collection("quote")
.where("userHandle", "==", req.user.handle)
.where("quoteId", "==", req.params.postId)
.limit(1);
const postDoc = db.doc(`/posts/${req.params.postId}`); const postDoc = db.doc(`/posts/${req.params.postId}`);
postDoc.get() postDoc
.then((doc) => { .get()
if(doc.exists) { .then(doc => {
quoteData = doc.data(); if (doc.exists) {
return quoteDoc.get(); quoteData = doc.data();
} return quoteDoc.get();
else } else {
{ return res.status(404).json({ error: "Post not found" });
return res.status(404).json({error: 'Post not found'}); }
}
}) })
.then(data => { .then(data => {
if (data.empty) { if (data.empty) {
@ -258,7 +293,7 @@ exports.quoteWithoutPost = (req, res) => {
} }
}) })
.catch(err => { .catch(err => {
// return res.status(500).json({ error: "Something is wrong" }); // return res.status(500).json({ error: "Something is wrong" });
return res.status(500).json({ error: err }); return res.status(500).json({ error: err });
}); });
}; };
@ -272,202 +307,198 @@ exports.checkforLikePost = (req, res) => {
.limit(1); .limit(1);
let result; let result;
likedPostDoc.get().then(data => { likedPostDoc
if (data.empty) { .get()
result = false; .then(data => {
return res.status(200).json(result); if (data.empty) {
} else { result = false;
result = true; return res.status(200).json(result);
return res.status(200).json(result); } else {
} result = true;
}) return res.status(200).json(result);
.catch((err) => { }
})
.catch(err => {
console.log(err); console.log(err);
return res.status(500).json({error: err}); return res.status(500).json({ error: err });
}) });
}; };
exports.likePost = (req, res) => { exports.likePost = (req, res) => {
const postId = req.params.postId;
let likedPostDoc;
db.doc(`/users/${req.userData.handle}`)
.get()
.then(userDoc => {
let likes = userDoc.data().likes;
if (likes === undefined || likes === null) {
likes = [];
}
const postId = req.params.postId; if (likes.includes(postId)) {
let likedPostDoc; return res
db.doc(`/users/${req.userData.handle}`) .status(400)
.get() .json({ error: "This user has already liked this post" });
.then((userDoc) => { }
let likes = userDoc.data().likes;
if (likes === undefined || likes === null) {
likes = [];
}
if (likes.includes(postId)) { likes.push(postId);
return res.status(400).json({error: "This user has already liked this post"});
}
likes.push(postId); return userDoc.ref.update({ likes });
})
.then(() => {
return db.doc(`/posts/${postId}`).get();
})
.then(postDoc => {
let postData = postDoc.data();
postData.likeCount++;
likedPostDoc = postData;
return postDoc.ref.update({ likeCount: postData.likeCount });
})
.then(() => {
return res.status(201).json(likedPostDoc);
})
.catch(err => {
console.log(err);
return res.status(500).json({ error: err });
});
return userDoc.ref.update({likes}) // let postData;
}) // const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
.then(() => { // .where('postId', '==', req.params.postId).limit(1);
return db.doc(`/posts/${postId}`).get()
}) // const postDoc = db.doc(`/posts/${req.params.postId}`);
.then((postDoc) => {
let postData = postDoc.data();
postData.likeCount++;
likedPostDoc = postData;
return postDoc.ref.update({likeCount : postData.likeCount})
})
.then(() => {
return res.status(201).json(likedPostDoc);
})
.catch((err) => {
console.log(err);
return res.status(500).json({error: err});
})
// let postData; // postDoc.get()
// const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle) // .then((doc) => {
// .where('postId', '==', req.params.postId).limit(1); // if(doc.exists) {
// postData = doc.data();
// const postDoc = db.doc(`/posts/${req.params.postId}`); // return likeDoc.get();
// }
// postDoc.get() // else
// .then((doc) => { // {
// if(doc.exists) { // return res.status(404).json({error: 'Post not found'});
// postData = doc.data(); // }
// return likeDoc.get(); // })
// } // .then((data) => {
// else // if (data.empty) {
// { // return admin.firestore().collection('likes').add({
// return res.status(404).json({error: 'Post not found'}); // postId : req.params.postId,
// } // userHandle: req.user.handle
// })
// .then((data) => {
// if (data.empty) {
// return admin.firestore().collection('likes').add({
// postId : req.params.postId,
// userHandle: req.user.handle
// })
// .then(() => {
// postData.likeCount++;
// return postDoc.update({likeCount : postData.likeCount})
// })
// .then(() => {
// return res.status(200).json(postData);
// })
// }
// })
// .catch((err) => {
// return res.status(500).json({error: 'Something is wrong'});
// })
}
// })
// .then(() => {
// postData.likeCount++;
// return postDoc.update({likeCount : postData.likeCount})
// })
// .then(() => {
// return res.status(200).json(postData);
// })
// }
// })
// .catch((err) => {
// return res.status(500).json({error: 'Something is wrong'});
// })
};
exports.unlikePost = (req, res) => { exports.unlikePost = (req, res) => {
const postId = req.params.postId;
let likedPostDoc;
db.doc(`/users/${req.userData.handle}`)
.get()
.then(userDoc => {
let likes = userDoc.data().likes;
if (likes === undefined || likes === null) {
likes = [];
}
const postId = req.params.postId; if (!likes.includes(postId)) {
let likedPostDoc; return res
db.doc(`/users/${req.userData.handle}`) .status(400)
.get() .json({ error: "This user hasn't liked this post yet" });
.then((userDoc) => { }
let likes = userDoc.data().likes;
if (likes === undefined || likes === null) {
likes = [];
}
if (!likes.includes(postId)) { let i;
return res.status(400).json({error: "This user hasn't liked this post yet"}); for (i = 0; i < likes.length; i++) {
} if (likes[i] === postId) {
likes.splice(i, 1);
}
}
let i; return userDoc.ref.update({ likes });
for (i = 0; i < likes.length; i++) { })
if (likes[i] === postId) { .then(() => {
likes.splice(i, 1); return db.doc(`/posts/${postId}`).get();
} })
} .then(postDoc => {
let postData = postDoc.data();
postData.likeCount--;
likedPostDoc = postData;
return postDoc.ref.update({ likeCount: postData.likeCount });
})
.then(() => {
return res.status(201).json(likedPostDoc);
})
.catch(err => {
console.log(err);
return res.status(500).json({ error: err });
});
return userDoc.ref.update({likes}) // let postData;
}) // const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle)
.then(() => { // .where('postId', '==', req.params.postId).limit(1);
return db.doc(`/posts/${postId}`).get()
}) // const postDoc = db.doc(`/posts/${req.params.postId}`);
.then((postDoc) => {
let postData = postDoc.data();
postData.likeCount--;
likedPostDoc = postData;
return postDoc.ref.update({likeCount : postData.likeCount})
})
.then(() => {
return res.status(201).json(likedPostDoc);
})
.catch((err) => {
console.log(err);
return res.status(500).json({error: err});
})
// let postData; // postDoc.get()
// const likeDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle) // .then((doc) => {
// .where('postId', '==', req.params.postId).limit(1); // if(doc.exists) {
// postData = doc.data();
// const postDoc = db.doc(`/posts/${req.params.postId}`); // return likeDoc.get();
// }
// postDoc.get() // else
// .then((doc) => { // {
// if(doc.exists) { // return res.status(404).json({error: 'Post not found'});
// postData = doc.data(); // }
// return likeDoc.get(); // })
// } // .then((data) => {
// else // return db
// { // .doc(`/likes/${data.docs[0].id}`)
// return res.status(404).json({error: 'Post not found'}); // .delete()
// } // .then(() => {
// }) // postData.likeCount--;
// .then((data) => { // return postDoc.update({ likeCount: postData.likeCount });
// return db // })
// .doc(`/likes/${data.docs[0].id}`) // .then(() => {
// .delete() // res.status(200).json(postData);
// .then(() => { // });
// postData.likeCount--;
// return postDoc.update({ likeCount: postData.likeCount });
// })
// .then(() => {
// res.status(200).json(postData);
// });
// })
// .catch((err) => {
// console.error(err);
// return res.status(500).json({error: 'Something is wrong'});
// })
}
// })
// .catch((err) => {
// console.error(err);
// return res.status(500).json({error: 'Something is wrong'});
// })
};
exports.getLikes = (req, res) => { exports.getLikes = (req, res) => {
db.doc(`/users/${req.userData.handle}`) db.doc(`/users/${req.userData.handle}`)
.get() .get()
.then((doc) => { .then(doc => {
let likes = doc.data().likes; let likes = doc.data().likes;
if (likes === undefined || likes === null) { if (likes === undefined || likes === null) {
likes = []; likes = [];
} }
return res.status(200).json({likes}); return res.status(200).json({ likes });
}) })
.catch((err) => { .catch(err => {
console.log(err); console.log(err);
return res.status(500).json({error: err}); return res.status(500).json({ error: err });
}) });
} };
exports.getFilteredPosts = (req, res) => { exports.getFilteredPosts = (req, res) => {
admin admin
.firestore() .firestore()
.collection("posts") .collection("posts")
.where("userHandle", "==", "new user") .where("userHandle", "==", "new user")
.where("microBlogTopics", "=="); .where("microBlogTopics", "==");
}; };

View File

@ -26,6 +26,41 @@ exports.putTopic = (req, res) => {
}); });
}; };
exports.putNewTopic = (req, res) => {
let new_following = [];
let userRef = db.doc(`/users/${req.userData.handle}`);
userRef
.get()
.then(doc => {
let topics = [];
new_following = doc.data().following;
// new_following.push(req.body.following);
new_following.forEach(follow => {
if (follow.handle === req.body.handle) {
// topics = follow.topics;
follow.topics.push(req.body.topic);
}
});
// return res.status(201).json({ new_following });
// add stuff
userRef
.set({ following: new_following }, { merge: true })
.then(doc => {
return res
.status(201)
.json({ message: `Following ${req.body.topic}` });
})
.catch(err => {
return res.status(500).json({ err });
});
return res.status(200).json({ message: "OK" });
})
.catch(err => {
return res.status(500).json({ err });
});
};
exports.getAllTopics = (req, res) => { exports.getAllTopics = (req, res) => {
admin admin
.firestore() .firestore()

File diff suppressed because it is too large Load Diff

View File

@ -100,13 +100,23 @@ app.post("/addSubscription", fbAuth, addSubscription);
// remove one subscription // remove one subscription
app.post("/removeSub", fbAuth, removeSub); app.post("/removeSub", fbAuth, removeSub);
/*------------------------------------------------------------------* /*------------------------------------------------------------------*
* handlers/post.js * * handlers/post.js *
*------------------------------------------------------------------*/ *------------------------------------------------------------------*/
const { getallPostsforUser, getallPosts, putPost, likePost, unlikePost, getLikes, quoteWithPost, quoteWithoutPost, checkforLikePost, getOtherUsersPosts} = require("./handlers/post"); const {
getallPostsforUser,
getallPosts,
putPost,
likePost,
unlikePost,
getLikes,
quoteWithPost,
quoteWithoutPost,
checkforLikePost,
getOtherUsersPosts,
getAlert
} = require("./handlers/post");
app.get("/getallPostsforUser", fbAuth, getallPostsforUser); app.get("/getallPostsforUser", fbAuth, getallPostsforUser);
@ -125,6 +135,8 @@ app.post("/quoteWithoutPost/:postId", fbAuth, quoteWithoutPost);
app.post("/getOtherUsersPosts", fbAuth, getOtherUsersPosts); app.post("/getOtherUsersPosts", fbAuth, getOtherUsersPosts);
app.get("/getAlert", fbAuth, getAlert);
/*------------------------------------------------------------------* /*------------------------------------------------------------------*
* handlers/topic.js * * handlers/topic.js *
*------------------------------------------------------------------*/ *------------------------------------------------------------------*/
@ -132,7 +144,8 @@ const {
putTopic, putTopic,
getAllTopics, getAllTopics,
deleteTopic, deleteTopic,
getUserTopics getUserTopics,
putNewTopic
} = require("./handlers/topic"); } = require("./handlers/topic");
// add topic to database // add topic to database
@ -147,4 +160,6 @@ app.post("/deleteTopic", fbAuth, deleteTopic);
// get topic for this user // get topic for this user
app.post("/getUserTopics", fbAuth, getUserTopics); app.post("/getUserTopics", fbAuth, getUserTopics);
app.post("/putNewTopic", fbAuth, putNewTopic);
exports.api = functions.https.onRequest(app); exports.api = functions.https.onRequest(app);

View File

@ -180,7 +180,7 @@ class Home extends Component {
<p></p> <p></p>
) )
) : ( ) : (
<p>Loading</p> <p></p>
) )
) )
) : ( ) : (

View File

@ -79,6 +79,7 @@ class user extends Component {
following: null, following: null,
posts: null, posts: null,
myTopics: null, myTopics: null,
followingList: null
loading: false loading: false
}; };
} }
@ -115,6 +116,24 @@ class user extends Component {
} }
}; };
handleAdd = newTopic => {
axios
.post("/putNewTopic", {
handle: this.state.profile,
topic: newTopic
})
.then(() => {
let temp = this.state.myTopics;
temp.push(newTopic);
this.setState({
myTopics: temp
});
})
.catch(err => {
console.err(err);
});
};
componentDidMount() { componentDidMount() {
this.setState({loading: true}); this.setState({loading: true});
let otherUserPromise = axios let otherUserPromise = axios
@ -132,11 +151,19 @@ class user extends Component {
let userPromise = axios let userPromise = axios
.get("/user") .get("/user")
.then(res => { .then(res => {
// console.log(res.data.credentials.following);
let list = [];
let fol = false;
res.data.credentials.following.forEach(follow => {
console.log(follow);
if (this.state.profile === follow.handle) {
fol = true;
list = follow.topics;
}
});
this.setState({ this.setState({
following: res.data.credentials.following.includes( following: fol,
this.state.profile myTopics: list
),
myTopics: res.data.credentials.followedTopics
}); });
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
@ -153,6 +180,23 @@ class user extends Component {
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
axios
.get("/getAlert")
.then(res => {
let temp = this.state.posts;
// console.log(res.data);
res.data.forEach(element => {
element ? temp.push(element) : console.err;
});
// temp.push(res.data[0]);
this.setState({
posts: temp
});
})
.catch(function(err) {
console.log(err);
});
Promise.all([otherUserPromise, userPromise, posts]) Promise.all([otherUserPromise, userPromise, posts])
.then(() => { .then(() => {
this.setState({loading: false}); this.setState({loading: false});
@ -188,8 +232,8 @@ class user extends Component {
<p>loading username...</p> <p>loading username...</p>
); );
console.log(this.state.topics); // console.log(this.state.topics);
console.log(this.state.myTopics); // console.log(this.state.myTopics);
let topicsMarkup = this.state.topics ? ( let topicsMarkup = this.state.topics ? (
this.state.topics.map( this.state.topics.map(
topic => topic =>
@ -206,6 +250,8 @@ class user extends Component {
label={topic} label={topic}
key={{ topic }.topic.id} key={{ topic }.topic.id}
color="secondary" color="secondary"
clickable
onClick={key => this.handleAdd(topic)}
/> />
) )
) : ( ) : (
@ -222,7 +268,7 @@ class user extends Component {
) : ( ) : (
<img src={noImage} height="150" width="150" /> <img src={noImage} height="150" width="150" />
); );
//(this.state.posts);
let postMarkup = this.state.posts ? ( let postMarkup = this.state.posts ? (
this.state.posts.map(post => ( this.state.posts.map(post => (
<Card className={classes.card}> <Card className={classes.card}>