Merge pull request #68 from ClaytonWWilson/delete_topic

Delete topic
This commit is contained in:
Leon Liang 2019-10-31 14:44:41 -04:00 committed by GitHub
commit 649b9b4a69
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 265 additions and 189 deletions

View File

@ -1,52 +1,61 @@
/* eslint-disable promise/always-return */ /* eslint-disable promise/always-return */
const { admin, db } = require("../util/admin"); const { admin, db } = require("../util/admin");
exports.putTopic = (req, res) => { exports.putTopic = (req, res) => {
const newTopic = {
topic: req.body.topic
};
const newTopic = { admin
topic: req.body.topic .firestore()
}; .collection("topics")
.add(newTopic)
admin.firestore().collection('topics').add(newTopic) .then(doc => {
.then((doc) => { const resTopic = newTopic;
const resTopic = newTopic; return res.status(200).json(resTopic);
newTopic.topicId = doc.id;
return res.status(200).json(resTopic);
}) })
.catch((err) => { .catch(err => {
console.error(err); console.error(err);
return res.status(500).json({ error: 'something is wrong'}); return res.status(500).json({ error: "something is wrong" });
}); });
}; };
exports.getAllTopics = (req, res) => { exports.getAllTopics = (req, res) => {
admin.firestore().collection('topics').get() admin
.then((data) => { .firestore()
let topics = []; .collection("topics")
data.forEach(function(doc) { .get()
topics.push(doc.data()); .then(data => {
let topics = [];
data.forEach(function(doc) {
topics.push({
topic: doc.data().topic,
id: doc.id
}); });
return res.status(200).json(topics); });
}) return res.status(200).json(topics);
.catch((err) => {
console.error(err);
return res.status(500).json({error: 'Failed to fetch all topics.'})
}) })
.catch(err => {
console.error(err);
return res.status(500).json({ error: "Failed to fetch all topics." });
});
}; };
exports.deleteTopic = (req, res) => { exports.deleteTopic = (req, res) => {
const topic = db.doc(`/topics/${req.params.topicId}`); const topic = db.doc(`/topics/${req.params.topicId}`);
topic.get().then((doc) => { topic
if (!doc.exists) { .get()
return res.status(404).json({error: 'Topic not found'}); .then(doc => {
} else { if (!doc.exists) {
return topic.delete(); return res.status(404).json({ error: "Topic not found" });
} } else {
return topic.delete();
}
}) })
.then(() => { .then(() => {
res.json({ message: 'Topic successfully deleted!'}); res.json({ message: "Topic successfully deleted!" });
}) })
.catch((err) => { .catch(err => {
console.error(err); console.error(err);
return res.status(500).json({error: 'Failed to delete topic.'}) return res.status(500).json({ error: "Failed to delete topic." });
}) });
} };

View File

@ -44,8 +44,7 @@ app.get("/user", fbAuth, getAuthenticatedUser);
/*------------------------------------------------------------------* /*------------------------------------------------------------------*
* handlers/post.js * * handlers/post.js *
*------------------------------------------------------------------*/ *------------------------------------------------------------------*/
const { getallPostsforUser, putPost const { getallPostsforUser, putPost } = require("./handlers/post");
} = require("./handlers/post");
app.get("/getallPostsforUser", getallPostsforUser); app.get("/getallPostsforUser", getallPostsforUser);
@ -55,11 +54,7 @@ app.post("/putPost", fbAuth, putPost);
/*------------------------------------------------------------------* /*------------------------------------------------------------------*
* handlers/topic.js * * handlers/topic.js *
*------------------------------------------------------------------*/ *------------------------------------------------------------------*/
const { const { putTopic, getAllTopics, deleteTopic } = require("./handlers/topic");
putTopic,
getAllTopics,
deleteTopic
} = require("./handlers/topic");
// add topic to database // add topic to database
app.post("/putTopic", fbAuth, putTopic); app.post("/putTopic", fbAuth, putTopic);

View File

@ -10,11 +10,11 @@ import jwtDecode from "jwt-decode";
// Redux // Redux
import { Provider } from "react-redux"; import { Provider } from "react-redux";
import store from "./redux/store"; import store from "./redux/store";
import MuiThemeProvider from '@material-ui/core/styles/MuiThemeProvider'; import MuiThemeProvider from "@material-ui/core/styles/MuiThemeProvider";
import createMuiTheme from '@material-ui/core/styles/createMuiTheme'; import createMuiTheme from "@material-ui/core/styles/createMuiTheme";
import themeObject from './util/theme'; import themeObject from "./util/theme";
import { SET_AUTHENTICATED } from './redux/types'; import { SET_AUTHENTICATED } from "./redux/types";
import { logoutUser, getUserData } from './redux/actions/userActions'; import { logoutUser, getUserData } from "./redux/actions/userActions";
// Components // Components
import AuthRoute from "./util/AuthRoute"; import AuthRoute from "./util/AuthRoute";
@ -22,21 +22,20 @@ import AuthRoute from "./util/AuthRoute";
// axios.defaults.baseURL = 'http://localhost:5006/twistter-e4649/us-central1/api'; // axios.defaults.baseURL = 'http://localhost:5006/twistter-e4649/us-central1/api';
// Pages // Pages
import home from './pages/Home'; import home from "./pages/Home";
import signup from './pages/Signup'; import signup from "./pages/Signup";
import login from './pages/Login'; import login from "./pages/Login";
import user from './pages/user'; import user from "./pages/user";
import logout from './pages/Logout'; import logout from "./pages/Logout";
import Delete from './pages/Delete'; import Delete from "./pages/Delete";
import writeMicroblog from './Writing_Microblogs.js'; import writeMicroblog from "./Writing_Microblogs.js";
import editProfile from './pages/editProfile'; import editProfile from "./pages/editProfile";
import userLine from './Userline.js'; import userLine from "./Userline.js";
const theme = createMuiTheme(themeObject); const theme = createMuiTheme(themeObject);
const token = localStorage.FBIdToken; const token = localStorage.FBIdToken;
if (token) { if (token) {
try { try {
const decodedToken = jwtDecode(token); const decodedToken = jwtDecode(token);
if (decodedToken.exp * 1000 < Date.now()) { if (decodedToken.exp * 1000 < Date.now()) {
@ -44,7 +43,7 @@ if (token) {
window.location.href = "/login"; window.location.href = "/login";
} else { } else {
store.dispatch({ type: SET_AUTHENTICATED }); store.dispatch({ type: SET_AUTHENTICATED });
axios.defaults.headers.common['Authorization'] = token; axios.defaults.headers.common["Authorization"] = token;
store.dispatch(getUserData()); store.dispatch(getUserData());
} }
} catch (invalidTokenError) { } catch (invalidTokenError) {
@ -53,33 +52,30 @@ if (token) {
} }
} }
class App extends Component { class App extends Component {
render() { render() {
return ( return (
<MuiThemeProvider theme={theme}> <MuiThemeProvider theme={theme}>
<Provider store={store}> <Provider store={store}>
<Router> <Router>
<div className='container' > <div className="container">
<Navbar /> <Navbar />
</div> </div>
<div className="app"> <div className="app">
<Switch> <Switch>
{/* AuthRoute checks if the user is logged in and if they are it redirects them to /home */} {/* AuthRoute checks if the user is logged in and if they are it redirects them to /home */}
<AuthRoute exact path="/signup" component={signup} /> <AuthRoute exact path="/signup" component={signup} />
<AuthRoute exact path="/login" component={login} /> <AuthRoute exact path="/login" component={login} />
<Route exact path="/logout" component={logout} /> <Route exact path="/logout" component={logout} />
<Route exact path="/delete" component={Delete} /> <Route exact path="/delete" component={Delete} />
<Route exact path="/user" component={user} />
<Route exact path="/home" component={writeMicroblog} />
<Route exact path="/edit" component={editProfile} />
<Route exact path="/user" component={user} /> <AuthRoute exact path="/" component={home} />
<Route exact path="/home" component={writeMicroblog} />
<Route exact path="/edit" component={editProfile} />
<AuthRoute exact path="/" component={home}/>
</Switch> </Switch>
</div> </div>
</Router> </Router>
</Provider> </Provider>
</MuiThemeProvider> </MuiThemeProvider>

View File

@ -1,11 +1,9 @@
import React, { Component } from "react"; import React, { Component } from "react";
import { BrowserRouter as Router } from 'react-router-dom'; import { BrowserRouter as Router } from "react-router-dom";
import Route from 'react-router-dom/Route'; import Route from "react-router-dom/Route";
import axios from 'axios'; import axios from "axios";
class Writing_Microblogs extends Component { class Writing_Microblogs extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
@ -24,14 +22,22 @@ class Writing_Microblogs extends Component {
} }
handleChange(event) { handleChange(event) {
this.setState( {title: event.target.value }); this.setState({ title: event.target.value });
} }
handleChangeforTopics(event) {
this.setState( {topics: event.target.value});
}
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,
userImage: "bing-url",
microBlogTitle: this.state.title,
microBlogTopics: this.state.topics.split(", ")
};
const headers = {
headers: { "Content-Type": "application/json" }
};
handleSubmit(event) { handleSubmit(event) {
const postData = { const postData = {
@ -57,51 +63,104 @@ class Writing_Microblogs extends Component {
event.preventDefault(); event.preventDefault();
this.setState({value: '', title: '',characterCount: 250, topics: ''}) this.setState({value: '', title: '',characterCount: 250, topics: ''})
} }
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,
userHandle: "new user",
userImage: "bing-url",
microBlogTitle: this.state.title,
microBlogTopics: this.state.topics.split(", ")
};
const headers = {
headers: { "Content-Type": "application/json" }
};
handleChangeforPost(event) { axios
this.setState({value: event.target.value }) .post("/putPost", postData, headers)
} .then(res => {
alert("Post was shared successfully!");
console.log(res.data);
})
.catch(err => {
alert("An error occured.");
console.error(err);
});
event.preventDefault();
this.setState({ value: "", title: "", characterCount: 250, topics: "" });
}
handleChangeforCharacterCount(event) { handleChangeforPost(event) {
const charCount = event.target.value.length this.setState({ value: event.target.value });
const charRemaining = 250 - charCount }
this.setState({characterCount: charRemaining })
}
render() { handleChangeforCharacterCount(event) {
return ( const charCount = event.target.value.length;
<div> const charRemaining = 250 - charCount;
<div style={{ width: "200px", height: "50px", marginTop: "180px", marginLeft: "50px" }}> this.setState({ characterCount: charRemaining });
<form> }
<textarea placeholder="Enter Microblog Title" value={this.state.title} required onChange={this.handleChange} cols={30} rows={1} />
</form> render() {
return (
<div>
<div
style={{
width: "200px",
height: "50px",
marginTop: "180px",
marginLeft: "50px"
}}
>
<form>
<textarea
placeholder="Enter Microblog Title"
value={this.state.title}
required
onChange={this.handleChange}
cols={30}
rows={1}
/>
</form>
</div>
<div style={{ width: "200px", height: "50px", marginLeft: "50px" }}>
<form>
<textarea
placeholder="Enter topics seperated by a comma"
value={this.state.topics}
required
onChange={this.handleChangeforTopics}
cols={40}
rows={1}
/>
</form>
</div>
<div style={{ width: "200px", marginLeft: "50px" }}>
<form onSubmit={this.handleSubmit}>
<textarea
value={this.state.value}
required
maxLength="250"
placeholder="Write Microblog here..."
onChange={e => {
this.handleChangeforPost(e);
this.handleChangeforCharacterCount(e);
}}
cols={40}
rows={20}
/>
<div style={{ fontSize: "14px", marginRight: "-100px" }}>
<p2>Characters Left: {this.state.characterCount}</p2>
</div> </div>
<div style={{ width: "200px", height: "50px", marginLeft: "50px"}} > <div style={{ marginRight: "-100px" }}>
<form> <button onClick>Share Post</button>
<textarea placeholder="Enter topics seperated by a comma" value={this.state.topics} required onChange={this.handleChangeforTopics} cols={40} rows={1} /> </div>
</form> </form>
</div> </div>
</div>
<div style={{ width: "200px", marginLeft: "50px"}}> );
<form onSubmit={this.handleSubmit}> }
<textarea value={this.state.value} required maxLength="250" placeholder= "Write Microblog here..."
onChange = { (e) => { this.handleChangeforPost(e); this.handleChangeforCharacterCount(e) } } cols={40} rows={20} />
<div style={{ fontSize: "14px", marginRight: "-100px"}} >
<p2>Characters Left: {this.state.characterCount}</p2>
</div>
<div style={{ marginRight: "-100px" }}>
<button onClick>Share Post</button>
</div>
</form>
</div>
</div>
);
}
} }
export default Writing_Microblogs; export default Writing_Microblogs;

View File

@ -1,53 +1,60 @@
/* eslint-disable */ /* eslint-disable */
import React, { Component } from 'react'; import React, { Component } from "react";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
import axios from 'axios'; import axios from "axios";
//import '../App.css'; //import '../App.css';
import { makeStyles, styled } from '@material-ui/core/styles'; import { makeStyles, styled } from "@material-ui/core/styles";
import Grid from '@material-ui/core/Grid'; import Grid from "@material-ui/core/Grid";
import Card from '@material-ui/core/Card'; import Card from "@material-ui/core/Card";
import Chip from '@material-ui/core/Chip'; import Chip from "@material-ui/core/Chip";
import Typography from "@material-ui/core/Typography"; import Typography from "@material-ui/core/Typography";
import AddCircle from '@material-ui/icons/AddCircle'; import AddCircle from "@material-ui/icons/AddCircle";
import TextField from '@material-ui/core/TextField'; import TextField from "@material-ui/core/TextField";
// component // component
import Userline from '../Userline'; import noImage from "../images/no-img.png";
import noImage from '../images/no-img.png';
const MyChip = styled(Chip)({ const MyChip = styled(Chip)({
margin: 2, margin: 2,
color: 'primary' color: "primary"
}); });
class user extends Component { class user extends Component {
state = { state = {
profile: null, profile: null,
imageUrl: null, imageUrl: null,
topics: null, topics: null,
newTopic: null newTopic: null
}; };
handleDelete = (topic) => { handleDelete = topic => {
alert(`Delete topic: ${topic}!`); axios
} .delete(`/deleteTopic/${topic.id}`)
.then(function() {
location.reload();
})
.catch(function(err) {
console.log(err);
});
};
handleAddCircle = () => { handleAddCircle = () => {
axios.post('/putTopic', { axios
topic: this.state.newTopic .post("/putTopic", {
}) topic: this.state.newTopic
.then(function () { })
location.reload(); .then(function() {
}) location.reload();
.catch(function (err) { })
console.log(err); .catch(function(err) {
}); console.log(err);
} });
};
handleChange(event) { handleChange(event) {
this.setState({ this.setState({
newTopic: event.target.value newTopic: event.target.value
}) });
} }
componentDidMount() { componentDidMount() {
@ -65,57 +72,67 @@ class user extends Component {
.then(res => { .then(res => {
this.setState({ this.setState({
topics: res.data topics: res.data
}) });
}) })
.catch(err => console.log(err)); .catch(err => console.log(err));
} }
render() { render() {
const classes = this.props;
let profileMarkup = this.state.profile ? ( let profileMarkup = this.state.profile ? (
<p> <p>
<Typography variant='h5'>{this.state.profile}</Typography>         <Typography variant="h5">{this.state.profile}</Typography>
</p>) : (<p>loading username...</p>);       
</p>
) : (
<p>loading username...</p>
);
let topicsMarkup = this.state.topics ? ( let topicsMarkup = this.state.topics ? (
this.state.topics.map(topic => <MyChip this.state.topics.map(
label={{topic}.topic.topic} topic => (
key={{topic}.topic.topicId} <MyChip
onDelete={ (topic) => this.handleDelete(topic)}/>) label={{ topic }.topic.topic}
) : (<p> loading topics...</p>); key={{ topic }.topic.id}
onDelete={key => this.handleDelete(topic)}
/>
) // console.log({ topic }.topic.id)
)
) : (
<p> loading topics...</p>
);
let imageMarkup = this.state.imageUrl ? ( let imageMarkup = this.state.imageUrl ? (
<img <img src={this.state.imageUrl} height="250" width="250" />
src={this.state.imageUrl} ) : (
height="250" <img src={noImage} />
width="250" );
/>
) : (<img src={noImage}/>);
return ( return (
<Grid container spacing={16}> <Grid container spacing={16}>
        
<Grid item sm={8} xs={12}> <Grid item sm={8} xs={12}>
<p>Post</p>           <p>Post</p>
        
</Grid> </Grid>
        
<Grid item sm={4} xs={12}> <Grid item sm={4} xs={12}>
{imageMarkup}           {imageMarkup}
{profileMarkup}           {profileMarkup}
{topicsMarkup}           {topicsMarkup}
          
<TextField <TextField
id="newTopic" id="newTopic"
label="new topic" label="new topic"
defaultValue="" defaultValue=""
margin="normal" margin="normal"
variant="outlined" variant="outlined"
value={this.state.newTopic} value={this.state.newTopic}
onChange={ (event) => this.handleChange(event)} onChange={event => this.handleChange(event)}
/>
<AddCircle
color="primary"
clickable
onClick={this.handleAddCircle}
/> />
          
<AddCircle color="primary" clickable onClick={this.handleAddCircle} />
        
</Grid> </Grid>
      
</Grid> </Grid>
); );
} }