Skip to content

Commit c7ade98

Browse files
committed
add crud controller
1 parent 5ec4e39 commit c7ade98

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package com.ss.demo.controller
2+
3+
import com.ss.demo.repository.WordRepository
4+
import org.springframework.web.bind.annotation.GetMapping
5+
import org.springframework.web.bind.annotation.RestController
6+
import org.springframework.web.bind.annotation.RequestMapping
7+
import org.springframework.web.bind.annotation.PathVariable
8+
import org.springframework.web.bind.annotation.PostMapping
9+
import org.springframework.web.bind.annotation.PutMapping
10+
import org.springframework.web.bind.annotation.DeleteMapping
11+
import org.springframework.web.bind.annotation.RequestBody
12+
import org.springframework.http.ResponseEntity
13+
import org.springframework.http.HttpStatus
14+
import com.ss.demo.model.WordEntity
15+
16+
@RestController
17+
@RequestMapping("/api/words")
18+
class WordController(private val wordRepository: WordRepository) {
19+
20+
// Read all words
21+
@GetMapping
22+
fun getAllWords(): List<WordEntity> {
23+
return wordRepository.findAll()
24+
}
25+
26+
// Read a single word by ID
27+
@GetMapping("/{id}")
28+
fun getWordById(@PathVariable id: Long): ResponseEntity<WordEntity> {
29+
val word = wordRepository.findById(id)
30+
return if (word.isPresent) {
31+
ResponseEntity.ok(word.get())
32+
} else {
33+
ResponseEntity.notFound().build()
34+
}
35+
}
36+
37+
// Create a new word
38+
@PostMapping
39+
fun createWord(@RequestBody word: WordEntity): ResponseEntity<WordEntity> {
40+
if (word.word.isBlank()) {
41+
return ResponseEntity.badRequest().build()
42+
}
43+
val savedWord = wordRepository.save(word)
44+
return ResponseEntity.status(HttpStatus.CREATED).body(savedWord)
45+
}
46+
47+
// Update an existing word
48+
@PutMapping("/{id}")
49+
fun updateWord(@PathVariable id: Long, @RequestBody updatedWord: WordEntity): ResponseEntity<WordEntity> {
50+
val existingWord = wordRepository.findById(id)
51+
return if (existingWord.isPresent) {
52+
val wordToUpdate = existingWord.get().copy(word = updatedWord.word)
53+
ResponseEntity.ok(wordRepository.save(wordToUpdate))
54+
} else {
55+
ResponseEntity.notFound().build()
56+
}
57+
}
58+
59+
// Delete a word
60+
@DeleteMapping("/{id}")
61+
fun deleteWord(@PathVariable id: Long): ResponseEntity<Void> {
62+
return if (wordRepository.existsById(id)) {
63+
wordRepository.deleteById(id)
64+
ResponseEntity.noContent().build()
65+
} else {
66+
ResponseEntity.notFound().build()
67+
}
68+
}
69+
}

0 commit comments

Comments
 (0)