Skip to content

Instantly share code, notes, and snippets.

@alexandrebodin
Last active April 11, 2017 15:24
Show Gist options
  • Save alexandrebodin/0d4c3923af9aef214b8038c262093b81 to your computer and use it in GitHub Desktop.
Save alexandrebodin/0d4c3923af9aef214b8038c262093b81 to your computer and use it in GitHub Desktop.
A query filtering generator for knex
const mapping = {
userId: 'user_id',
comment: 'comment',
date: 'date',
id: 'id',
createdAt: 'created_at',
updatedAt: 'updated_at',
};
// generate a where query with any filters matching a mapping
const handleFilters = (filters = {}) => query => {
Object.keys(filters).map(key => {
const mappedKey = mapping[key];
const filter = filters[key];
if (mappedKey !== undefined && filter !== null && filter !== undefined) {
if (Array.isArray(filter)) {
query.whereIn(mappedKey, filter);
} else {
query.where(mappedKey, filter);
}
}
});
};
// usage =>
knex.select().from('table').where(handleFilters({userId: [1]}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment