All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.kondaurovdev.http_client.HttpJsonClient.scala Maven / Gradle / Ivy

The newest version!
package com.github.kondaurovdev.http_client

import com.github.kondaurovdev.core.models.auth.{LoginCredentials, LoginSuccess}
import com.github.kondaurovdev.play_json.JsonHelper
import play.api.libs.json._

trait iHttpClient {

  def http: JsonClient

  def credentials: LoginCredentials
  def host: String

  var loginSuccess = Option.empty[LoginSuccess]

  def sendDataWithToken[T](url: String, data: T, headers: List[(String, String)] = List())(implicit writes: Writes[T]): Either[JsValue, JsValue] = {
    for (
      token <- getToken.right;
      res <- sendData(url, data, headers ::: List(
        "token" -> token
      )).right
    ) yield res
  }

  def sendData[T](url: String, data: T, headers: List[(String, String)] = List())(implicit writes: Writes[T]): Either[JsValue, JsValue] = {
    PageParser.getJsonPage {
      http(s"$host$url", data)
        .headers(headers)
        .method("POST")
    }.right.map(_.body)
  }

  private def getToken: Either[JsValue, String] = {
    (loginSuccess match {
      case Some(l) => if (l.token.isExpired) refreshToken else Right(l)
      case _ => refreshToken
    }).right.map(_.tokenForm)
  }

  private def refreshToken: Either[JsValue, LoginSuccess] = {
    (for (
      response <- sendData("/auth", Json.obj("login" -> Json.toJson(credentials).as[JsObject])).right;
      res <- JsonHelper.validate[LoginSuccess](response \ "data").right
    ) yield res).left.map(err => {
      Json.obj("can't refresh token" -> err)
    }).right.map(res => {
      loginSuccess = Some(res)
      res
    })
  }

}

case class HttpJsonClient(
                         credentials: LoginCredentials,
                         host: String,
                         http: JsonClient) extends iHttpClient




© 2015 - 2025 Weber Informatics LLC | Privacy Policy