Ktor server for beginners – Pagination

Level: Beginner

In the previous lesson we learned how to protect our endpoints using JWT authentication, now lets learn about pagination.

for the sake of simplicity im just going to add the video tutorial here with the code snippets as writing the tutorial in addition to doing the recording consumes a lot of time.

@Serializable
data class FruitPage(
    val fruits: List<Fruit>,
    val page: Int,
    val total: Long,
    val pageSize: Int,
    val totalPages: Long
)
suspend fun getFruits(
     sortingField: String = Fruit::name.name,
     sortingDirection: Int = 1,
     season: List<Season>? = null,
     query: String? = null,
     limit: Int = 10,
     page: Int = 1
): FruitPage {
    val sorting = if (sortingDirection > 0) Sorts.ascending(sortingField) else Sorts.descending(sortingField)
    val seasonFilter = if (season == null || season.isEmpty()) Filters.empty() else Filters.`in`(Fruit::season.name, season)
    val queryFilter = if (query == null) Filters.empty() else Filters.regex(Fruit::name.name, query, "i")
    val filter = Filters.and(seasonFilter, queryFilter)
    val total = fruitCollection.countDocuments(filter)
    val skip = (page - 1) * limit

    val fruits = fruitCollection.find(filter).skip(skip).limit(limit).sort(sorting).toList()

    return FruitPage(
        fruits = fruits,
        page = page,
        total = total,
        pageSize = limit,
        totalPages = ceil(total.toDouble() / limit).toLong()
    )
}
        val page = call.queryParameters["page"]?.toIntOrNull() ?: 1

        val fruits = getFruits(
            sortingField = sortingField,
            sortingDirection = sortingDirection,
            season = seasons,
            query = q,
            limit = limit,
            page = page
        )

The source code can be found here.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments