Skip to content

Instantly share code, notes, and snippets.

@chris-jamieson
Created November 26, 2017 13:44
Show Gist options
  • Save chris-jamieson/992634a88a2cf138c52b971681d4629a to your computer and use it in GitHub Desktop.
Save chris-jamieson/992634a88a2cf138c52b971681d4629a to your computer and use it in GitHub Desktop.
Sequelize snippet for sorting (REST api)
// snippet to help feed sort parameters into Sequelize query
// following Vinay Sahni's best practices (http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api)
// e.g. https://my-url.com/api/v1/sausages?sort=-createdAt,name
function list (req, res, next) {
const findOptions = {
order: [],
};
// handle sorting / ordering
if (req.query.sort) {
const sorts = req.query.sort.split(',');
_.each(sorts, (sort) => {
let field = sort;
let order = 'ASC';
if (sort.charAt(0) === '-') {
order = 'DESC';
field = sort.substring(1); // everything after first char
}
findOptions.order.push([field, order]);
});
} else {
// default ordering (createdAt)
findOptions.order.push(['createdAt', 'DESC']);
}
// run the query
models.Sausage.findAndCountAll(findOptions)
.then((result) => {
const rows = result.rows.map((row) => {
const row = row.get({ plain: true });
return row;
});
res.set('Total-Count', result.count); // set count value to res.headers
return res.status(httpStatus.OK).json(rows);
})
.catch(next);
}
@atubijessica
Copy link

ReferenceError: _ is not defined

@chris-jamieson
Copy link
Author

chris-jamieson commented May 14, 2023

@atubijessica

Here's the modified code snippet that removes the dependency on Underscore.js and uses the array.forEach() method instead:

function list (req, res, next) {
  const findOptions = {
    order: [],
  };

  // handle sorting / ordering
  if (req.query.sort) {
    const sorts = req.query.sort.split(',');
    sorts.forEach((sort) => {
      let field = sort;
      let order = 'ASC';
      if (sort.charAt(0) === '-') {
        order = 'DESC';
        field = sort.substring(1); // everything after first char
      }

      findOptions.order.push([field, order]);
    });
  } else {
    // default ordering (createdAt)
    findOptions.order.push(['createdAt', 'DESC']);
  }
  
  // run the query
  models.Sausage.findAndCountAll(findOptions)
    .then((result) => {
      const rows = result.rows.map((row) => {
        const plainRow = row.get({ plain: true });
        return plainRow;
      });

      res.set('Total-Count', result.count); // set count value to res.headers
      return res.status(200).json(rows);
    })
    .catch(next);
}

The changes made are:

  • Removed the dependency on Underscore.js library.
  • Replaced the _.each() method with the forEach() method.
  • Renamed the inner row variable to plainRow in the map function to avoid naming conflicts.
  • Made sure the plainRow variable is returned from the map function.

@atubijessica
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment