summaryrefslogtreecommitdiff
path: root/lib/cache.fnl
blob: fdde74cd575156cd17f131ff5a6cc6a254670d8b (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
(local {: must} (require :lib.utils))

(fn get [db key else]
  (local result
    (must (luna.db.query db "SELECT value FROM cache WHERE key = ?"
                         [key])))
  (or (if (and result (< 0 (# result)))
        (. (. result 1) 1)
        nil)
      else))

(fn _set [db key value]
  value
  (must (luna.db.exec db "INSERT OR REPLACE INTO cache VALUES (?, ?)"
                      [key value]))
  value)

(fn clear [db prefix]
  (if (= "string" (type prefix))
    (must (luna.db.exec db "DELETE FROM cache WHERE key LIKE ?"
                           [(.. prefix "%")]))
    (must (luna.db.exec db"DELETE FROM cache" []))))

(fn wrap [db key f]
 (local cached (get db key))
 (if cached
   cached
   (let [res (f)]
     (if res (_set db key res) nil))))

{:get get :set _set :clear clear :wrap wrap}