Skip to content
Snippets Groups Projects
Commit 708876f8 authored by Felipe D'Abrantes's avatar Felipe D'Abrantes
Browse files

Add endpoint to fetch questions stored in DB

parent 1844a9ac
No related branches found
No related tags found
1 merge request!25Add a question management page
......@@ -19,6 +19,27 @@ import scala.concurrent.TimeoutException
class QuestionController @Inject()(val controllerComponents: ControllerComponents, authenticatedUserAction: AuthenticatedUserAction)
extends BaseController {
/**
* Create an Action to get all the Questions in the DB.
*/
def getQuestions() = authenticatedUserAction { implicit request: AuthenticationRequest[AnyContent] =>
println("QuestionController:getQuestions")
try {
if (!request.isAdmin) throw new ForbiddenException("You must be an admin to get the stored questions.")
val questions: Seq[Question] = Question.getQuestionsAsync()
val jsonResult: JsValue = Question.toJson(questions)
Ok(jsonResult)
} catch {
case _: TimeoutException => BadRequest("Request timed out")
case ex: ForbiddenException => Forbidden(ex.getMessage())
case ex: Throwable => {
println(ex.getMessage())
BadRequest("Exception raised")
}
}
}
/**
* Create an Action to insert a Question to the DB.
*/
......
......@@ -17,6 +17,10 @@ import org.bson.conversions.Bson
import org.mongodb.scala.model.{Filters, Updates, Sorts}
import play.api.libs.json.{Json, JsValue, JsString, JsObject, JsNumber, JsArray}
import scala.math.BigDecimal
import java.text.SimpleDateFormat
case class Question (
id: Option[ObjectId],
......@@ -29,6 +33,11 @@ case class Question (
object Question {
val questionRepo = new QuestionRepository()
def getQuestionsAsync(timeout: Int = 4): Seq[Question] = {
val result: Future[Seq[Question]] = questionRepo.getAll(None, Some(Sorts.descending("createdAt")), None, None)
Await.result[Seq[Question]](result, timeout.seconds)
}
def createQuestionAsync(content: String, timeout: Int = 4): Question = {
val now: Date = Date.from(Instant.now())
val question: Question = Question(None, content, 0, now, now)
......@@ -56,6 +65,30 @@ object Question {
questionRepo.updateOne(question.id.get, Seq(update))
}
// Convert from Question object to JSON (serializing to JSON)
def toJson(question: Question): JsValue = {
val dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
val formattedCreatedAt: String = dateFormat.format(question.createdAt)
val formattedUpdatedAt: String = dateFormat.format(question.updatedAt)
val questionJson = Seq(
"id" -> JsString(question.id.getOrElse("").toString()),
"content" -> JsString(question.content),
"used" -> JsNumber(BigDecimal(question.used)),
"createdAt" -> JsString(formattedCreatedAt),
"updatedAt" -> JsString(formattedUpdatedAt)
)
Json.toJson[JsObject](JsObject(questionJson))
}
// Convert from Question set to JSON (serializing to JSON)
def toJson(questions: Seq[Question]): JsValue = {
val questionsJson: Seq[JsValue] = questions.map(question => Question.toJson(question))
Json.toJson[JsArray](JsArray(questionsJson))
}
// Codec instance for serialising/deserialising type Question to or from BSON.
// Implicit keyword lets Scala compiler automatically insert this into the code where it's needed.
implicit val codec: Codec[Question] = new Codec[Question] {
......
......@@ -29,4 +29,6 @@ GET /test/verifyUser controllers.TestController.verifyUser(userId: St
GET /question controllers.DailyQuestionController.getDailyQuestion()
GET /questions controllers.QuestionController.getQuestions()
POST /question controllers.QuestionController.insertQuestion()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment