Suave - Control when responses are 'cached' or recalculated
Asked Answered
F

1

5

I want to understand how to control when responses are 'cached' versus when they are 'recalculated'.

As an example:

[<EntryPoint>]
let main [| port |] =

    let config =
        { defaultConfig with
                bindings = [ HttpBinding.mk HTTP IPAddress.Loopback (uint16 port) ]
                listenTimeout = TimeSpan.FromMilliseconds 3000.
                }

    let appDemo:WebPart = 
        DateTime.Now.ToString()
        |> sprintf "Server timestamp: %s"
        |> Successful.OK

    startWebServer config appDemo

If I run the above webserver and hit it several times then each time I get the same timestamp back. Which I guess makes sense; appDemo is just an expression which is calculated first time around and never again, right?

In this circumstance, I might want appDemo to be 'recalculated' for every request. How do I do that? I can't seem to find an example in the docs.

Ferguson answered 8/10, 2016 at 10:2 Comment(0)
F
9

Try this - not sure how high it scores on "idiomatic Suave" scale though:

let appDemo:WebPart = 
    request (fun req -> 
        DateTime.Now.ToString()
        |> sprintf "Server timestamp: %s"
        |> Successful.OK)

You're right in that you're seeing the same value because it's captured at the time appDemo is evaluated. That's a property of how F# works however, and has nothing to do with Suave caching it.

Note that WebPart type is an alias for HttpContext -> Async<HttpContext option> function - so inherently it yields itself to being recalculated on each request rather than being calculated once.

Faso answered 8/10, 2016 at 10:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.