Last active
November 10, 2019 04:57
-
-
Save rnovec/58cf4f427d75c10f846879bcf03ebde8 to your computer and use it in GitHub Desktop.
simple and useful example of API pagination implementation
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
// assume that you develop a course's API GET endpoint | |
// best practices is pagination of /v1/courses endpoint | |
// if you is receving page & limit paramas as a queries, aditional filter params are optional | |
// this is a example of our endpoint with pagination, sorting & filtering | |
// we have a request containing data like params, queries, headers... | |
const { reviews, status, title, page = 1, limit = 20, sort } = request.query // using object destructuring | |
let List = [] // get data form database | |
// filter data by params pased on request | |
let mockList = List.filter(item => { | |
if (reviews && item.reviews !== +reviews) return false | |
if (status && item.status !== parseInt(status)) return false | |
if (title && item.title.indexOf(title) < 0) return false | |
return true | |
}) | |
// sorting by uuid field | |
if (sort === '-uuid') { | |
mockList = mockList.reverse() | |
} | |
// pagination filtered list | |
const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1)) | |
return { | |
code: 200, // status code OK! | |
data: { | |
total: mockList.length, // total database resources | |
page, // current page returned | |
items: pageList // current array with query matched | |
} | |
} | |
// this hipotetic example have some considerations | |
// for example, get all resources of database can provoke memory leak | |
// has not the best performance with many requests | |
// is just an example, nowadays depends on what datadabase is using, there are internal | |
// libraries to do pagination and have better performance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment