Created
April 18, 2019 13:45
-
-
Save lordgape/c46a269fb7bb5d9d25a142bfc827c043 to your computer and use it in GitHub Desktop.
Add Filters and Sort Feature to your search API
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
validateFilterAndSort(req,res,next) | |
{ | |
let query = req.query['q']; | |
// Let destructure our query. | |
let {filter,sort} = req.query; | |
// Let's limit the possible column user can filter by. | |
const FilterableColumns = ['books_count', 'ratings_count', 'original_publication_year', 'original_publication_year', 'original_publication_day']; | |
if(filter != undefined) | |
{ | |
// Validate Filter Column and fail if invalid | |
if (!FilterableColumns.includes(filter)) { | |
res.status(500).json(super.sendResponse('SEARCH_FILTERING_ERROR', "You cannot filter by "+ filter)); | |
} | |
} | |
// Let's limit the possible column user can sort by | |
const sortableColumns = ['id', 'ratings_count', 'original_publication_year', 'original_publication_year', 'original_publication_day']; | |
if(sort) | |
{ | |
// We support the order of sorting. So lets destructure by ":" delimiter | |
let [column, order] = sort.split(':'); | |
if (!sortableColumns.includes(column)) { | |
res.status(500).json(super.sendResponse('SEARCH_SORTING_ERROR', "You cannot sort by "+ sort)); | |
} | |
if (order === undefined) { | |
order = 'asc'; | |
} | |
if (order !== 'asc' && order !== 'desc') { | |
res.status(500).json(super.sendResponse('SEARCH_SORTING_ERROR', "You have an invalid sort order "+ order)); | |
} | |
} | |
return (query) ? query : "books"; // Always return original query or validated query if filter or sort is present | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment