Skip to content

Instantly share code, notes, and snippets.

@eval
Last active February 15, 2024 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eval/5af8064aa31bb981f573c3b4a9bb6684 to your computer and use it in GitHub Desktop.
Save eval/5af8064aa31bb981f573c3b4a9bb6684 to your computer and use it in GitHub Desktop.
deps-try recipe to step through examples of https://www.juxt.pro/blog/uri-templates/
;; Use this file with [deps-try](https://github.com/eval/deps-try)
;; $ deps-try --recipe https://gist.github.com/eval/5af8064aa31bb981f573c3b4a9bb6684/raw
(ns recipes.juxt-blog-uri-template
"Recipe to step through the examples from https://www.juxt.pro/blog/uri-templates/"
{:deps-try.recipe/deps ["https://github.com/juxt/reap"]}
(:require [juxt.reap.rfc6570 :refer [compile-uri-template make-uri match-uri]]))
;; helper-fns
(defn render [tpl variables]
(make-uri (compile-uri-template tpl) variables))
(defn extract [tpl variable-types uri]
(match-uri
(compile-uri-template tpl)
variable-types
uri))
;; TIP to eval single expression place cursor behind it and press Ctrl-c Ctrl-e
;; TIP submit step with Ctrl-x Ctrl-m
;;
;; simple URI template
(def tpl1 "http://example.com/~{username}/")
;; render
(make-uri (compile-uri-template tpl1) {:username "malcolm"})
;; same but using the recipe helper
(render tpl1 {:username "malcolm"})
;; More complex template
(def tpl2 "https://{env}bank.com{/ctx*}/accounts/{accno}/transactions{.format}{?from,to}{#frag}")
;; env - An optional string so we can generate, say, https://uat.bank.com for testing.
;; /ctx* - The forward-slash indicates this is a path segment. The asterisk modifies this to mean it can have multiple segments.
;; accno - This will be the account number of our bank account.
;; .format - This might be .csv or .json.
;; from - The start of the date range.
;; to - The end of the date range.
;; #frag - An optional fragment, the #-prefix indicates ‘fragment expansion’.
;; render
(render tpl2 {:ctx ["europe" "uk"]
:accno "12345678"
:format "csv"
:from "20201010"
:to "20201110"})
;; The reverse: extract data from a uri.
(match-uri
(compile-uri-template tpl2)
;; Specify the types of the variables we want to extract
{:env :string
:frag :string
:accno :string
:ctx :list
:format :string
:from :string
:to :string}
"https://bank.com/europe/uk/accounts/12345678/transactions.csv?from=20201010&to=20201110")
;; same but using the recipe helper-fn
(extract tpl2
{:env :string
:frag :string
:accno :string
:ctx :list
:format :string
:from :string
:to :string}
"https://bank.com/europe/uk/accounts/12345678/transactions.csv?from=20201010&to=20201110")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment