Skip to content

Instantly share code, notes, and snippets.

@currentoor
Last active January 11, 2016 23:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save currentoor/dcdfbe4d8e99513a4135 to your computer and use it in GitHub Desktop.
Save currentoor/dcdfbe4d8e99513a4135 to your computer and use it in GitHub Desktop.
Reset the components of an entity without worrying about the current values or their entity-ids.
(defn reset-components [db eid attr new-comps]
(let [current-comps (-> (d/pull db [attr] eid) attr)
;; First we do a value based comparison ignoring component entity ids.
current-comp-vals (into #{} (map #(dissoc % :db/id) current-comps))
new-comp-vals (into #{} new-comps)
deletions (clojure.set/difference current-comp-vals new-comp-vals)
additions (clojure.set/difference new-comp-vals current-comp-vals)
;; Then we retract components based on value comparison above.
deletion-txn (->> (filter (fn [m] (contains? deletions
(dissoc m :db/id)))
current-comps)
(map (fn [e] [:db.fn/retractEntity (:db/id e)])))
addition-txn [{:db/id eid attr additions}]]
(concat deletion-txn addition-txn)))
@currentoor
Copy link
Author

Say you have an entity with a component

{:task/id                #uuid "567ef544-825c-45df-81ef-f5ebe1c54eba"
 :task/name              "Garbage Day!"
 :task/automation-entity [{:automation-entity/adstage-id "/foo/foo"
                           :automation-entity/name       "foo"
                           :automation-entity/type       "foo"}]}

You can reset this entity's component like so

(reset-components (d/db conn)
                  [:task/id #uuid "567ef544-825c-45df-81ef-f5ebe1c54eba"]
                  :task/automation-entity
                  [{:automation-entity/adstage-id "/bar/bar"
                    :automation-entity/name       "bar"
                    :automation-entity/type       "bar"}])

This function will generate the appropriate addition/retraction transactions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment