Reformat code

This commit is contained in:
Leon Liang 2019-10-27 02:53:12 -04:00
parent 1c81ae1663
commit 13a1401759
5 changed files with 258 additions and 224 deletions

View File

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

View File

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

View File

@ -10,27 +10,27 @@ import jwtDecode from "jwt-decode";
// Redux
import { Provider } from "react-redux";
import store from "./redux/store";
import MuiThemeProvider from '@material-ui/core/styles/MuiThemeProvider';
import createMuiTheme from '@material-ui/core/styles/createMuiTheme';
import themeObject from './util/theme';
import { SET_AUTHENTICATED } from './redux/types';
import { logoutUser, getUserData } from './redux/actions/userActions';
import MuiThemeProvider from "@material-ui/core/styles/MuiThemeProvider";
import createMuiTheme from "@material-ui/core/styles/createMuiTheme";
import themeObject from "./util/theme";
import { SET_AUTHENTICATED } from "./redux/types";
import { logoutUser, getUserData } from "./redux/actions/userActions";
// Components
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
import home from './pages/Home';
import signup from './pages/Signup';
import login from './pages/Login';
import user from './pages/user';
import logout from './pages/Logout';
import Delete from './pages/Delete';
import writeMicroblog from './Writing_Microblogs.js';
import editProfile from './pages/editProfile';
import userLine from './Userline.js';
import home from "./pages/Home";
import signup from "./pages/Signup";
import login from "./pages/Login";
import user from "./pages/user";
import logout from "./pages/Logout";
import Delete from "./pages/Delete";
import writeMicroblog from "./Writing_Microblogs.js";
import editProfile from "./pages/editProfile";
import userLine from "./Userline.js";
const theme = createMuiTheme(themeObject);
@ -42,39 +42,37 @@ if (token) {
window.location.href = "/login";
} else {
store.dispatch({ type: SET_AUTHENTICATED });
axios.defaults.headers.common['Authorization'] = token;
axios.defaults.headers.common["Authorization"] = token;
store.dispatch(getUserData());
}
}
class App extends Component {
render() {
return (
<MuiThemeProvider theme={theme}>
<Provider store={store}>
<Router>
<div className='container' >
<div className="container">
<Navbar />
</div>
<div className="app">
<Switch>
{/* 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="/login" component={login} />
<Route exact path="/logout" component={logout} />
<Route exact path="/delete" component={Delete} />
{/* 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="/login" component={login} />
<Route exact path="/logout" component={logout} />
<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={userLine} /> */}
<Route exact path="/user" component={user} />
<Route exact path="/home" component={writeMicroblog} />
<Route exact path="/edit" component={editProfile} />
{/* <Route exact path="/user" component={userLine} /> */}
<AuthRoute exact path="/" component={home}/>
<AuthRoute exact path="/" component={home} />
</Switch>
</div>
</Router>
</Provider>
</MuiThemeProvider>

View File

@ -1,108 +1,129 @@
import React, { Component } from "react";
import { BrowserRouter as Router } from 'react-router-dom';
import Route from 'react-router-dom/Route';
import axios from 'axios';
import { BrowserRouter as Router } from "react-router-dom";
import Route from "react-router-dom/Route";
import axios from "axios";
class Writing_Microblogs extends Component {
constructor(props) {
super(props);
this.state = {
value: "",
title: "",
topics: "",
characterCount: 250
};
constructor(props) {
super(props);
this.state = {
value: '',
title: '',
topics: '',
characterCount: 250
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeforPost = this.handleChangeforPost.bind(this);
this.handleChangeforTopics = this.handleChangeforTopics.bind(this);
}
};
handleChange(event) {
this.setState({ title: event.target.value });
}
handleChangeforTopics(event) {
this.setState({ topics: event.target.value });
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeforPost = this.handleChangeforPost.bind(this);
this.handleChangeforTopics = this.handleChangeforTopics.bind(this);
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" }
};
}
axios
.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: "" });
}
handleChange(event) {
this.setState( {title: event.target.value });
}
handleChangeforPost(event) {
this.setState({ value: event.target.value });
}
handleChangeforTopics(event) {
this.setState( {topics: event.target.value});
}
handleChangeforCharacterCount(event) {
const charCount = event.target.value.length;
const charRemaining = 250 - charCount;
this.setState({ characterCount: charRemaining });
}
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'}
}
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>
axios
.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: ''})
}
handleChangeforPost(event) {
this.setState({value: event.target.value })
}
handleChangeforCharacterCount(event) {
const charCount = event.target.value.length
const charRemaining = 250 - charCount
this.setState({characterCount: charRemaining })
}
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 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={{ 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 style={{ marginRight: "-100px" }}>
<button onClick>Share Post</button>
</div>
</form>
</div>
</div>
);
}
<div style={{ marginRight: "-100px" }}>
<button onClick>Share Post</button>
</div>
</form>
</div>
</div>
);
}
}
export default Writing_Microblogs;

View File

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