Last active
March 3, 2020 13:42
-
-
Save wilkerlucio/a096df18f65fbbf57f62cf96bc168e8d to your computer and use it in GitHub Desktop.
Pathom cache extension example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn cache-resolver [resolver] | |
(update resolver ::pc/resolve | |
(fn [resolve] | |
(fn [{::keys [persistent-cache*] :as env} input] | |
(let [cache-key [(::pc/sym resolver) input (p/params env)]] | |
(if-let [[_ v] (find @persistent-cache* cache-key)] | |
v | |
(let [response (resolve env input)] | |
(swap! persistent-cache* assoc cache-key response) | |
response))))))) | |
(pc/defresolver cached-resolver [env {:keys []}] | |
{::pc/output [:some-value] | |
::pc/transform cache-resolver} | |
{:some-value (gensym "random")}) | |
(def registry | |
[cached-resolver]) | |
(def parser | |
(p/parser | |
{::p/env {::p/reader [p/map-reader | |
pc/reader2 | |
pc/open-ident-reader | |
p/env-placeholder-reader] | |
::p/placeholder-prefixes #{">"}} | |
::p/mutate pc/mutate | |
::p/plugins [(pc/connect-plugin {::pc/register registry}) | |
p/error-handler-plugin | |
p/trace-plugin]})) | |
(defonce global-atom-persistent-cache* (atom {})) | |
(comment | |
; re-create cache, will always get a fresh value | |
(parser {::persistent-cache* (atom {})} | |
[:some-value]) | |
; with the persistent cache, the value will remain constant | |
(parser {::persistent-cache* global-atom-persistent-cache*} | |
[:some-value])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment