I am writing API in Kotlin - this is my first code in this language. I implemented a very primitive 'player' endpoint. I was wondering if I am doing everything ok (please don't mind the static variables - I will put them in the database later)
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import pl.domain.Player
import pl.rest.dto.PlayerDto
@RestController
@RequestMapping("/player")
class PlayerController {
var players: Map<Long, Player> = mapOf(
1L to Player(1L, "user1", "password1"),
2L to Player(2L, "user2", "password2"),
3L to Player(3L, "user3", "password3")
)
@GetMapping("/{id}")
fun fetchPlayer(@PathVariable id : Long): ResponseEntity<Player> =
players[id]?.let { ResponseEntity.ok(it) } ?: ResponseEntity.notFound().build()
@PostMapping
fun createPlayer(@RequestParam username: String, @RequestParam password : String): ResponseEntity<Player> {
val playerId = (players.size + 1).toLong()
val player = Player(playerId, username, password)
players = players.plus(player.id to player)
return ResponseEntity.ok(player)
}
@PutMapping
fun updatePlayer(@RequestBody playerDto: PlayerDto): ResponseEntity<Player> {
return players[playerDto.id]
?.apply {
username = playerDto.username ?: username
password = playerDto.password ?: password
}?.let { ResponseEntity.ok(it) } ?: ResponseEntity.badRequest().build()
}
@DeleteMapping("/{id}")
fun deletePlayer(@PathVariable id: Long): ResponseEntity<Nothing> {
players = players.minus(id)
return ResponseEntity.noContent().build()
}
}
PlayerDto.kt:
class PlayerDto(var id: Long? = null, var username: String? = null, var password: String? = null)
Player.kt:
data class Player(var id: Long, var username: String, var password: String)