logicp 5 years ago
parent
commit
6d7c3fba6d
2 changed files with 289 additions and 201 deletions
  1. 204 127
      src/form.js
  2. 85 74
      src/server/index.js

+ 204 - 127
src/form.js

@@ -1,195 +1,272 @@
-import React from 'react';
-import PropTypes from 'prop-types';
-import { withStyles } from '@material-ui/core/styles';
-import MenuItem from '@material-ui/core/MenuItem';
-import TextField from '@material-ui/core/TextField';
-import Select from '@material-ui/core/Select';
-import { Button } from '@material-ui/core'
-import { FormControl, Input, InputLabel, FormHelperText } from '@material-ui/core'
-import { black } from 'ansi-colors';
-
+import React from "react";
+import PropTypes from "prop-types";
+import { withStyles } from "@material-ui/core/styles";
+import MenuItem from "@material-ui/core/MenuItem";
+import TextField from "@material-ui/core/TextField";
+import Select from "@material-ui/core/Select";
+import { Button } from "@material-ui/core";
+import {
+  FormControl,
+  Input,
+  InputLabel,
+  FormHelperText
+} from "@material-ui/core";
+import { black } from "ansi-colors";
 
 const styles = theme => ({
   container: {
-    display: 'inline',
+    display: "inline"
   },
   textField: {
     marginLeft: theme.spacing.unit,
     marginRight: theme.spacing.unit,
-    display: 'inline-block',
+    display: "inline-block",
     width: 200
   },
   menu: {
-    width: 200,
+    width: 200
   },
   fullWidth: {
-    width: '100%',
-    textAlign: 'left'
+    width: "100%",
+    textAlign: "left"
   },
   blackText: {
-    color: 'black'
+    color: "black"
   },
   floatLeft: {
-    float: 'left',
-    display: 'inline'
+    float: "left",
+    display: "inline"
   }
 });
 
 const superheroes = [
-  'Sabre Claus',
-  'Rudolph Mistletoe',
-  'Mr. Frosty',
-  'Scrooge',
-  'John McClane',
-  'Midnight Snacking Gremlin',
-  'Grinch',
-  'Tiny Tim',
-  'Jesus'
-]
-
-const partyHosts = ['In-Young', 'Emmanuel']
-
-const MakeAttendees = (attendees) => {
-  const items = []
+  "Sabre Claus",
+  "Rudolph Mistletoe",
+  "Mr. Frosty",
+  "Scrooge",
+  "John McClane",
+  "Midnight Snacking Gremlin",
+  "Grinch",
+  "Tiny Tim",
+  "Jesus"
+];
+
+const partyHosts = ["In-Young", "Emmanuel"];
+
+const MakeAttendees = attendees => {
+  debugger;
+  const items = [];
   if (attendees) {
     for (let i = 0; i < attendees.length; i++) {
-      items.push(<div style={{flex: 1}}key={i}>{i+1}. <div>Name: <span className='attendee-name'>{attendees[i].name}</span></div><div>Type: <span className='attendee-name'>{attendees[i].superhero ? attendees[i].superhero : 'The Villain of All Things Christmas'}</span></div>{partyHosts.indexOf(attendees[i].name) < 0 && attendees[i].guest ? <div><span className='attendee-name'> ...with an extra guest!! ;)</span> </div> : '' }
-      <br /><br /></div>)
+      console.log(attendees[i].guest);
+      items.push(
+        <div style={{ flex: 1 }} key={i}>
+          {i + 1}.{" "}
+          <div>
+            Name: <span className="attendee-name">{attendees[i].name}</span>
+          </div>
+          <div>
+            Type:{" "}
+            <span className="attendee-name">
+              {attendees[i].superhero
+                ? attendees[i].superhero
+                : "The Villain of All Things Christmas"}
+            </span>
+          </div>
+          {attendees[i].guest ? (
+            <div>
+              <span className="attendee-name">
+                {" "}
+                ...with an extra guest!! ;)
+              </span>{" "}
+            </div>
+          ) : (
+            ""
+          )}
+          <br />
+          <br />
+        </div>
+      );
     }
   }
-  return (<div style={{display: 'block', color: 'black', fontSize: '50%', textAlign: 'left'}}>{items}</div>)
-}
-
+  return (
+    <div
+      style={{
+        display: "block",
+        color: "black",
+        fontSize: "50%",
+        textAlign: "left"
+      }}
+    >
+      {items}
+    </div>
+  );
+};
 
 class TextFields extends React.Component {
-
-  constructor (props) {
-    super(props)
+  constructor(props) {
+    super(props);
     this.state = {
-      name: '',
-      superhero: '',
+      name: "",
+      superhero: "",
       significantOther: false,
-      attendees: undefined
-    }
+      attendees: []
+    };
   }
 
-  async componentDidMount () {
+  async componentDidMount() {
     this.setState({
       attendees: MakeAttendees(await this.fetchAttendees())
-    })
+    });
   }
 
   handleChange = name => event => {
     this.setState({
-      [name]: event.target.value,
+      [name]: event.target.value
     });
   };
 
-  handleFoodSelect = (event) => {
-    this.setState({superhero: event.target.value})
-  }
+  handleFoodSelect = event => {
+    this.setState({ superhero: event.target.value });
+  };
 
   handleSignificantOther = () => {
-    this.setState({significantOther: !this.state.significantOther})
-  }
+    const value = !this.state.significantOther;
+    console.log(value);
+    this.setState({ significantOther: !this.state.significantOther });
+  };
 
   Superheroes = () => {
-    const items = []
+    const items = [];
     for (let i = 0; i < superheroes.length; i++) {
-      items.push(<MenuItem key={i} value={superheroes[i]}>{superheroes[i]}</MenuItem>)
+      items.push(
+        <MenuItem key={i} value={superheroes[i]}>
+          {superheroes[i]}
+        </MenuItem>
+      );
     }
 
-    return items
-  }
+    return items;
+  };
 
   submitForm = async () => {
     if (this.state.name && this.state.name.length > 0) {
       const body = JSON.stringify({
         name: this.state.name,
         superhero: this.state.superhero,
-        guest: this.state.significantOther,
-      })
+        guest: this.state.significantOther
+      });
+      console.log(body);
 
-      const response = await fetch('/attendee', {
-        method: 'post',
+      const response = await fetch("/attendee", {
+        method: "post",
         body: body,
         headers: new Headers({
-          'Content-Type': 'application/json'
+          "Content-Type": "application/json"
         })
-      })
+      });
 
       if (!response.error) {
-        console.log('Success')
-        this.setState({attendees: MakeAttendees(await this.fetchAttendees())})
-        addHugeAssImage()
+        console.log("Success");
+
+        this.setState({
+          attendees: MakeAttendees(await this.fetchAttendees())
+        });
+        addHugeAssImage();
       }
     }
-  }
+  };
 
   fetchAttendees = async () => {
-    let attendees
-    await fetch('/list', {
-      method: 'get',
-    }).then(data => {
-      data.json().then(finalData => {
-          attendees = finalData.attendees
-      })
-    })
-    return attendees
-  }
+    let attendees;
+    await fetch("/list", {
+      method: "get"
+    }).then(async data => {
+      attendees = (await data.json()).attendees;
+    });
+    return attendees;
+  };
 
   updateAttendees = async () => {
-    this.setState({ attendees: MakeAttendees(await this.fetchAttendees())})
-  }
+    this.setState({ attendees: MakeAttendees(await this.fetchAttendees()) });
+  };
 
   render() {
     const { classes } = this.props;
 
     return (
-      <div id='form-wrap'>
-      <form className={classes.container} noValidate autoComplete="off">
-      <div className='name-wrap' id='name-wrap' style={styles.fullWidth}>
-          <InputLabel id='name-label' htmlFor="attendee-name">Name</InputLabel>
-
-          <TextField
-            id="attendee-name"
-            label=""
-            className={classes.textField}
-            value={this.state.name}
-            onChange={this.handleChange('name')}
-            margin="normal"
-          />
-      </div>
-      <FormControl className='food-select'>
-        <InputLabel htmlFor="food-helper">Your ultimate celebrative festivian of the season</InputLabel>
-        <Select
-          value={this.state.cat}
-          onChange={this.handleFoodSelect}
-          input={<Input name="food" id="food-helper" value={this.state.foodItem}/>}>
-          <MenuItem value="">
-            <em>The hell you talking about</em>
-          </MenuItem>
-          {this.Superheroes()}
-        </Select>
-        <FormHelperText>Your courage is needed to maximize festivities</FormHelperText>
-      </FormControl>
-      <div style={styles.fullWidth}>
-      <br />
-        <InputLabel htmlFor="significant-other" style={{float: 'left'}}>Bringing someone?</InputLabel>
-        <input
-            id="significant-other"
-            name="Significant Other"
-            type="checkbox"
-            className={classes.textField}
-            style={{verticalAlign: 'top'}}
-            checked={this.state.significantOther}
-            onChange={this.handleSignificantOther} />
-      </div>
+      <div id="form-wrap">
+        <form className={classes.container} noValidate autoComplete="off">
+          <div className="name-wrap" id="name-wrap" style={styles.fullWidth}>
+            <InputLabel id="name-label" htmlFor="attendee-name">
+              Name
+            </InputLabel>
+
+            <TextField
+              id="attendee-name"
+              label=""
+              className={classes.textField}
+              value={this.state.name}
+              onChange={this.handleChange("name")}
+              margin="normal"
+            />
+          </div>
+          <FormControl className="food-select">
+            <InputLabel htmlFor="food-helper">
+              Your ultimate celebrative festivian of the season
+            </InputLabel>
+            <Select
+              value={this.state.superhero}
+              onChange={this.handleFoodSelect}
+              input={
+                <Input
+                  name="food"
+                  id="food-helper"
+                  value={this.state.foodItem}
+                />
+              }
+            >
+              <MenuItem value="">
+                <em>The hell you talking about</em>
+              </MenuItem>
+              {this.Superheroes()}
+            </Select>
+            <FormHelperText>
+              Your courage is needed to maximize festivities
+            </FormHelperText>
+          </FormControl>
+          <div style={styles.fullWidth}>
+            <br />
+            <InputLabel htmlFor="significant-other" style={{ float: "left" }}>
+              Bringing someone?
+            </InputLabel>
+            <input
+              id="significant-other"
+              name="Significant Other"
+              type="checkbox"
+              className={classes.textField}
+              style={{ verticalAlign: "top" }}
+              checked={this.state.significantOther}
+              onChange={this.handleSignificantOther}
+            />
+          </div>
           <br />
-          <Button onClick={this.submitForm}> Click to Confirm Attendance </Button>
+          <Button onClick={this.submitForm}>
+            {" "}
+            Click to Confirm Attendance{" "}
+          </Button>
           <br />
-      </form>
-      <h5 style={{color: '#901a23', marginTop: '24px', marginBottom: '16px', padding: '4px'}}>Such lovely people, these:</h5>
+        </form>
+        <h5
+          style={{
+            color: "#901a23",
+            marginTop: "24px",
+            marginBottom: "16px",
+            padding: "4px"
+          }}
+        >
+          Such lovely people, these:
+        </h5>
         {this.state.attendees}
       </div>
     );
@@ -198,15 +275,15 @@ class TextFields extends React.Component {
 
 function addHugeAssImage() {
   setTimeout(() => {
-    const image = document.createElement('img')
-    image.id ='hugeAssImage'
-    image.src = require('./santa-sack.jpg')
-    document.getElementById('form-wrap').appendChild(image)
-  }, 1200)
+    const image = document.createElement("img");
+    image.id = "hugeAssImage";
+    image.src = require("./santa-sack.jpg");
+    document.getElementById("form-wrap").appendChild(image);
+  }, 1200);
 }
 
 TextFields.propTypes = {
-  classes: PropTypes.object.isRequired,
+  classes: PropTypes.object.isRequired
 };
 
 export default withStyles(styles)(TextFields);

+ 85 - 74
src/server/index.js

@@ -1,21 +1,26 @@
-const Sequelize = require('sequelize');
+const Sequelize = require("sequelize");
 const express = require("express");
 const bodyParser = require("body-parser");
 // const cors = require('cors')
-require('dotenv').config({ path: '.env.local' });
+require("dotenv").config({ path: ".env.local" });
 
 const database = new Sequelize({
-  dialect: 'sqlite',
-  storage: './xmas.sqlite',
+  dialect: "sqlite",
+  storage: "./xmas.sqlite"
 });
 
-const Attendee = database.define('attendee', {
+const Attendee = database.define("attendee", {
   name: Sequelize.STRING,
   guest: Sequelize.BOOLEAN,
   superhero: Sequelize.STRING
 });
 
-const whitelist = ['http://localhost:3001', 'http://localhost', 'http://127.0.0.1', 'http://christmas.logicp.ca']
+const whitelist = [
+  "http://localhost:3001",
+  "http://localhost",
+  "http://127.0.0.1",
+  "http://christmas.logicp.ca"
+];
 
 // const corsOptions = {
 //   origin: function (origin, callback) {
@@ -29,83 +34,89 @@ const whitelist = ['http://localhost:3001', 'http://localhost', 'http://127.0.0.
 // }
 
 class App {
-    //Run configuration methods on the Express instance.
-    constructor() {
-        this.express = express();
-        this.middleware();
-        this.routes();
-    }
-    // Configure Express middleware.
-    middleware() {
-        // this.express.use(logger('dev'));
-        this.express.use(bodyParser.json());
-        this.express.use(bodyParser.urlencoded({ extended: true }));
-        // this.express.engine('html', require('ejs').renderFile);
-    }
-    // Configure API endpoints.
-    routes() {
-        /* This is just to get up and running, and to make sure what we've got is
-         * working so far. This function will change when we start to add more
-         * API endpoints */
-        this.express.get('/test', (req, res) => {
-          console.log(req)
-          res.json({response: 'yo mamma'})
-        })
+  //Run configuration methods on the Express instance.
+  constructor() {
+    this.express = express();
+    this.middleware();
+    this.routes();
+  }
+  // Configure Express middleware.
+  middleware() {
+    // this.express.use(logger('dev'));
+    this.express.use(bodyParser.json());
+    this.express.use(bodyParser.urlencoded({ extended: true }));
+    // this.express.engine('html', require('ejs').renderFile);
+  }
+  // Configure API endpoints.
+  routes() {
+    /* This is just to get up and running, and to make sure what we've got is
+     * working so far. This function will change when we start to add more
+     * API endpoints */
+    this.express.get("/test", (req, res) => {
+      console.log(req);
+      res.json({ response: "yo mamma" });
+    });
 
-        this.express.get('/list', (req, res) => {
-          Attendee.findAll().then(attendees => {
-            res.json({attendees: attendees})
-          })
-        })
+    this.express.get("/list", (req, res) => {
+      Attendee.findAll().then(attendees => {
+        res.json({ attendees: attendees });
+      });
+    });
 
-        this.express.post('/attendee', (req, res) => {
-          console.log(req.body)
-          if ('name' in req.body) {
-            Attendee.findOrCreate({
+    this.express.post("/attendee", (req, res) => {
+      console.log(req.body);
+      if ("name" in req.body) {
+        Attendee.findOrCreate({
+          where: {
+            name: req.body.name
+          }
+        }).spread(attendee => {
+          console.log("Attendee!!:");
+          console.log(req.body);
+          attendee.guest = req.body.guest;
+          attendee.superhero = req.body.superhero;
+          Attendee.update(
+            {
+              name: req.body.name,
+              superhero: req.body.superhero,
+              guest: req.body.guest
+            },
+            {
               where: {
-                name: req.body.name
+                id: attendee.id
               }
-            })
-            .spread( attendee => {
-              console.log(attendee)
-              attendee.guest = req.body.significantOther
-              attendee.superhero = req.body.superhero
-              Attendee.update({
-                name: req.body.name,
-                superhero: req.body.superhero,
-                guest: req.body.significantOther
-              }, {
-                where: {
-                  id: attendee.id
-                }
-              }).then( attendee => {
-                console.log('Successfully updated attendee:', attendee)
-                res.json({response: 'success', code: 200, error: false})
-              })
-            })
-          }
-        })
-    }
+            }
+          ).then(attendee => {
+            console.log("Successfully updated attendee:", attendee);
+            res.json({ response: "success", code: 200, error: false });
+          });
+        });
+      }
+    });
+  }
 }
 
-const app = new App().express
+const app = new App().express;
 
-app.listen(3002)
- app.options('/attendee', function (req, res) {
-   res.setHeader("Access-Control-Allow-Origin", whitelist.join('|'));
-   res.setHeader('Access-Control-Allow-Methods', '*');
-   res.setHeader("Access-Control-Allow-Headers", "*");
-   res.end();
+app.listen(3002);
+app.options("/attendee", function(req, res) {
+  res.setHeader("Access-Control-Allow-Origin", whitelist.join("|"));
+  res.setHeader("Access-Control-Allow-Methods", "*");
+  res.setHeader("Access-Control-Allow-Headers", "*");
+  res.end();
 });
 
- app.all('*', function(req, res, next) {
-   if (whitelist.indexOf(req.headers.origin) >= 0){
-       res.header("Access-Control-Allow-Origin", req.headers.origin);
-   }
-   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
-   next();
- })
+app.all("*", function(req, res, next) {
+  if (whitelist.indexOf(req.headers.origin) >= 0) {
+    res.header("Access-Control-Allow-Origin", req.headers.origin);
+  }
+  res.header(
+    "Access-Control-Allow-Headers",
+    "Origin, X-Requested-With, Content-Type, Accept"
+  );
+  next();
+});
 
 database.sync().then(() => {
-    console.log(`Listening on port ${3002}`);
+  console.log(`Listening on port ${3002}`);
 });