You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.4 KiB

(ns blog.db
(:require ["pg" :refer [Client]]
[cljs.core.async :refer [go, take!, put!, >!, chan]]
[cljs.core.async.interop :refer-macros [<p!]]
[blog.env :as env]))
(defn create-client
"Create a new client for Postgres using enviroment variables."
[]
(->> (env/get-database-credentials)
(cljs.core/clj->js)
(new Client)))
(defn connect-client
"Connect a client to the database"
[client]
(. client connect))
(defn create-tables
[client]
(. client query "CREATE TABLE IF NOT EXISTS articles (id SERIAL PRIMARY KEY, title VARCHAR(255) NOT NULL, content TEXT NOT NULL, created TIMESTAMP DEFAULT CURRENT_TIMESTAMP);"))
(defn get-articles
"Reads all articles and returns via channel. It gets and returns the same channel."
[client channel]
(go
(try
(let [res (<p! (. client query "select * from articles"))]
(>! channel (.-rows res)))
(catch js/Error err (js/console.log (ex-cause err)))))
channel)
(defn get-article
"Reads an article with the id and returns via channel. It gets and returns the same channel. Empty collection if not found."
[client id channel]
(go
(try
(let [res (<p! (.query client
"select * from articles where id=$1"
(cljs.core/clj->js [id])))]
(>! channel (.-rows res)))
(catch js/Error err (js/console.log (ex-cause err)))))
channel)