Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@currentoor currentoor commented Dec 26, 2015

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