logicp 6 years ago
parent
commit
76db486067
3 changed files with 100 additions and 19 deletions
  1. 52 4
      src/form.js
  2. BIN
      src/invite.jpeg
  3. 48 15
      src/server/index.js

+ 52 - 4
src/form.js

@@ -42,17 +42,28 @@ const cats = [
   'King of the Jungle',
   'Incel cat',
   'C-ch-at-d',
+  'Sabretooth Bro',
+  'Higher order being',
   'Decadent feline',
   'Trapped in the litter box',
   'All claw and no meow'
 ]
 
+const MakeAttendees = (attendees) => {
+  const items = []
+  for (let i = 0; i < attendees.length; i++) {
+    items.push(<div style={{flex: 1}}key={i}>{i+1}: <div><bold>Name:</bold> {attendees[i].name}</div><div><bold>Type: </bold>{attendees[i].cat ? attendees[i].cat : 'Incel, for sure'}</div><div><bold>Lonely: </bold>{attendees[i].guest ? 'Probably' : 'Very!'}</div><br /><br /></div>)
+  }
+  return (<div style={{display: 'block', color: 'black', fontSize: '50%'}}>{items}</div>)
+}
+
 
 class TextFields extends React.Component {
   state = {
     name: 'The Grinch',
     cat: '',
-    significantOther: false
+    significantOther: false,
+    attendees: undefined
   };
 
   handleChange = name => event => {
@@ -80,16 +91,43 @@ class TextFields extends React.Component {
 
   submitForm = async () => {
     console.log(this.state)
-    const response = await fetch('http://localhost:3002/test', {
-      method: 'get'
+    const body = JSON.stringify({
+      name: this.state.name,
+      cat: this.state.cat,
+      significantOther: this.state.significantOther,
+    })
+
+    const response = await fetch('http://localhost:3002/attendee', {
+      method: 'post',
+      body: body,
+      headers: new Headers({
+        'Content-Type': 'application/json'
+      })
     })
     console.log(response)
   }
 
+  fetchAttendees = async () => {
+    return await fetch('http://localhost:3002/list', {
+      method: 'get',
+    })
+  }
+
+  updateAttendees = async () => {
+    const attendees = await this.fetchAttendees().then(data => {
+      data.json().then(finalData => {
+        if ('attendees' in finalData) {
+          this.setState({ attendees: MakeAttendees(finalData.attendees)})
+        }
+      })
+    })
+  }
+
   render() {
     const { classes } = this.props;
 
     return (
+      <div>
       <form className={classes.container} noValidate autoComplete="off">
       <div style={styles.fullWidth}>
           <InputLabel htmlFor="attendee-name">Who do you think you are?</InputLabel>
@@ -118,7 +156,7 @@ class TextFields extends React.Component {
           <FormControl className='food-select'>
             <InputLabel htmlFor="food-helper">What sort of cat are you?</InputLabel>
             <Select
-              value={this.state.foodItem}
+              value={this.state.cat}
               onChange={this.handleFoodSelect}
               input={<Input name="food" id="food-helper" value={this.state.foodItem}/>}
             >
@@ -132,7 +170,17 @@ class TextFields extends React.Component {
           <br />
           <Button style={{marginTop: '1.25em'}}onClick={this.submitForm}> Click to Confirm Attendance </Button>
 
+          <br />
+          <br />
+          <Button style={{marginTop: '1.25em'}}onClick={this.updateAttendees}> Who's coming? </Button>
+
+          <br />
+          <br /><br />
+          <br /><br />
+          <br />
       </form>
+      {this.state.attendees}
+      </div>
     );
   }
 }

BIN
src/invite.jpeg


+ 48 - 15
src/server/index.js

@@ -12,12 +12,14 @@ const database = new Sequelize({
 const Attendee = database.define('attendee', {
   name: Sequelize.STRING,
   guest: Sequelize.BOOLEAN,
+  cat: Sequelize.STRING
 });
 
-const whitelist = ['http://localhost:3001', '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) {
+    console.log('request attempted from ', origin)
     if (whitelist.indexOf(origin) !== -1) {
       callback(null, true)
     } else {
@@ -37,7 +39,7 @@ class App {
     middleware() {
         // this.express.use(logger('dev'));
         this.express.use(bodyParser.json());
-        this.express.use(bodyParser.urlencoded({ extended: false }));
+        this.express.use(bodyParser.urlencoded({ extended: true }));
         // this.express.engine('html', require('ejs').renderFile);
     }
     // Configure API endpoints.
@@ -50,20 +52,37 @@ class App {
           res.json({response: 'yo mamma'})
         })
 
-        this.express.post('/attendee', (req, res) => {
-          console.log(req.body)
-          // Attendee.findOrCreate({ name: 'Emmanuel', guest: true }).then(() =>
-          Attendee.findOrCreate({
-            where: {
-              name: 'Emmanuel'
-            }, defaults: {name: 'Emmanuel', guest: true}
-          })
-          .spread((param1, param2) => {
-            console.log('Param 1')
-            console.log(param1)
-            console.log('Param 2')
-            console.log(param2)
+        this.express.get('/list', cors(corsOptions), (req, res) => {
+          Attendee.findAll().then(attendees => {
+            res.json({attendees: attendees})
           })
+        })
+
+        this.express.post('/attendee', cors(corsOptions), (req, res) => {
+          console.log(req.body)
+          if ('name' in req.body) {
+            Attendee.findOrCreate({
+              where: {
+                name: req.body.name
+              }
+            })
+            .spread( attendee => {
+              console.log(attendee)
+              attendee.guest = req.body.significantOther
+              attendee.cat = req.body.cat
+              Attendee.update({
+                name: req.body.name,
+                cat: req.body.cat,
+                guest: req.body.significantOther
+              }, {
+                where: {
+                  id: attendee.id
+                }
+              }).then( attendee => {
+                console.log('Successfully updated attendee:', attendee)
+              })
+            })
+          }
           res.json({response: 'yeah we got you'})
         })
     }
@@ -72,6 +91,20 @@ class App {
 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.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}`);