Skip to content

Instantly share code, notes, and snippets.

@sjkillen
Created February 15, 2017 03:25
Show Gist options
  • Save sjkillen/49edba63dcedf728af2192990b518933 to your computer and use it in GitHub Desktop.
Save sjkillen/49edba63dcedf728af2192990b518933 to your computer and use it in GitHub Desktop.
const express = require("express"),
Sequelize = require("sequelize"),
body = require("body-parser");
const { STRING, DATE, Model, Instance } = Sequelize;
// Connect to db
const db = new Sequelize("CONNECTION STRING GOES HERE", {
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 10000
},
define: { freezeTableName: true }
});
const app = express();
// Schema for logins
const Login = db.define("LOGIN_SPENCER", {
email: {
type: STRING,
primaryKey: true,
validate: {
// makes sure its an email
isEmail: true
}
},
username: {
type: STRING,
validate: {
// max/min lengths
max: 30,
min: 2
}
},
password: {
type: STRING,
validate: {
max: 30,
min: 2
}
},
branch: {
type: DATE,
validate: {
max: 50,
min: 1
}
}
});
// Creates tables, dropping if nessessary lol
db.sync({ force: true }).then(() => {
})
.then(() => {
// For json requests req.body will get converted to an object
app.use("/", body.json());
// get list of users
app.get("/users", (req, res, next) => {
Login.findAll()
// If sucessfull, send the data
.then(data => res.json(data))
// If failure continue to error handler
.catch(err => next(err));
});
// get a single user
app.get("/user/:id", (req, res, next) => {
// dynamically use the id from the url
Login.findOne({
where: {
email: req.params.id
}
})
// If sucessfull, send the data
.then(data => res.json(data))
// If failure continue to error handler
.catch(err => next(err));
});
// delete a single user
app.delete("/user/:id", (req, res, next) => {
});
// update a single user
app.put("/user/:id", (req, res, next) => {
// dynamically use the id from the url
Login.findOne({
where: {
email: req.params.id
}
})
// If sucessfull edit the model
.then(instance => instance.update(req.body))
// when update finishes, tell user
.then(() => res.json("SUCEEDS"))
// If either of last two steps fail, continue to error handler
.catch(err => next(err));
});
// create a user
app.post("/user", (req, res, next) => {
// create a user with the posted json
// validation / sanitization performed as well
Login.create(req.body)
// If sucessfull, tell the user it was
.then(() => res.json("It was a suceeds!"))
// If failure continue to error handler
.catch(err => next(err));
});
// send a helpful error message if any catch is triggered
app.use("/", (err, req, res, next) => {
// HTTP 500
res.status(500);
res.json({"important massage": "SHIIIIT! IT BORKED!!!", other_thing: err});
});
// Start http server on port 80
app.listen(80, () => {
console.log("Listening on port 80");
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment