Generic service for CRUD requests in Ktor

I’ve generated a new Ktor project in which I could find a UsersSchema.kt file.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Serializable
data class ExposedUser(val name: String, val age: Int)
class UserService(database: Database) {
object Users : Table() {
val id = integer("id").autoIncrement()
val name = varchar("name", length = 50)
val age = integer("age")
override val primaryKey = PrimaryKey(id)
}
init {
transaction(database) {
SchemaUtils.create(Users)
}
}
suspend fun create(user: ExposedUser): Int = dbQuery {
Users.insert {
it[name] = user.name
it[age] = user.age
}[Users.id]
}
suspend fun read(id: Int): ExposedUser? {
return dbQuery {
Users.selectAll()
.where { Users.id eq id }
.map { ExposedUser(it[Users.name], it[Users.age]) }
.singleOrNull()
}
}
suspend fun update(id: Int, user: ExposedUser) {
dbQuery {
Users.update({ Users.id eq id }) {
it[name] = user.name
it[age] = user.age
}
}
}
suspend fun delete(id: Int) {
dbQuery {
Users.deleteWhere { Users.id.eq(id) }
}
}
private suspend fun <T> dbQuery(block: suspend () -> T): T =
newSuspendedTransaction(Dispatchers.IO) { block() }
}
</code>
<code>@Serializable data class ExposedUser(val name: String, val age: Int) class UserService(database: Database) { object Users : Table() { val id = integer("id").autoIncrement() val name = varchar("name", length = 50) val age = integer("age") override val primaryKey = PrimaryKey(id) } init { transaction(database) { SchemaUtils.create(Users) } } suspend fun create(user: ExposedUser): Int = dbQuery { Users.insert { it[name] = user.name it[age] = user.age }[Users.id] } suspend fun read(id: Int): ExposedUser? { return dbQuery { Users.selectAll() .where { Users.id eq id } .map { ExposedUser(it[Users.name], it[Users.age]) } .singleOrNull() } } suspend fun update(id: Int, user: ExposedUser) { dbQuery { Users.update({ Users.id eq id }) { it[name] = user.name it[age] = user.age } } } suspend fun delete(id: Int) { dbQuery { Users.deleteWhere { Users.id.eq(id) } } } private suspend fun <T> dbQuery(block: suspend () -> T): T = newSuspendedTransaction(Dispatchers.IO) { block() } } </code>
@Serializable
data class ExposedUser(val name: String, val age: Int)

class UserService(database: Database) {
    object Users : Table() {
        val id = integer("id").autoIncrement()
        val name = varchar("name", length = 50)
        val age = integer("age")

        override val primaryKey = PrimaryKey(id)
    }

    init {
        transaction(database) {
            SchemaUtils.create(Users)
        }
    }

    suspend fun create(user: ExposedUser): Int = dbQuery {
        Users.insert {
            it[name] = user.name
            it[age] = user.age
        }[Users.id]
    }

    suspend fun read(id: Int): ExposedUser? {
        return dbQuery {
            Users.selectAll()
                .where { Users.id eq id }
                .map { ExposedUser(it[Users.name], it[Users.age]) }
                .singleOrNull()
        }
    }

    suspend fun update(id: Int, user: ExposedUser) {
        dbQuery {
            Users.update({ Users.id eq id }) {
                it[name] = user.name
                it[age] = user.age
            }
        }
    }

    suspend fun delete(id: Int) {
        dbQuery {
            Users.deleteWhere { Users.id.eq(id) }
        }
    }

    private suspend fun <T> dbQuery(block: suspend () -> T): T =
        newSuspendedTransaction(Dispatchers.IO) { block() }
}

Based on this example, I created a CategorySchema.kt file.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@Serializable
data class Category(
val id: String,
val name: String,
val image: String?,
val slug: String,
)
class CategoryService(database: Database) {
object CategoryTable: Table(""Category"") {
val id = varchar("id", 36).uniqueIndex()
val name = varchar("name", 50).uniqueIndex()
val image = text("image").nullable()
val slug = varchar("slug", 50).uniqueIndex()
val createdAt = datetime("createdAt")
val updatedAt = datetime("updatedAt")
override val primaryKey = PrimaryKey(id)
}
init {
transaction(database) {
SchemaUtils.create(CategoryTable)
addLogger(StdOutSqlLogger)
}
}
suspend fun getAll(): List<Category> {
try {
return dbQuery {
CategoryTable.selectAll().map {
Category(
it[CategoryTable.id],
it[CategoryTable.name],
it[CategoryTable.image],
it[CategoryTable.slug]
)
}
}
} catch (e: Exception) {
exposedLogger.error("Aucune catégorie existante")
return emptyList()
}
}
suspend fun getOne(id: String): Category? {
try {
return dbQuery {
CategoryTable
.selectAll()
.where { CategoryTable.id eq id }
.map {
Category(
it[CategoryTable.id],
it[CategoryTable.name],
it[CategoryTable.image],
it[CategoryTable.slug]
)
}
.singleOrNull()
}
} catch (e: Exception) {
exposedLogger.error("La catégorie recherchée n'existe pas")
return null
}
}
private suspend fun <T> dbQuery(block: suspend () -> T): T =
newSuspendedTransaction(Dispatchers.IO) { block() }
}
</code>
<code>@Serializable data class Category( val id: String, val name: String, val image: String?, val slug: String, ) class CategoryService(database: Database) { object CategoryTable: Table(""Category"") { val id = varchar("id", 36).uniqueIndex() val name = varchar("name", 50).uniqueIndex() val image = text("image").nullable() val slug = varchar("slug", 50).uniqueIndex() val createdAt = datetime("createdAt") val updatedAt = datetime("updatedAt") override val primaryKey = PrimaryKey(id) } init { transaction(database) { SchemaUtils.create(CategoryTable) addLogger(StdOutSqlLogger) } } suspend fun getAll(): List<Category> { try { return dbQuery { CategoryTable.selectAll().map { Category( it[CategoryTable.id], it[CategoryTable.name], it[CategoryTable.image], it[CategoryTable.slug] ) } } } catch (e: Exception) { exposedLogger.error("Aucune catégorie existante") return emptyList() } } suspend fun getOne(id: String): Category? { try { return dbQuery { CategoryTable .selectAll() .where { CategoryTable.id eq id } .map { Category( it[CategoryTable.id], it[CategoryTable.name], it[CategoryTable.image], it[CategoryTable.slug] ) } .singleOrNull() } } catch (e: Exception) { exposedLogger.error("La catégorie recherchée n'existe pas") return null } } private suspend fun <T> dbQuery(block: suspend () -> T): T = newSuspendedTransaction(Dispatchers.IO) { block() } } </code>
@Serializable
data class Category(
    val id: String,
    val name: String,
    val image: String?,
    val slug: String,
)

class CategoryService(database: Database) {
    object CategoryTable: Table(""Category"") {
        val id = varchar("id", 36).uniqueIndex()
        val name = varchar("name", 50).uniqueIndex()
        val image = text("image").nullable()
        val slug = varchar("slug", 50).uniqueIndex()
        val createdAt = datetime("createdAt")
        val updatedAt = datetime("updatedAt")

        override val primaryKey = PrimaryKey(id)
    }

    init {
        transaction(database) {
            SchemaUtils.create(CategoryTable)
            addLogger(StdOutSqlLogger)
        }
    }

    suspend fun getAll(): List<Category> {
        try {
            return dbQuery {
                CategoryTable.selectAll().map {
                    Category(
                        it[CategoryTable.id],
                        it[CategoryTable.name],
                        it[CategoryTable.image],
                        it[CategoryTable.slug]
                    )
                }
            }
        } catch (e: Exception) {
            exposedLogger.error("Aucune catégorie existante")
            return emptyList()
        }
    }

    suspend fun getOne(id: String): Category? {
        try {
            return dbQuery {
                CategoryTable
                    .selectAll()
                    .where { CategoryTable.id eq id }
                    .map {
                        Category(
                            it[CategoryTable.id],
                            it[CategoryTable.name],
                            it[CategoryTable.image],
                            it[CategoryTable.slug]
                        )
                    }
                    .singleOrNull()
            }
        } catch (e: Exception) {
            exposedLogger.error("La catégorie recherchée n'existe pas")
            return null
        }
    }

    private suspend fun <T> dbQuery(block: suspend () -> T): T =
        newSuspendedTransaction(Dispatchers.IO) { block() }
}

Then I realised that many of my tables have similar methods, and as I didn’t want to repeat myself, I decided to create a BaseService class.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>abstract class BaseService<Entity, ExposedTable : Table>(
private val table: ExposedTable,
private val mapper: (ResultRow) -> Entity
) {
suspend fun getAll(): List<Entity> {
try {
return dbQuery {
table.selectAll().map(mapper)
}
} catch (e: Exception) {
exposedLogger.error("Erreur lors de la récupération des éléments issus de ${table.tableName}")
return emptyList()
}
}
private suspend fun <T> dbQuery(block: suspend () -> T): T =
newSuspendedTransaction(Dispatchers.IO) { block() }
}
</code>
<code>abstract class BaseService<Entity, ExposedTable : Table>( private val table: ExposedTable, private val mapper: (ResultRow) -> Entity ) { suspend fun getAll(): List<Entity> { try { return dbQuery { table.selectAll().map(mapper) } } catch (e: Exception) { exposedLogger.error("Erreur lors de la récupération des éléments issus de ${table.tableName}") return emptyList() } } private suspend fun <T> dbQuery(block: suspend () -> T): T = newSuspendedTransaction(Dispatchers.IO) { block() } } </code>
abstract class BaseService<Entity, ExposedTable : Table>(
    private val table: ExposedTable,
    private val mapper: (ResultRow) -> Entity
) {
    suspend fun getAll(): List<Entity> {
        try {
            return dbQuery {
                table.selectAll().map(mapper)
            }
        } catch (e: Exception) {
            exposedLogger.error("Erreur lors de la récupération des éléments issus de ${table.tableName}")
            return emptyList()
        }
    }
    
    private suspend fun <T> dbQuery(block: suspend () -> T): T =
        newSuspendedTransaction(Dispatchers.IO) { block() }
}

However, I don’t know how I should write the getOne() method.

What I’ve tried:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>suspend fun getOne(id: String): Entity? {
try {
return dbQuery {
table
.selectAll()
.where { table.primaryKey eq id }
.map(mapper)
.singleOrNull()
}
} catch (e: Exception) {
exposedLogger.error("Erreur lors de la récupération de l'élément issu de ${table.tableName}")
return null
}
}
</code>
<code>suspend fun getOne(id: String): Entity? { try { return dbQuery { table .selectAll() .where { table.primaryKey eq id } .map(mapper) .singleOrNull() } } catch (e: Exception) { exposedLogger.error("Erreur lors de la récupération de l'élément issu de ${table.tableName}") return null } } </code>
suspend fun getOne(id: String): Entity? {
    try {
        return dbQuery {
            table
                .selectAll()
                .where { table.primaryKey eq id }
                .map(mapper)
                .singleOrNull()
        }
    } catch (e: Exception) {
        exposedLogger.error("Erreur lors de la récupération de l'élément issu de ${table.tableName}")
        return null
    }
}

Error:

Type mismatch. Required: Op Found: Unit

What I want to do:

I would like to create an API with only GET and POST methods. I should be able to get data from all my tables and update some of them. As the GET methods always work in the same way, I wanted to create a generic service with two methods getAll() and getOne(). Thanks to this, I could pass them parameters and use them in all my services.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật