-
-
Notifications
You must be signed in to change notification settings - Fork 62
Entities
Entities are one of the most important concepts to grasp about pathom. If you think of nodes on a graph, a node has its own information and the connections with other nodes. Using this as a parallel, the entity
in pathom is the representation of the current node value, this is where you are taking the information to navigate on the graph. The entity is usually a Clojure map, but that's not a hard constraint, you can use whatever you want to represent the current entity, just take something from where you can derive the information from (although maps/map-like things a more straightforward support).
Pathom uses a commonplace to represent the entity in the environment. By default, it sits at ::p/entity
. Having it in a common place (instead of say, having a customer entity at a :customer
key) gives the opportunity to write generic readers to handle common situations (like the map-reader
we will see later).
To get the entity use the p/entity
function:
(ns com.wsscode.pathom-docs.using-entity
(:require [com.wsscode.pathom.core :as p]))
(def attrs
; define the reader for the contact name
{:contact/name
(fn [env]
(let [e (p/entity env)]
(:contact/name e)))})
(def parser
(p/parser {::p/plugins [(p/env-plugin {::p/reader [attrs]})]}))
(comment
; we send the entity using ::p/entity key on environment
(parser {::p/entity #:contact{:name "Rick" :age 26}} [:contact/name])
; => #:contact{:name "Rick"}
)
This is a very simple example, we just fetch the same key, but since you have access to the environment you can do whatever you want to satisfy that reader inside of the function, be creative.
Reading from maps matching the :dispatch-key
to the map key is very common, so we have a helper for that, let's take a look.
Let's re-write our previous example, now using the map-reader
:
(ns com.wsscode.pathom-docs.using-entity-map-reader
(:require [com.wsscode.pathom.core :as p]))
(def parser
(p/parser {::p/plugins [(p/env-plugin {::p/reader [p/map-reader]})]}))
(comment
; we send the entity using ::p/entity key on environment
(parser {::p/entity #:contact{:name "Rick" :age 26}}
[:contact/name :contact/age :contact/foobar])
; => #:contact{:name "Rick", :age 26, :foobar :com.wsscode.pathom.core/not-found}
)