 (defresource document-download [id]
   :allowed-methods #{:get}
   :available-media-types ["application/pdf"]
+  :malformed? (fn [ctx]
+                (try [false {::id (Integer/parseInt id)}]
+                     (catch NumberFormatException e
+                       true)))
   :exists? (fn [ctx]
              (let [db (get-in ctx [:request ::db])
                    id (Integer/parseInt id)

(defresource page [id]
  :allowed-methods #{:get}
  :available-media-types ["application/transit+json"]
  :exists? (fn [ctx]
             (when-let [page (first (m/get-pages (get-in ctx [:request ::db])
                                                 [(Integer/parseInt id)]))]
               {::page (select-keys page
                                    [:id :render-status :rotation])}))
  :handle-ok ::page)

(defresource page-image [id size]
  :allowed-methods #{:get}
  :available-media-types ["image/png"]
  :exists? (fn [ctx]
             (try
               (let [db (get-in ctx [:request ::db])
                     config (get-in ctx [:request ::config])
                     [{:keys [image hash]}] (if (= size ::max)
                                              (db/query db ["SELECT image, hash FROM page_images WHERE page = ? ORDER BY dpi DESC LIMIT 1"
                                                            (Integer/parseInt id)])
                                              (db/query db ["SELECT image, hash FROM page_images WHERE page = ? AND dpi = ?"
                                                            (Integer/parseInt id) (Integer/parseInt size)]))]
                 (when image
                   {::page (ByteArrayInputStream. image)
                    ::hash hash}))

(defresource document [id]
  :allowed-methods #{:get :post}
  :available-media-types +default-media-types+
  :malformed? (fn [ctx]
                (try [false {::id (Integer/parseInt id)}]
                     (catch NumberFormatException e
                       true)))
  :exists? (fn [ctx]
             (when-let [d (m/get-document (get-in ctx [:request ::db]) (::id ctx))]
               {::document d}))
  :post-redirect? true
  :location (fn [ctx] (str "/documents/" id))
  :post! (fn [ctx]
