summaryrefslogtreecommitdiff
path: root/flash.lisp
blob: 09818b0e92beedb85dcca185405ec9f3958c4d7a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
;;;; flash.lisp -- communicating between page loads

(in-package :dnd)

(defvar *flashes*
  (make-hash-table :test #'equal :synchronized t))

(defparameter +flash-cookie-name+ "DNDFLASHKEY")
(defparameter +flash-value-lifetime+ 10
  "Number of seconds a flashed value lives.")

(defstruct flash-entry
  (timestamp (get-universal-time))
  (table nil))

(defun flash-entry-alive-p (entry)
  "Returns T if ENTRY has not expired."
  (<= (get-universal-time)
      (+ (flash-entry-timestamp entry) +flash-value-lifetime+)))

(defun flash (label value)
  "A flash is a one-time inter-request value. Once stored, it can only
be retrieved once. And if not retrieved in a short period of time, it
expires."
  (check-type label keyword)
  (let* ((key
           (or (lzb:request-cookie +flash-cookie-name+) (nuid)))
         (now
           (get-universal-time))
         (entry
           (gethash key *flashes* (make-flash-entry))))
    ;; update the entry
    (setf (flash-entry-timestamp entry) now
          (getf (flash-entry-table entry) label) value
          (gethash key *flashes*) entry)
    ;; set the cookie, updating its expiration if necessary 
    (lzb:set-response-cookie
     +flash-cookie-name+ key
     ;; TODO: generalize domain
     :path "/" :domain "localhost" 
     :expires (+ +flash-value-lifetime+ now))))


(defun flashed-value (label)
  "Retrieves and deletes the flashed value with label LABEL associated
with this request. If the value exists, return it. Otherwise return
NIL."
  (a:when-let* ((key (lzb:request-cookie +flash-cookie-name+))
                (entry (gethash key *flashes*)))
    (cond
      ((flash-entry-alive-p entry)
       (let ((val (getf (flash-entry-table entry) label)))
         ;; can only retrieve once
         (remf (flash-entry-table entry) label)
         val))
      (t
       ;; drop expired entries and return nil
       (remhash key *flashes*)
       nil))))