SimpleNotes/api/src/services/NotesService.kt

47 lines
1.3 KiB
Kotlin

package be.vandewalleh.services
import be.vandewalleh.tables.Notes
import be.vandewalleh.tables.Tags
import me.liuwj.ktorm.database.Database
import me.liuwj.ktorm.dsl.*
import org.kodein.di.Kodein
import org.kodein.di.KodeinAware
import org.kodein.di.generic.instance
import java.time.format.DateTimeFormatter
/**
* service to handle database queries at the Notes level.
*/
class NotesService(override val kodein: Kodein) : KodeinAware {
val db by instance<Database>()
/**
* returns a list of [NotesDTO] associated with the userId
*/
fun getNotes(userId: Int): List<NotesDTO> {
val notes = db.from(Notes)
.select(Notes.id, Notes.title, Notes.updatedAt)
.where { Notes.userId eq userId }
.orderBy(Notes.updatedAt.desc())
.map { row ->
Notes.createEntity(row)
}
.toList()
return notes.map { note ->
val tags = db.from(Tags)
.select(Tags.name)
.where { Tags.noteId eq note.id }
.map { it[Tags.name]!! }
.toList()
val updatedAt = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(note.updatedAt)
NotesDTO(note.title, tags, updatedAt)
}
}
}
data class NotesDTO(val title: String, val tags: List<String>, val updatedAt: String)