aleeusgr / hs-clojure

Other
0 stars 0 forks source link

Add filtering #18

Closed aleeusgr closed 2 months ago

aleeusgr commented 3 months ago

To add a function to return filtered database entries, you can create a new function in your patients.clj file. Here's an example:

(defn get-patients-by-filter
  [spec filter-map]
  (db-patients/get-patients-by-filter db/spec filter-map))

(defn get-patients-by-name
  [spec name]
  (get-patients-by-filter spec {:name name}))

(defn get-patients-by-sex
  [spec sex]
  (get-patients-by-filter spec {:sex sex}))

(defn get-patients-by-date-of-birth
  [spec date-of-birth]
  (get-patients-by-filter spec {:date_of_birth date-of-birth}))

In the above code, we've added a get-patients-by-filter function that takes a spec and a filter map as arguments. This function will query the database using the filter map.

We've also added three convenience functions: get-patients-by-name, get-patients-by-sex, and get-patients-by-date-of-birth. These functions call get-patients-by-filter with a specific filter map.

You'll also need to add a function to your db.patients namespace to handle the filtering:

(defn get-patients-by-filter
  [spec filter-map]
  (jdbc/query spec
             (str "SELECT * FROM patients WHERE "
                  (clojure.string/join " AND "
                                       (map (fn [[k v]]
                                              (str (name k) " = ?"))
                                            filter-map))
                  " ORDER BY id ASC")
             (vals filter-map)))

This function generates a SQL query based on the filter map and executes it using jdbc/query.

You can then use these functions in your routes to filter patients. For example:

(defroutes patient-routes
  ...
  (GET "/patients/by-name/:name" [name]
    (let [patients (patients/get-patients-by-name db/spec name)]
      {:status 200
       :headers {"Content-Type" "application/json"}
       :body (json/generate-string patients)}))
  ...)

This route will return a JSON response with patients filtered by name.

Remember to update your routes.clj file to include the new routes and functions.