Last active
April 11, 2017 15:24
-
-
Save alexandrebodin/0d4c3923af9aef214b8038c262093b81 to your computer and use it in GitHub Desktop.
A query filtering generator for knex
This file contains hidden or 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
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