add image route support for the remaining parameters

This commit is contained in:
Gered 2014-03-30 11:07:31 -04:00
parent 3ba5bb3937
commit e91a6f50a7
2 changed files with 40 additions and 11 deletions

View file

@ -4,20 +4,32 @@
[liberator.core :refer [defresource]]
[compojure.core :refer [ANY]]
[toascii.route-utils :refer [register-routes]]
[toascii.models.image :refer [convert-image get-image-by-url]]))
[toascii.models.image :refer [convert-image get-image-by-url]]
[toascii.util :refer [parse-int parse-boolean]]))
(defn- color? [color]
(if (nil? color)
true
(parse-boolean color)))
(defresource render-image [{:keys [url width color format] :as params}]
:media-type-available?
(fn [ctx]
(let [type (condp = format
"html" "text/html"
"text" "text/plain"
"text/html")]
{:representation {:media-type type}}))
(if (color? color)
{:representation {:media-type "text/html"}}
(let [type (condp = format
"html" "text/html"
"text" "text/plain"
"text/html")]
{:representation {:media-type type}})))
:malformed?
(fn [_]
(cond
(str/blank? url) {:error "Missing image url"}))
(str/blank? url)
{:error "Missing image url"}
(and width (nil? (parse-int width)))
{:error "Invalid image width."}))
:exists?
(fn [_]
(if-let [image (get-image-by-url url)]
@ -25,10 +37,10 @@
[false {:error "Image could not be loaded."}]))
:handle-ok
(fn [ctx]
(let [rendered (convert-image (:image ctx) true)]
(if (= "text/html" (get-in ctx [:representation :media-type]))
rendered
rendered)))
(convert-image
(:image ctx)
(parse-int width)
(color? color)))
:handle-malformed
(fn [ctx]
(:error ctx))

View file

@ -59,3 +59,20 @@
(url/url)
(encode-url-path-components)
(URL.)))
(defn parse-int [s]
(try
(Integer/parseInt s)
(catch Exception ex)))
(defn parse-boolean [x]
(let [x (if (string? x)
(-> x (.toLowerCase) (.trim))
x)]
(condp = x
"false" false
false false
"0" false
0 false
nil false
true)))