Skip to content

Instantly share code, notes, and snippets.

@fourestfire
Last active February 6, 2021 19:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fourestfire/e7d9a691f88f1cf2c3680c5e14822887 to your computer and use it in GitHub Desktop.
Save fourestfire/e7d9a691f88f1cf2c3680c5e14822887 to your computer and use it in GitHub Desktop.
Notes on common iteractions within express and sequelize

Sequelize

Quick Links

Stuck?

  • When creating instance/class methods, remember to return!
  • Instead of reaching for a findAll and then trying to chain, think about using update or destroy
  • Common methods: findById, findAll, findOrCreate, create, destroy, update
  • Update method takes ({values}, {options.where, options.returning}). When returning: true, promise will return the actual value updated, accessible via .then(data => data[1][0])
  • Hooks will take a function with the first parameter being the instance, and the second being options

Sample Code

Querying

Model.findAll({
    attributes: ['name'],
    where: {x === true},
    order: '"asdf" DESC'
  })
  .then()
  .catch(err => console.error("we have an error!", err))

Hooks

hooks: {
  beforeUpdate: function(article) {  // gets the article instance we're trying to update
    article.version++;
  }
}

Associations

  • Child.belongsTo(Parent, {as: 'alias'});
  • Model1.belongsToMany(Model2, { through: 'join_table_alias' });

Express

Quick Links

Key Elements

  1. req.params.id - '/something/:id/'
  2. req.query - not shown in route, these would be the ?s after the URI
  3. req.body - these are found from a POST
  4. res.send / res.json / res.sendStatus

Other Notes

  • After setting up our main error handler, always remember to pass .catch(next) in any route we are setting up
  • We can directly pass req.body into something like Model.create(req.body) (...instead of Model.create{ title: req.body.title })

Sample Code

Basic Get Route

app.get('/', function(req, res, next) {});

app.params

router.param(‘bookId’, function (req, res, next, id) {
 Book.findById(id)
 .then(foundBook => foundBook === null ?
   res.status(404).send(‘Not Found’) : (req.book = foundBook, next()))
 .catch(next);
});

Error Handling: Single Route

app.get('/forbidden', function(req, res, next) {
  res.sendStatus(403); // contrived, but we'll be able to send status 403 if user tries to access this
});

Error Handling: Main

app.use(function (err, req, res, next) {
  if (err) res.sendStatus(500); // general error handler. do whatever we want here
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment