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

com.gu.featureswitching.CookieFeatureSwitchingOverrideStrategy.scala Maven / Gradle / Ivy

package com.gu.featureswitching

import java.net.{URLDecoder, URLEncoder}

trait CookieFeatureSwitchingOverrideStrategy extends FeatureSwitchingOverrideStrategy {

  def getCookie(name: String): Option[String]
  def setCookie(name: String, value: String): Unit

  lazy val featureSwitchOverrideKey = "features.override"

  // TODO: clear obsolete keys for non-existing features, by reading the list of existing switches
  private def rawValue = getCookie(featureSwitchOverrideKey).getOrElse("")
  private def rawCookie = URLDecoder.decode(rawValue, "utf-8")

  private def cookieMap = rawCookie.split(",").map(_.split("=").toList).flatMap {
    case List(key, "true") => Some((key -> true))
    case List(key, "false") => Some((key -> false))
    case _ => None // invalid token, ignore
  }.toMap

  private def renderCookie(newCookieMap: Map[String, Boolean]) =
    URLEncoder.encode(renderCookieString(newCookieMap), "utf-8")

  private def renderCookieString(newCookieMap: Map[String, Boolean]) = newCookieMap.map {
    case (key, value) => "%s=%s".format(key, value)
  }.toList.mkString(",")

  private def resetCookie(newCookieMap: Map[String, Boolean]) {
    setCookie(featureSwitchOverrideKey, renderCookie(newCookieMap))
  }


  /* Public interface */

  def featureIsOverridden(feature: FeatureSwitch): Option[Boolean] = {
    cookieMap.get(feature.key)
  }
  def featureSetOverride(feature: FeatureSwitch, overridden: Boolean) {
    val updatedCookieMap = cookieMap + (feature.key -> overridden)
    resetCookie(updatedCookieMap)
  }
  def featureResetOverride(feature: FeatureSwitch) {
    val updatedCookieMap = cookieMap - feature.key
    resetCookie(updatedCookieMap)
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy