def send()

in src/main/scala/com/gu/mobile/content/notifications/lib/NotificationsApiClient.scala [23:56]


  def send(notification: NotificationPayload): Either[String, UUID] = {
    val url = s"${config.notificationsHost}/push/topic"

    val mediaType = MediaType.parse(s"application/json; charset=utf-8")
    val authHeader = s"Bearer ${config.notificationsKey}"
    val body = RequestBody.create(mediaType, Json.toBytes(Json.toJson(notification)))
    val request = new Request.Builder()
      .url(url)
      .header("Authorization", authHeader)
      .post(body)
      .build()

    val result = Try(client.newCall(request).execute()).map { response =>
      val status = response.code
      val responseBody = response.body.string()

      if (status >= 200 && status < 300) {
        parse(responseBody) match {
          case Some(id) => Right(id)
          case None => Left(s"Notification was sent but unable to parse the response. Got status $status and body $responseBody")
        }

      } else {
        Left(s"Unable to send notification, got status $status and body $responseBody")
      }
    }

    result match {
      case Success(value) => value
      case Failure(NonFatal(e)) =>
        logger.error("Unable to send notification", e)
        Left(s"Unable to send notification: ${e.getMessage}")
    }
  }