;; lib/dream/demos/counter.sx — per-session visit counter (counter.ml).
;; Demonstrates the session middleware: each browser session keeps its own count.

(define
  dream-counter-handler
  (fn
    (req)
    (let
      ((n (+ 1 (or (dream-session-field req "count") 0))))
      (begin
        (dream-set-session-field req "count" n)
        (dream-html (str "<p>You have visited this page " n " time(s).</p>"))))))

;; reset clears the session counter
(define
  dream-counter-reset
  (fn
    (req)
    (begin
      (dream-set-session-field req "count" 0)
      (dream-redirect "/"))))

(define
  dream-counter-app-with
  (fn
    (backend)
    ((dream-sessions backend)
      (dream-router
        (list
          (dream-get "/" dream-counter-handler)
          (dream-post "/reset" dream-counter-reset))))))

(define dream-counter-app (dream-counter-app-with (dream-memory-sessions)))

;; entry point: (dream-run (dream-counter-app-with (dream-memory-sessions)))
