diff --git a/functions/handlers/post.js b/functions/handlers/post.js index 69a751e..2f5ce4f 100644 --- a/functions/handlers/post.js +++ b/functions/handlers/post.js @@ -1,76 +1,141 @@ /* eslint-disable prefer-arrow-callback */ /* eslint-disable promise/always-return */ -const admin = require('firebase-admin'); -const { db } = require('../util/admin'); - +const admin = require("firebase-admin"); +const { db } = require("../util/admin"); exports.putPost = (req, res) => { - const newPost = { - body: req.body.body, - userHandle: req.user.handle, - userImage: req.body.userImage, - userID: req.user.uid, - microBlogTitle: req.body.microBlogTitle, - createdAt: new Date().toISOString(), - likeCount: 0, - commentCount: 0, - microBlogTopics: req.body.microBlogTopics, - quoteBody: null - }; + const newPost = { + body: req.body.body, + userHandle: req.user.handle, + userImage: req.body.userImage, + userID: req.user.uid, + microBlogTitle: req.body.microBlogTitle, + createdAt: new Date().toISOString(), + likeCount: 0, + commentCount: 0, + microBlogTopics: req.body.microBlogTopics, + quoteBody: null + }; - admin.firestore().collection('posts').add(newPost) - .then((doc) => { - doc.update({postId: doc.id}) - const resPost = newPost; - resPost.postId = doc.id; - return res.status(200).json(resPost); + admin + .firestore() + .collection("posts") + .add(newPost) + .then(doc => { + doc.update({ postId: doc.id }); + const resPost = newPost; + resPost.postId = doc.id; + return res.status(200).json(resPost); }) - .catch((err) => { - console.error(err); - return res.status(500).json({ error: 'something went wrong'}); + .catch(err => { + console.error(err); + return res.status(500).json({ error: "something went wrong" }); }); }; exports.getallPostsforUser = (req, res) => { - var post_query = admin.firestore().collection("posts").where("userHandle", "==", req.user.handle); + var post_query = admin + .firestore() + .collection("posts") + .where("userHandle", "==", req.user.handle); - post_query.get() + post_query + .get() .then(function(myPosts) { - let posts = []; - myPosts.forEach(function(doc) { - posts.push(doc.data()); - }); - return res.status(200).json(posts); + 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."); - + 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); + return res + .status(500) + .json("Failed to retrieve user's posts from database.", err); }); }; exports.getallPosts = (req, res) => { - var post_query = admin.firestore().collection("posts"); - post_query.get() - .then(function(allPosts) { - let posts = []; - allPosts.forEach(function(doc) { - posts.push(doc.data()); + let posts = []; + let users = {}; + + // Get all the posts + var postsPromise = new Promise((resolve, reject) => { + db.collection("posts").get() + .then((allPosts) => { + allPosts.forEach((post) => { + posts.push(post.data()); }); - return res.status(200).json(posts); + resolve(); + }) + .catch((error) => { + reject(error); + }) + }); + + // Get all users + var usersPromise = new Promise((resolve, reject) => { + db.collection("users").get() + .then((allUsers) => { + allUsers.forEach((user) => { + users[user.data().handle] = user.data(); + }) + resolve(); + }) + .catch((error) => { + reject(error); + }) + }); + + // Wait for the two promises + Promise.all([postsPromise, usersPromise]) + .then(() => { + let newPosts = [] + // Add the image url of the person who made the post to all of the post objects + posts.forEach((post) => { + post.profileImage = users[post.userHandle].imageUrl ? users[post.userHandle].imageUrl : null; + newPosts.push(post); + }); + return res.status(200).json(newPosts); + }) + .catch((error) => { + return res.status(500).json({error}); + }) +}; + +exports.getOtherUsersPosts = (req, res) => { + var post_query = admin + .firestore() + .collection("posts") + .where("userHandle", "==", req.body.handle); + + 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 every post from database."); + return res + .status(200) + .json("Successfully retrieved all user's posts from database."); }) .catch(function(err) { - return res.status(500).json("Failed to retrieve posts from database.", err); + return res + .status(500) + .json("Failed to retrieve user's posts from database.", err); }); }; exports.quoteWithPost = (req, res) => { - let quoteData; const quoteDoc = admin.firestore().collection('quote'). where('userHandle', '==', req.user.handle). @@ -89,46 +154,50 @@ exports.quoteWithPost = (req, res) => { return res.status(404).json({error: 'Post not found'}); } }) - .then((data) => { - if(data.empty) { - return admin.firestore().collection('quote').add({ - quoteId : req.params.postId, - userHandle : req.user.handle, - quoteBody : req.body.quoteBody - }) - .then(() => { - const post = { - body: quoteData.body, - userHandle : req.user.handle, - quoteBody: req.body.quoteBody, - createdAt : new Date().toISOString(), - userImage: req.body.userImage, - likeCount: 0, - commentCount: 0, - userID: req.user.uid, - microBlogTitle: quoteData.microBlogTitle, - microBlogTopics: quoteData.microBlogTopics, - quoteId: req.params.postId - } - return admin.firestore().collection('posts').add(post) - .then((doc) => { - doc.update({postId: doc.id}) + .then(data => { + if (data.empty) { + return admin + .firestore() + .collection("quote") + .add({ + quoteId: req.params.postId, + userHandle: req.user.handle, + quoteBody: req.body.quoteBody + }) + .then(() => { + const post = { + body: quoteData.body, + userHandle: req.user.handle, + quoteBody: req.body.quoteBody, + createdAt: new Date().toISOString(), + userImage: req.body.userImage, + likeCount: 0, + commentCount: 0, + userID: req.user.uid, + microBlogTitle: quoteData.microBlogTitle, + microBlogTopics: quoteData.microBlogTopics, + quoteId: req.params.postId + }; + return admin + .firestore() + .collection("posts") + .add(post) + .then(doc => { + doc.update({ postId: doc.id }); const resPost = post; resPost.postId = doc.id; return res.status(200).json(resPost); - }) - }) - } - else { - return res.status(400).json({ error: 'Post has already been quoted.' }); - } - }) - .catch((err) => { - return res.status(500).json({error: err}); - + }); + }); + } else { + return res.status(400).json({ error: "Post has already been quoted." }); + } }) -} + .catch(err => { + return res.status(500).json({ error: err }); + }); +}; exports.quoteWithoutPost = (req, res) => { let quoteData; @@ -149,70 +218,77 @@ exports.quoteWithoutPost = (req, res) => { return res.status(404).json({error: 'Post not found'}); } }) - .then((data) => { - if(data.empty) { - return admin.firestore().collection('quote').add({ - quoteId : req.params.postId, - userHandle : req.user.handle, - quoteBody: null - }) - .then(() => { - const post = { - userHandle : req.user.handle, - body: quoteData.body, - quoteBody: null, - createdAt : new Date().toISOString(), - likeCount: 0, - commentCount: 0, - userID: req.user.uid, - userImage: req.body.userImage, - microBlogTitle: quoteData.microBlogTitle, - microBlogTopics: quoteData.microBlogTopics, - quoteId: req.params.postId - } - return admin.firestore().collection('posts').add(post) - .then((doc) => { - doc.update({postId: doc.id}) + .then(data => { + if (data.empty) { + return admin + .firestore() + .collection("quote") + .add({ + quoteId: req.params.postId, + userHandle: req.user.handle, + quoteBody: null + }) + .then(() => { + const post = { + userHandle: req.user.handle, + body: quoteData.body, + quoteBody: null, + createdAt: new Date().toISOString(), + likeCount: 0, + commentCount: 0, + userID: req.user.uid, + userImage: req.body.userImage, + microBlogTitle: quoteData.microBlogTitle, + microBlogTopics: quoteData.microBlogTopics, + quoteId: req.params.postId + }; + return admin + .firestore() + .collection("posts") + .add(post) + .then(doc => { + doc.update({ postId: doc.id }); const resPost = post; resPost.postId = doc.id; return res.status(200).json(resPost); - }) - - - - }) - } - else { - return res.status(400).json({ error: 'Post has already been quoted.' }); + }); + }); + } else { + return res.status(400).json({ error: "Post has already been quoted." }); } }) - .catch((err) => { - return res.status(500).json({error: 'Something is wrong'}); - - }) - -} + .catch(err => { + // return res.status(500).json({ error: "Something is wrong" }); + return res.status(500).json({ error: err }); + }); +}; exports.checkforLikePost = (req, res) => { - const likedPostDoc = admin.firestore().collection('likes').where('userHandle', '==', req.user.handle) - .where('postId', '==', req.params.postId).limit(1); - let result; + const likedPostDoc = admin + .firestore() + .collection("likes") + .where("userHandle", "==", req.user.handle) + .where("postId", "==", req.params.postId) + .limit(1); + let result; - likedPostDoc.get() - .then((data) => { - if (data.empty) { - result = false; - return res.status(200).json(result); - } - else - { - result = true; - return res.status(200).json(result); - } - }) -} + likedPostDoc.get().then(data => { + if (data.empty) { + result = false; + return res.status(200).json(result); + } else { + result = true; + return res.status(200).json(result); + } + }) + .catch((err) => { + console.log(err); + return res.status(500).json({error: err}); + }) +}; exports.likePost = (req, res) => { + const postId = req.params.postId; let likedPostDoc; db.doc(`/users/${req.userData.handle}`) @@ -369,6 +445,7 @@ exports.unlikePost = (req, res) => { } + exports.getLikes = (req, res) => { db.doc(`/users/${req.userData.handle}`) .get() @@ -386,5 +463,11 @@ exports.getLikes = (req, res) => { } exports.getFilteredPosts = (req, res) => { - admin.firestore().collection('posts').where('userHandle', '==', 'new user').where('microBlogTopics', '==') -}; \ No newline at end of file + + admin + .firestore() + .collection("posts") + .where("userHandle", "==", "new user") + .where("microBlogTopics", "=="); +}; + diff --git a/functions/handlers/users.js b/functions/handlers/users.js index 5350d19..7d2b5c0 100644 --- a/functions/handlers/users.js +++ b/functions/handlers/users.js @@ -1,4 +1,6 @@ /* eslint-disable promise/catch-or-return */ +/* eslint-disable promise/always-return */ + const { admin, db } = require("../util/admin"); const config = require("../util/config"); const { validateUpdateProfileInfo } = require("../util/validator"); @@ -209,7 +211,7 @@ exports.deleteUser = (req, res) => { let errors = {}; function thenFunction(data) { - console.log(`${data} data for ${req.userData.handle} has been deleted.`); + console.log(`${data} for ${req.userData.handle} has been deleted.`); } function catchFunction(data, err) { @@ -217,14 +219,131 @@ exports.deleteUser = (req, res) => { errors[data] = err; } + function deleteDirectMessages() { + return new Promise((resolve, reject) => { + const deleteUsername = req.userData.handle; + db.doc(`/users/${deleteUsername}`) + .get() + .then((deleteUserDocSnap) => { + const dms = deleteUserDocSnap.data().dms; + const dmRecipients = deleteUserDocSnap.data().dmRecipients; + + if (!dms) { + resolve(); + return; + } + + // Iterate over the list of users who this person has DM'd + let otherUsersPromises = []; + + // Resolve if they don't have a dmRecipients list + if (dmRecipients === undefined || dmRecipients === null || dmRecipients.length === 0) { + resolve(); + return; + } + dmRecipients.forEach((dmRecipient) => { + otherUsersPromises.push( + // Get each users data + db.doc(`/users/${dmRecipient}`).get() + .then((otherUserDocSnap) => { + // Get the index of deleteUsername so that we can remove the dangling + // reference to the DM document + let otherUserDMRecipients = otherUserDocSnap.data().dmRecipients; + let otherUserDMs = otherUserDocSnap.data().dms; + let index = -1; + otherUserDMRecipients.forEach((dmRecip, i) => { + if (dmRecip === deleteUsername) { + index = i; + } + }) + + if (index !== -1) { + // Remove deleteUsername from their dmRecipients list + otherUserDMRecipients.splice(index, 1); + + // Remove the DM channel with deleteUsername + otherUserDMs.splice(index, 1); + + // Update the users data + return otherUserDocSnap.ref.update({ + dmRecipients: otherUserDMRecipients, + dms: otherUserDMs + }); + } + + }) + ) + }) + + // Wait for the removal of DM data stored on other users to be deleted + Promise.all(otherUsersPromises) + .then(() => { + // Iterate through DM references and delete them from the dm collection + let dmRefsPromises = []; + dms.forEach((dmRef) => { + // Create a delete queue + let batch = db.batch(); + dmRefsPromises.push( + // Add the messages to the delete queue + db.collection(`/dm/${dmRef.id}/messages`).listDocuments() + .then((docs) => { + console.log("second") + console.log(docs); + docs.map((doc) => { + batch.delete(doc); + }) + + // Add the doc that the DM is stored in to the delete queue + batch.delete(dmRef); + + // Commit the writes + return batch.commit(); + }) + ) + }) + + return Promise.all(dmRefsPromises); + }) + .then(() => { + resolve(); + return; + }) + .catch((err) => { + console.log("error " + err); + reject(err); + return; + }) + }) + .catch((err) => { + console.log(err); + return res.status(500).json({error: err}); + }) + + }) + } + // Deletes user from authentication let auth = admin.auth().deleteUser(userId); // Deletes database data - let data = db - .collection("users") - .doc(`${req.user.handle}`) - .delete(); + let data = new Promise((resolve, reject) => { + deleteDirectMessages() + .then(() => { + return db + .collection("users") + .doc(`${req.user.handle}`) + .delete() + }) + .then(() => { + resolve(); + return; + }) + .catch((err) => { + console.log(err); + reject(err); + return; + }) + }) // Deletes any custom profile image let image; @@ -298,7 +417,7 @@ exports.updateProfileInfo = (req, res) => { // Update the database entry for this user db.collection("users") .doc(req.user.handle) - .set(profileData, { merge: true }) + .set(profileData) .then(() => { console.log(`${req.user.handle}'s profile info has been updated.`); return res.status(201).json({ @@ -331,6 +450,25 @@ exports.getUserDetails = (req, res) => { }); }; +exports.getAllHandles = (req, res) => { + var user_query = admin.firestore().collection("users"); + user_query.get() + .then((allUsers) => { + let users = []; + allUsers.forEach((user) => { + users.push(user.data().handle); + }); + return res.status(200).json(users); + }) + .catch((err) => { + return res.status(500).json({ + message:"Failed to retrieve posts from database.", + error: err + }); + }); +}; + +// Returns all data stored for a user exports.getAuthenticatedUser = (req, res) => { let credentials = {}; db.doc(`/users/${req.user.handle}`) @@ -466,6 +604,126 @@ exports.getSubs = (req, res) => { }); }; +// Uploads a profile image +exports.uploadProfileImage = (req, res) => { + const BusBoy = require("busboy"); + const path = require("path"); + const os = require("os"); + const fs = require("fs"); + + const busboy = new BusBoy({ headers: req.headers }); + + let imageFileName; + let imageToBeUploaded = {}; + let oldImageFileName = req.userData.imageUrl ? req.userData.imageUrl.split("/o/")[1].split("?alt")[0] : null; + // console.log(`old file: ${oldImageFileName}`); + + busboy.on("file", (fieldname, file, filename, encoding, mimetype) => { + if (mimetype !== 'image/jpeg' && mimetype !== 'image/png') { + return res.status(400).json({ error: "Wrong filetype submitted" }); + } + // console.log(fieldname); + // console.log(filename); + // console.log(mimetype); + const imageExtension = filename.split(".")[filename.split(".").length - 1]; // Get the image file extension + imageFileName = `${Math.round(Math.random() * 100000000000)}.${imageExtension}`; // Get a random filename + const filepath = path.join(os.tmpdir(), imageFileName); + imageToBeUploaded = { filepath, mimetype }; + file.pipe(fs.createWriteStream(filepath)); + }); + busboy.on("finish", () => { + // Save the file to the storage bucket + admin.storage().bucket(config.storageBucket).upload(imageToBeUploaded.filepath, { + resumable: false, + metadata: { + metadata: { + contentType: imageToBeUploaded.mimetype + } + } + }) + .then(() => { + // Add the new URL to the user's profile + const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`; + return db.doc(`/users/${req.user.handle}`).update({ imageUrl }); + }) + .then(() => { + // Delete their old image if they have one + if (oldImageFileName !== null && oldImageFileName !== "no-img.png") { + admin.storage().bucket(config.storageBucket).file(oldImageFileName).delete() + .then(() => { + return res.status(201).json({ message: "Image uploaded successfully1"}); + }) + .catch((err) => { + console.log(err); + return res.status(201).json({ message: "Image uploaded successfully2"}); + }) + // return res.status(201).json({ message: "Image uploaded successfully"}); + } else { + return res.status(201).json({ message: "Image uploaded successfully3"}); + } + + }) + .catch((err) => { + console.error(err); + return res.status(500).json({ error: err.code}) + }) + }); + busboy.end(req.rawBody); + + // const BusBoy = require('busboy'); + // const path = require('path'); + // const os = require('os'); + // const fs = require('fs'); + + // const busboy = new BusBoy({ headers: req.headers }); + + // let imageToBeUploaded = {}; + // let imageFileName; + + // busboy.on('file', (fieldname, file, filename, encoding, mimetype) => { + // // console.log(fieldname, file, filename, encoding, mimetype); + // if (mimetype !== 'image/jpeg' && mimetype !== 'image/png') { + // return res.status(400).json({ error: 'Wrong file type submitted' }); + // } + // // my.image.png => ['my', 'image', 'png'] + // const imageExtension = filename.split('.')[filename.split('.').length - 1]; + // // 32756238461724837.png + // imageFileName = `${Math.round( + // Math.random() * 1000000000000 + // ).toString()}.${imageExtension}`; + // const filepath = path.join(os.tmpdir(), imageFileName); + // imageToBeUploaded = { filepath, mimetype }; + // file.pipe(fs.createWriteStream(filepath)); + // }); + // busboy.on('finish', () => { + // admin + // .storage() + // .bucket(config.storageBucket) + // .upload(imageToBeUploaded.filepath, { + // resumable: false, + // metadata: { + // metadata: { + // contentType: imageToBeUploaded.mimetype + // } + // } + // }) + // .then(() => { + // const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${ + // config.storageBucket + // }/o/${imageFileName}?alt=media`; + // return db.doc(`/users/${req.user.handle}`).update({ imageUrl }); + // }) + // .then(() => { + // return res.json({ message: 'image uploaded successfully' }); + // }) + // .catch((err) => { + // console.error(err); + // return res.status(500).json({ error: 'something went wrong' }); + // }); + // }); + // busboy.end(req.rawBody); +} + exports.removeSub = (req, res) => { let new_following = []; let userRef = db.doc(`/users/${req.userData.handle}`); @@ -489,6 +747,7 @@ exports.removeSub = (req, res) => { .catch(err => { return res.status(500).json({ err }); }); + return res.status(200).json({ message: "ok" }); }); }; diff --git a/functions/index.js b/functions/index.js index 16c8708..d64c9c0 100644 --- a/functions/index.js +++ b/functions/index.js @@ -11,12 +11,14 @@ app.use(cors()); *------------------------------------------------------------------*/ const { getAuthenticatedUser, + getAllHandles, getUserDetails, getProfileInfo, login, signup, deleteUser, updateProfileInfo, + uploadProfileImage, verifyUser, unverifyUser, getUserHandles, @@ -39,14 +41,23 @@ app.delete("/delete", fbAuth, deleteUser); app.post("/getUserDetails", fbAuth, getUserDetails); +// Returns a list of all usernames +// Used for searching +app.get("/getAllHandles", fbAuth, getAllHandles); + // Returns all profile data of the currently logged in user app.get("/getProfileInfo", fbAuth, getProfileInfo); // Updates the currently logged in user's profile information app.post("/updateProfileInfo", fbAuth, updateProfileInfo); +// Returns all user data for the logged in user. +// Used when setting the state in Redux. app.get("/user", fbAuth, getAuthenticatedUser); +// Uploads a profile image +app.post("/user/image", fbAuth, uploadProfileImage); + // Verifies the user sent to the request // Must be run by the Admin user app.post("/verifyUser", fbAuth, verifyUser); @@ -70,8 +81,10 @@ app.post("/removeSub", fbAuth, removeSub); /*------------------------------------------------------------------* * handlers/post.js * *------------------------------------------------------------------*/ + const { getallPostsforUser, getallPosts, putPost, likePost, unlikePost, getLikes, quoteWithPost, quoteWithoutPost, checkforLikePost} = require("./handlers/post"); + app.get("/getallPostsforUser", fbAuth, getallPostsforUser); app.get("/getallPosts", getallPosts); @@ -87,7 +100,7 @@ app.get("/checkforLikePost/:postId", fbAuth, checkforLikePost); app.post("/quoteWithPost/:postId", fbAuth, quoteWithPost); app.post("/quoteWithoutPost/:postId", fbAuth, quoteWithoutPost); - +app.post("/getOtherUsersPosts", fbAuth, getOtherUsersPosts); /*------------------------------------------------------------------* * handlers/topic.js * diff --git a/functions/package.json b/functions/package.json index 29b3e89..04a805c 100644 --- a/functions/package.json +++ b/functions/package.json @@ -14,6 +14,7 @@ }, "dependencies": { "axios": "^0.19.0", + "busboy": "^0.3.1", "firebase": "^6.6.2", "firebase-admin": "^8.6.0", "firebase-functions": "^3.1.0", diff --git a/functions/util/fbAuth.js b/functions/util/fbAuth.js index 35253e7..d440bb9 100644 --- a/functions/util/fbAuth.js +++ b/functions/util/fbAuth.js @@ -4,12 +4,12 @@ const { admin, db } = require('./admin'); // The function will only execute if the user is logged in, or rather, they have // a valid token module.exports = (req, res, next) => { - console.log(req); - console.log(req.body); - console.log(req.headers); - console.log(req.headers.authorization); - console.log(JSON.stringify(req.body)); - console.log(JSON.stringify(req.header)); + // console.log(req); + // console.log(req.body); + // console.log(req.headers); + // console.log(req.headers.authorization); + // console.log(JSON.stringify(req.body)); + // console.log(JSON.stringify(req.header)); let idToken; diff --git a/twistter-frontend/package.json b/twistter-frontend/package.json index 2fc8943..3ac341d 100644 --- a/twistter-frontend/package.json +++ b/twistter-frontend/package.json @@ -10,6 +10,7 @@ "axios": "^0.19.0", "clsx": "^1.0.4", "create-react-app": "^3.1.2", + "fuse.js": "^3.4.6", "install": "^0.13.0", "jwt-decode": "^2.2.0", "node-pre-gyp": "^0.13.0", @@ -42,5 +43,5 @@ "last 1 safari version" ] }, - "proxy": "http://localhost:5001/twistter-e4649/us-central1/api" + "proxy": "https://us-central1-twistter-e4649.cloudfunctions.net/api" } diff --git a/twistter-frontend/src/App.js b/twistter-frontend/src/App.js index 9e29d2e..1ed56dc 100644 --- a/twistter-frontend/src/App.js +++ b/twistter-frontend/src/App.js @@ -74,7 +74,7 @@ class App extends Component { - + diff --git a/twistter-frontend/src/Userline.js b/twistter-frontend/src/Userline.js index 8c95620..6c61d6d 100644 --- a/twistter-frontend/src/Userline.js +++ b/twistter-frontend/src/Userline.js @@ -1,10 +1,10 @@ import React, { Component } from "react"; -import { BrowserRouter as Router } from 'react-router-dom'; -import Route from 'react-router-dom/Route'; +// import { BrowserRouter as Router } from 'react-router-dom'; +// import Route from 'react-router-dom/Route'; import axios from 'axios'; import Box from '@material-ui/core/Box' -import {borders} from '@material-ui/system'; -import { sizing } from '@material-ui/system'; +// import {borders} from '@material-ui/system'; +// import { sizing } from '@material-ui/system'; // var moment = require('moment'); @@ -41,7 +41,7 @@ class Userline extends Component {

Userline

- +

{sortedPosts.map((microBlog) =>

Microblog Title: {microBlog.microBlogTitle} @@ -50,7 +50,7 @@ class Userline extends Component {

Number of comments: {microBlog.commentCount}

Number of likes: {microBlog.likeCount}

Body of post: {microBlog.body} -

Tagged topics: {microBlog.microBlogTopics.join("," + " ")} +

Tagged topics: {microBlog.microBlogTopics.join(", ")}

)}

diff --git a/twistter-frontend/src/Writing_Microblogs.js b/twistter-frontend/src/Writing_Microblogs.js index 9cac7b7..70b67d0 100644 --- a/twistter-frontend/src/Writing_Microblogs.js +++ b/twistter-frontend/src/Writing_Microblogs.js @@ -1,8 +1,29 @@ import React, { Component } from "react"; -import { BrowserRouter as Router } from "react-router-dom"; -import Route from "react-router-dom/Route"; +// import { BrowserRouter as Router } from "react-router-dom"; +// import Route from "react-router-dom/Route"; import axios from "axios"; +// Material-UI +import TextField from '@material-ui/core/TextField'; +// import Typography from '@material-ui/core/Typography'; +import Button from '@material-ui/core/Button'; +import withStyles from "@material-ui/styles/withStyles"; + +const styles = { + container: { + position: "fixed" + }, + form: { + width: "300px", + height: "50px", + marginTop: "180px", + marginLeft: "50px" + }, + textField: { + marginBottom: 15 + } +} + class Writing_Microblogs extends Component { constructor(props) { super(props); @@ -27,7 +48,7 @@ class Writing_Microblogs extends Component { this.setState({ topics: event.target.value }); } - handleSubmit(event) { + handleSubmit = (event) => { // alert('A title for the microblog was inputted: ' + this.state.title + '\nA microblog was posted: ' + this.state.value); const postData = { body: this.state.value, @@ -40,20 +61,34 @@ class Writing_Microblogs extends Component { }; axios - .post("/putPost", postData, headers) + .post("/putPost", postData, headers) // TODO: add topics .then(res => { - alert("Post was shared successfully!"); + // alert("Post was shared successfully!"); console.log(res.data); }) .catch(err => { alert("An error occured."); console.error(err); }); + console.log(postData.microBlogTopics); + postData.microBlogTopics.forEach(topic => { + axios + .post("/putTopic", { + following: topic + }) + .then(res => { + console.log(res.data); + }) + .catch(err => { + console.error(err); + }); + }); event.preventDefault(); this.setState({ value: "", title: "", characterCount: 250, topics: "" }); } handleChangeforPost(event) { + this.setState({ value: event.target.value }); } @@ -64,65 +99,67 @@ class Writing_Microblogs extends Component { } render() { + const { classes } = this.props; return ( -
-
-
-