summaryrefslogtreecommitdiff
path: root/pages/shop/cart/add.fnl
blob: 36e3e41bcc014e9970114bd7043008c640bcc4aa (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
(local lib (require :lib))

(fn create-order [db]
  (let [id (_G.must (luna.crypto.random-string 64))]
    (_G.must
     (luna.db.exec
       db "INSERT INTO orders (id, creation_time) VALUES (?, ?)"
       [id (lib.now)]))
    id))

(fn create-order-line [db order-id name quantity]
  (_G.must
    (luna.db.exec
      db
      "INSERT INTO order_lines (order_id, product_name, quantity) VALUES (?, ?, ?)"
      [order-id name quantity])))

(fn render [request db]
  (if (= request.method "POST")
    (do
      (var order-id (lib.order-id request))
      (var headers
       (if (not order-id)
         (do
          (set order-id (create-order db))
          {:Set-Cookie (.. "order= " order-id "; HttpOnly; SameSite=strict"
                           (if luna.debug? "" "; Secure"))})
         {}))

      (if (and order-id request.body)
        (let [body-values (lib.parse-values request.body)]
          (create-order-line db order-id body-values.name body-values.quantity)
          (tset headers :Location "/shop")
          (values 302 headers ""))
        (values 400 {} "bad body")))
    (values 404 {} "not found")))

{: render}