Created
August 8, 2017 16:25
-
-
Save rla/962cab26d742cfa89efb2d9fb4cac5cb to your computer and use it in GitHub Desktop.
Node-mysql custom formatter for values, identifiers and sort order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
params() { | |
return Object.assign({}, this.search, { | |
order: this.order, | |
limit: this.count, | |
offset: this.count * this.page, | |
ORDER_DIRECTION: this.direction | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT | |
`id`, | |
`name`, | |
`contact`, | |
`email`, | |
`address`, | |
`phone` | |
FROM `companies` | |
ORDER BY ?order ORDER_DIRECTION | |
LIMIT :limit OFFSET :offset |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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