Testing Spiffy and Intarweb added by avalos on Sat Jul 18 19:15:54 2020

(import (chicken format)
        (chicken port)
        (chicken io)
        spiffy
        intarweb
        uri-common
        spiffy-uri-match
        medea
        postgresql)

;; Database
(define conn
  (connect '((dbname . chicken_employees)
             (user . playground)
             (password . "xxxxxxxxxxxxx"))))

(define (db-auto-migrate)
  (query conn (string-append "CREATE TABLE IF NOT EXISTS employees ("
                             "id     int PRIMARY KEY NOT NULL,"
                             "name   varchar(255) NOT NULL,"
                             "salary real NOT NULL,"
                             "age    smallint NOT NULL"
                             ");")))

;; Record types
(define-record employee id name salary age)

;; Route handlers
(define (handle-get-all-employee continue)
  (send-status 200 "GET /employee")
  (continue))

(define (handle-create-employee continue)
  ;; This is the part where it gets stuck
  ;; Until connection is broken by the client.
  ;; Probably caused by read-string.
  (print (read-string #f (request-port (current-request))))
  (send-status 200 "Done"))

(define (handle-get-employee continue id)
  (send-status 200 (format #f "GET /employee/~A" id))
  (continue))

(define (handle-update-employee continue id)
  (send-status 200 (format #f "PUT /employee/~A" id))
  (continue))

(define (handle-delete-employee continue id)
  (send-status 200 (format #f "DELETE /employee/~A" id))
  (continue))

(vhost-map `(("localhost" . ,(uri-match/spiffy
                              `(((/ "employee")
                                 (GET ,handle-get-all-employee)
                                 (POST ,handle-create-employee))
                                ((/ "employee" (submatch (+ num)))
                                 (GET ,handle-get-employee)
                                 (PUT ,handle-update-employee)
                                 (DELETE ,handle-delete-employee)))))))

(define (main)
  (db-auto-migrate)
  (server-port 8000)
  (start-server))
(main)