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

Add endpoint to insert a question

parent a72d1562
No related branches found
No related tags found
1 merge request!17Implement Question Service
package controllers
import models.{Question}
import models.exceptions.{ConflictException, InvalidRequestBodyException}
import javax.inject._
import play.api.mvc._
import play.api.libs.json.{JsValue}
import play.api.libs.json.JsLookupResult
import scala.concurrent.TimeoutException
/**
* This controller handles all the Question endpoints.
*/
@Singleton
class QuestionController @Inject()(val controllerComponents: ControllerComponents) extends BaseController {
/**
* Create an Action to insert a Question to the DB.
*/
def insertQuestion() = Action { implicit request: Request[AnyContent] =>
println("QuestionController:insertQuestion")
try {
val questionText: String = fetchInsertQuestionRequestBody(request.body)
Question.createQuestionAsync(questionText)
Ok("Inserted question")
} catch {
case _: TimeoutException => BadRequest("Request timed out")
case ex: ConflictException => BadRequest(ex.getMessage())
case _: Throwable => BadRequest("Exception raised")
}
}
/**
* Fetch the needed values from the request body for the liking/unliking a Daily endpoint.
*
* @param requestBody The request's body.
*/
def fetchInsertQuestionRequestBody(requestBody: AnyContent): String = {
if (!requestBody.asJson.isDefined) throw new InvalidRequestBodyException("Request body must be in JSON format.")
val bodyJson = requestBody.asJson.get
fetchJsonBodyString(bodyJson, "questionText")
}
/**
* Fetch the value of the given field name from the JSON.
*
* @param bodyJson The JSON.
* @param fieldName The field name.
*/
def fetchJsonBodyValue(bodyJson: JsValue, fieldName: String): JsValue = {
val value: JsLookupResult = (bodyJson \ fieldName)
if (!value.isDefined) throw new InvalidRequestBodyException("Missing parameter: " + fieldName)
value.get
}
/**
* Fetch the String value of the field name from the JSON.
*
* @param bodyJson The JSON.
* @param fieldName The field name.
*/
def fetchJsonBodyString(bodyJson: JsValue, fieldName: String): String = {
fetchJsonBodyValue(bodyJson, fieldName).as[String]
}
}
......@@ -26,3 +26,5 @@ GET /test/verifyUser controllers.TestController.verifyUser(userId: St
GET /question controllers.DailyQuestionController.getDailyQuestion()
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