clojurecompojurekormasqlkorma

How to convert korma select results to json for a rest service (compojure)?


I am using compojure, cheshire and korma (and postgre db) for creating a rest service. I've created a table with two string fields (name and description) with such structure:

(defentity posts
  (pk :id)
  (table :posts)
  (entity-fields :name :description))

I can insert records into this table but when I try to exec

(defn get-all-posts [] 
  (select posts))

and return the results from the server

defroutes app-routes
 (GET "/" [] (get-start))
 (context "/posts" []
   (GET "/" [] (get-all-posts))
 ...

I receive such an error: java.lang.IllegalArgumentException No implementation of method: :render of protocol: #'compojure.response/Renderable found for class: clojure.lang.PersistentVector

As I see I need to convert posts collection to json. How to do it?


Solution

  • Ring responses can be either a map or a string. If they are a map then they use a few keys such as :status and :body to define the response and set cookies etc. You may want to explicitly convert your response from a Clojure sequence (edn) to JSON by wrapping the call to (get-all-posts) in generate-string (since you are using Cheshire) :

     {:status 200
      :content-type "application/json; charset=UTF-8"
      :body (cheshire/generate-string (get-all-posts))}
    

    And while you are at it it can't hurt to specify the content type and response code.