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 */ /* 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 = { const newTopic = {
topic: req.body.topic topic: req.body.topic,
topicId: null
}; };
admin.firestore().collection('topics').add(newTopic) admin
.then((doc) => { .firestore()
.collection("topics")
.add(newTopic)
.then(doc => {
const resTopic = newTopic; const resTopic = newTopic;
newTopic.topicId = doc.id; newTopic.topicId = doc.id;
return res.status(200).json(resTopic); 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()
.collection("topics")
.get()
.then(data => {
let topics = []; let topics = [];
data.forEach(function(doc) { data.forEach(function(doc) {
topics.push(doc.data()); topics.push(doc.data());
}); });
return res.status(200).json(topics); return res.status(200).json(topics);
}) })
.catch((err) => { .catch(err => {
console.error(err); console.error(err);
return res.status(500).json({error: 'Failed to fetch all topics.'}) 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
.get()
.then(doc => {
if (!doc.exists) { if (!doc.exists) {
return res.status(404).json({error: 'Topic not found'}); return res.status(404).json({ error: "Topic not found" });
} else { } else {
return topic.delete(); 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,27 +10,27 @@ 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";
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);
@ -42,19 +42,18 @@ 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());
} }
} }
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>
@ -71,10 +70,9 @@ class App extends Component {
<Route exact path="/edit" component={editProfile} /> <Route exact path="/edit" component={editProfile} />
{/* <Route exact path="/user" component={userLine} /> */} {/* <Route exact path="/user" component={userLine} /> */}
<AuthRoute exact path="/" component={home}/> <AuthRoute exact path="/" component={home} />
</Switch> </Switch>
</div> </div>
</Router> </Router>
</Provider> </Provider>
</MuiThemeProvider> </MuiThemeProvider>

View File

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

View File

@ -1,23 +1,23 @@
/* 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 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 {
@ -25,29 +25,41 @@ class user extends Component {
profile: null, profile: null,
imageUrl: null, imageUrl: null,
topics: null, topics: null,
newTopic: null newTopic: null,
deleteTopic: null
}; };
handleDelete = (topic) => { handleDelete = () => {
alert(`Delete topic: ${topic}!`); // axios
} // .delete(`/deleteTopic/${topic}`)
// .then(
// function (response) {
// console.log(response);
// }
// )
// .catch(function (err) {
// console.log(err);
// });
alert(`Delete topic: ${this.state.deleteTopic}!`);
};
handleAddCircle = () => { handleAddCircle = () => {
axios.post('/putTopic', { axios
.post("/putTopic", {
topic: this.state.newTopic topic: this.state.newTopic
}) })
.then(function () { .then(function() {
location.reload(); location.reload();
}) })
.catch(function (err) { .catch(function(err) {
console.log(err); console.log(err);
}); });
} };
handleChange(event) { handleChange(event) {
this.setState({ this.setState({
newTopic: event.target.value newTopic: event.target.value
}) });
} }
componentDidMount() { componentDidMount() {
@ -65,32 +77,36 @@ 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(topic => (
label={{topic}.topic.topic} <MyChip
key={{topic}.topic.topicId} label={{ topic }.topic.topic}
onDelete={ (topic) => this.handleDelete(topic)}/>) key={{ topic }.topic.topicId}
) : (<p> loading topics...</p>); onDelete={this.handleDelete}
/>
))
) : (
<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}>
@ -108,13 +124,9 @@ class user extends Component {
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>
); );