summaryrefslogtreecommitdiff
path: root/src/chef/pages/admin/api.clj
diff options
context:
space:
mode:
Diffstat (limited to 'src/chef/pages/admin/api.clj')
-rw-r--r--src/chef/pages/admin/api.clj57
1 files changed, 46 insertions, 11 deletions
diff --git a/src/chef/pages/admin/api.clj b/src/chef/pages/admin/api.clj
index f1b7226..1119607 100644
--- a/src/chef/pages/admin/api.clj
+++ b/src/chef/pages/admin/api.clj
@@ -1,9 +1,12 @@
(ns chef.pages.admin.api
(:require [chef.utils :as cutils]
[chef.database :as cdb]
+ [clojure.string :as cstr]
[next.jdbc :as jdbc]
[honey.sql :as sql]
- [ring.util.response :as ruresp]))
+ [ring.util.response :as ruresp]
+ [clojure.java.io :as cjio])
+ (:import java.io.File))
(defn create-category [req]
(cutils/auth-only req
@@ -74,18 +77,50 @@
(ruresp/header "HX-Refresh" "true")))
(ruresp/bad-request "Bad request."))))
-;;TODO: validate request
(defn edit-recipe [req]
(cutils/auth-only req
+ (let [id (try (Integer/parseInt (get-in req [:path-params :id]))
+ (catch Exception _ nil))
+ ingredients (get-in req [:params "ingredients"])]
+ (if (and (some? id)
+ (cutils/valid-ingredients? ingredients))
+ (do (when-let [thumbnail (get-in req [:params "thumbnail"])]
+ (when-let [existing-thumbnail-file (->> {:select [:*]
+ :from [:recipes]
+ :where [:= :id id]}
+ sql/format
+ (jdbc/execute! @cdb/db)
+ first
+ cutils/get-thumbnail-file)]
+ (.delete ^File existing-thumbnail-file))
+ (cjio/copy (:tempfile thumbnail)
+ (File. (str "./thumbnails/" id "."
+ (-> thumbnail
+ :filename
+ (cstr/split #"\.")
+ last)))))
+ (jdbc/execute! @cdb/db
+ (sql/format {:update :recipes
+ :set {:title (get-in req [:params "title"])
+ :category (get-in req [:params "category"])
+ :unit (get-in req [:params "ingredients-unit"])
+ :ingredients ingredients
+ :preparation (get-in req [:params "preparation"])}
+ :where [:= :id id]}))
+ (ruresp/response "Saved."))
+ (ruresp/bad-request "Bad request.")))))
+
+(defn delete-thumbnail [req]
+ (cutils/auth-only req
(if-let [id (try (Integer/parseInt (get-in req [:path-params :id]))
(catch Exception _ nil))]
- (do (jdbc/execute! @cdb/db
- (sql/format {:update :recipes
- :set {:title (get-in req [:params "title"])
- :category (get-in req [:params "category"])
- :unit (get-in req [:params "ingredients-unit"])
- :ingredients (get-in req [:params "ingredients"])
- :preparation (get-in req [:params "preparation"])}
- :where [:= :id id]}))
- (ruresp/response "Saved."))
+ (when-let [thumbnail-file (->> {:select [:*]
+ :from [:recipes]
+ :where [:= :id id]}
+ sql/format
+ (jdbc/execute! @cdb/db)
+ first
+ cutils/get-thumbnail-file)]
+ (.delete ^File thumbnail-file)
+ (ruresp/response "Done."))
(ruresp/bad-request "Bad request."))))