plumber icon indicating copy to clipboard operation
plumber copied to clipboard

[FR] Native support for caching

Open jeffkeller87 opened this issue 4 years ago • 0 comments

There was a shiny blog post earlier this year describing the very useful native caching feature using the cachem package. I think it would be just as useful--if not more useful, considering performance expectations of HTTP APIs--to have a similar caching integration for plumber.

Of course, like apps built with shiny 1.6.0 and older, this can be done manually using the cachem package directly. Below is an example that keys off the URL parameters only.

cache <- cachem::cache_mem()

slow_add <- function(a, b) {
  
  Sys.sleep(5)
  return(as.numeric(a) + as.numeric(b))
  
}

pr <- plumber::pr()

pr$handle(
  methods = "GET", path = "/slow_add",
  handler = function(a, b, req, res) {
    
    slow_add(a, b)
    
  }
)

pr$handle(
  methods = "GET", path = "/slow_add_cached",
  handler = function(a, b, req, res) {
    
    key <- digest::digest(list(a, b), algo = "spookyhash")
    
    cache$get(
      key = key,
      missing = {
        
        value <- slow_add(a, b)
        cache$set(key, value)
        return(value)
        
      }
    )
    
  }
)

pr$run()

jeffkeller87 avatar May 14 '21 18:05 jeffkeller87