Skip to content

Commit

Permalink
user: Add update! function to user entity
Browse files Browse the repository at this point in the history
  • Loading branch information
goshatch committed Sep 13, 2024
1 parent 1549d5c commit 6f7b901
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/apossiblespace/parts/entity/user.clj
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,23 @@
(:require
[apossiblespace.parts.db :as db]))

(def allowed-update-fields #{:email :display_name :password})

(defn- validate-attrs [attrs]
(when (= {} attrs) (throw (ex-info "Nothing to update" {:type :validation})))
(when-let [{:keys [password password_confirmation]} attrs]
(when (and password (not= password password_confirmation))
(throw (ex-info "Password and confirmation do not match" {:type :validation})))
attrs))

(defn- sanitize-attrs [attrs]
(-> attrs
(select-keys allowed-update-fields)
)
(select-keys attrs allowed-update-fields))

(defn fetch
"Retrieve a user record from the database, or throw if not found"
"Retrieve a user record from the database"
[id]
(if-let [user (db/query-one
(db/sql-format
Expand All @@ -12,3 +27,14 @@
:where [:= :id id]}))]
user
(throw (ex-info "User not found" {:type :not-found}))))

(defn update!
"Update a user record with provided attributes"
[attrs]
(when (not (contains? attrs :id)) (throw (ex-info "Missing User ID" {:type :validation})))
(let [id (:id attrs)
sanitized-attrs (-> attrs
sanitize-attrs
validate-attrs)
updated-user (first (db/update! :users sanitized-attrs [:= :id id]))]
updated-user))
8 changes: 8 additions & 0 deletions test/apossiblespace/parts/entity/user_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,11 @@
(testing "throws when an invalid ID is passed"
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"User not found"
(user/fetch "random")))))

(deftest test-update!
(testing "saves the user entity to the database"
(let [db-user (register-test-user)
updated-user (user/update!
{:id (:id db-user)
:display_name "Bobby"})]
(is (= (:display_name updated-user) "Bobby")))))

0 comments on commit 6f7b901

Please sign in to comment.