diff --git a/src/main/kotlin/dev/usbharu/hideout/application/infrastructure/exposed/ExposedPaginationExtension.kt b/src/main/kotlin/dev/usbharu/hideout/application/infrastructure/exposed/ExposedPaginationExtension.kt new file mode 100644 index 00000000..48047aac --- /dev/null +++ b/src/main/kotlin/dev/usbharu/hideout/application/infrastructure/exposed/ExposedPaginationExtension.kt @@ -0,0 +1,19 @@ +package dev.usbharu.hideout.application.infrastructure.exposed + +import org.jetbrains.exposed.sql.ExpressionWithColumnType +import org.jetbrains.exposed.sql.Query +import org.jetbrains.exposed.sql.SortOrder +import org.jetbrains.exposed.sql.andWhere + +fun Query.pagination(page: Page, exp: ExpressionWithColumnType): Query { + if (page.minId != null) { + page.maxId?.let { andWhere { exp.lessEq(it) } } + page.minId?.let { andWhere { exp.greaterEq(it) } } + } else { + page.maxId?.let { andWhere { exp.lessEq(it) } } + page.sinceId?.let { andWhere { exp.greaterEq(it) } } + this.orderBy(exp, SortOrder.DESC) + } + page.limit?.let { limit(it) } + return this +} diff --git a/src/main/kotlin/dev/usbharu/hideout/application/infrastructure/exposed/Page.kt b/src/main/kotlin/dev/usbharu/hideout/application/infrastructure/exposed/Page.kt new file mode 100644 index 00000000..33902372 --- /dev/null +++ b/src/main/kotlin/dev/usbharu/hideout/application/infrastructure/exposed/Page.kt @@ -0,0 +1,36 @@ +package dev.usbharu.hideout.application.infrastructure.exposed + +sealed class Page { + abstract val maxId: Long? + abstract val sinceId: Long? + abstract val minId: Long? + abstract val limit: Int? + + data class PageByMaxId( + override val maxId: Long?, + override val sinceId: Long?, + override val limit: Int? + ) : Page() { + override val minId: Long? = null + } + + data class PageByMinId( + override val maxId: Long?, + override val minId: Long?, + override val limit: Int? + ) : Page() { + override val sinceId: Long? = null + } + + companion object { + fun of(maxId: Long?, sinceId: Long?, minId: Long?, limit: Int?): Page = if (minId != null) { + PageByMinId( + maxId, minId, limit + ) + } else { + PageByMaxId( + maxId, sinceId, limit + ) + } + } +}