playframework - Map data from a Scala Future -
i'm implementing task calling rest endpoint in play framework, here's code in service:
override def getaccesstoken(logindata: logindata): future[unit] = { logger.info("get access token hat") val accesstokenurl = // url called logger.info(accesstokenurl) ws .url(accesstokenurl) .withhttpheaders( headernames.accept -> contenttypes.json, "username" -> logindata.username, "password" -> logindata.password ) .withrequesttimeout(timeout) .get() .map { response => response.status match { case status.ok => val responseasjson = response.json future.successful((responseasjson \ "accesstoken").as[string]) case _ => val message = (response.json \"message").asopt[string] throw new generalbadrequestexception(message.get) } } }
the response of val accesstokenurl
like:
{ "accesstoken": "some token", "userid": "some user id" }
then in controller, write function data service above:
private def handleaccesstoken: logindata => future[result] = { logindata => requesthatservice.getaccesstoken(logindata).map ( response => ok(response)) recover { case e => val errorjson: jsvalue = json.obj( "status" -> "error", "error" -> json.obj( "code" -> "error", "message" -> e.getmessage ) ) badrequest(errorjson) } }
what i'm struggling @ moment part response => ok(response))
in function handleaccesstoken
, want include ok result return in controller response can not data out, accesstoken
, when i'm trying compile code , error throw this:
cannot write instance of unit http response. try define writeable[unit]
edit : @frederic answer, have problem here, how can attach response string jsvalue , pass ok result, thing
val successjson: jsvalue = json.obj("status" -> "ok") requesthatservice.getaccesstoken(logindata).map ( response => // code attach response successjson here ok(successjson)) recover { ...... }
the problem in definition of: def getaccesstoken(logindata: logindata): future[unit]
it should be: def getaccesstoken(logindata: logindata): future[string]
do need more explanations?
Comments
Post a Comment