Skip to content

Instantly share code, notes, and snippets.

@rla
Created August 8, 2017 16:25
Show Gist options
  • Save rla/962cab26d742cfa89efb2d9fb4cac5cb to your computer and use it in GitHub Desktop.
Save rla/962cab26d742cfa89efb2d9fb4cac5cb to your computer and use it in GitHub Desktop.
Node-mysql custom formatter for values, identifiers and sort order
// Custom bound parameters.
// :something for values and ?something for identifiers.
// https://github.com/mysqljs/mysql#custom-format
const DIRECTIONS = ['ASC', 'DESC'];
module.exports = function(query, values) {
if (!values) {
return query;
}
const formatted = query.replace(/\:(\w+)/g, (txt, key) => {
// Bound values.
if (values.hasOwnProperty(key)) {
return this.escape(values[key]);
} else {
throw new Error('No value parameter ' + key + ' supplied to MySQL query.');
}
return txt;
}).replace(/\?(\w+)/g, (txt, key) => {
// Bound identifiers.
if (values.hasOwnProperty(key)) {
return this.escapeId(values[key]);
} else {
throw new Error('No identifier parameter ' + key + ' supplied to MySQL query.');
}
return txt;
});
// Sorting direction
if (formatted.indexOf('ORDER_DIRECTION') && values.ORDER_DIRECTION) {
if (DIRECTIONS.indexOf(values.ORDER_DIRECTION) < 0) {
throw new Error('ORDER_DIRECTION can only be ASC or DESC.');
}
return formatted.replace('ORDER_DIRECTION', values.ORDER_DIRECTION);
} else {
return formatted;
}
};
params() {
return Object.assign({}, this.search, {
order: this.order,
limit: this.count,
offset: this.count * this.page,
ORDER_DIRECTION: this.direction
});
}
SELECT
`id`,
`name`,
`contact`,
`email`,
`address`,
`phone`
FROM `companies`
ORDER BY ?order ORDER_DIRECTION
LIMIT :limit OFFSET :offset
exports.list = async (connection, paginator) => {
assert.equal(typeof paginator, 'object');
return listQuery.run(connection, paginator.params());
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment