Skip to content

Instantly share code, notes, and snippets.

@YouniRoop
Last active October 23, 2023 17:50
Show Gist options
  • Save YouniRoop/dc360ca88bce3890066e17c668e24670 to your computer and use it in GitHub Desktop.
Save YouniRoop/dc360ca88bce3890066e17c668e24670 to your computer and use it in GitHub Desktop.
MessageController.kt
@RestController
@RequestMapping("/api/messages")
class MessageController(private val messageRepository: MessageRepository) {
@GetMapping
suspend fun getAll() = messageRepository.findAll()
@GetMapping("/{id}")
suspend fun getOne(@PathVariable id: Long) = messageRepository.findById(id)
@PostMapping
suspend fun post(@RequestBody messagePostRequestDto: MessagePostRequestDto) =
messageRepository.save(
Message(
message = messagePostRequestDto.message,
userName = messagePostRequestDto.userName,
date = Instant.now(),
)
)
@DeleteMapping("/{id}")
suspend fun deleteOne(@PathVariable id: Long) = messageRepository.deleteById(id)
}
// DTO to separate business/database model from API request model
data class MessagePostRequestDto(
val message: String?,
val userName: String?,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment