Skip to content

Commit

Permalink
Modified QuestionEntity to have author property gotten from Principal
Browse files Browse the repository at this point in the history
  • Loading branch information
Serge-NSN committed Jul 19, 2023
1 parent ac68ad1 commit 301f39f
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 33 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.serge.nsn.qahub.api.controller

import com.serge.nsn.qahub.api.dto.QuestionDto
import com.serge.nsn.qahub.services.QuestionService
import org.springframework.web.bind.annotation.*
import java.security.Principal

@RestController
@RequestMapping("/api/question")
class QuestionController(
private val questionService: QuestionService
) {

@GetMapping("/all")
fun getAll() = questionService.getAllQuestions()

@GetMapping("/{id}")
fun get(@PathVariable id: Long) = questionService.getQuestionById(id)

@GetMapping("/user/{userId}")
fun getByUserId(@PathVariable userId: Long): List<QuestionDto> {
return questionService.getByUserId(userId)
}

@PostMapping("/ask")
fun ask(@RequestBody question: QuestionDto, principal: Principal) = questionService.askQuestion(question, principal)
}
42 changes: 42 additions & 0 deletions src/main/kotlin/com/serge/nsn/qahub/services/QuestionService.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.serge.nsn.qahub.services

import com.serge.nsn.qahub.api.dto.QuestionDto
import com.serge.nsn.qahub.data.entities.QuestionEntity
import com.serge.nsn.qahub.data.entities.UserEntity
import com.serge.nsn.qahub.data.repositories.QuestionRepository
import com.serge.nsn.qahub.data.repositories.UserRepository
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Service
import java.security.Principal

@Service
class QuestionService(
private val questionRepository: QuestionRepository,
private val userRepository: UserRepository
) {
fun askQuestion(dto: QuestionDto, principal: Principal): ResponseEntity<QuestionDto> {
val questionAuthor: UserEntity = userRepository.findByEmail(principal.name).get()
val askedQuestion = questionRepository
.save(
QuestionEntity(
id = dto.id,
title = dto.title,
content = dto.content,
author = questionAuthor.name,
user = questionAuthor
)

)

return ResponseEntity(QuestionDto(askedQuestion), HttpStatus.CREATED)
}

fun getAllQuestions() = questionRepository.findAll().map { QuestionDto(it) }
fun getQuestionById(id: Long) = questionRepository.findById(id).map { QuestionDto(it) }

fun getByUserId(userId: Long): List<QuestionDto> {
return questionRepository.findAllByUserId(userId).map { QuestionDto(it) }
}

}

This file was deleted.

0 comments on commit 301f39f

Please sign in to comment.