Skip to content

Instantly share code, notes, and snippets.

@athomasoriginal
Last active December 2, 2020 19:04
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 athomasoriginal/bfcb1e6e9e9bc9d318725a6e7d9315b8 to your computer and use it in GitHub Desktop.
Save athomasoriginal/bfcb1e6e9e9bc9d318725a6e7d9315b8 to your computer and use it in GitHub Desktop.
;; API Design Question - Do you like V1 or V2 convenience functions?
;; -------------------------------------------------------------------
;; http clients canbe structured in the following way. There is a
;; base layer performing low level tasks. In this example, we pretend
;; its the `request` function below. Then there are conveniences like
;; `get` and `post` (and so on for the rest of the HTTP methods). The
;; question is, do people like the callsite of `option 1` or
;; `option 2`?
(defn request
"I return a promise"
[url opts]
(-> (js/fetch)
(.then handle-client-errors)
(.then handle-decode-body)
(.then handle-errors
;; convenience V1 - (just an example, the implementation is not the main Q)
(defn get
"Return promise"
([url])
(get url nil)
([url opts]
(request url opts))
;; convenience V2 - (just an example, the implementation is not the main Q)
(defn get
"Return promise"
[{:keys [url opts on-success on-failure]}]
(-> (request url opts)
(.then on-success)
(.catch on-failure))
;; Example Callsites
;; -------------------------------------------------------------------
;; V1
(-> (get "api/courses" {})
(.then handle-success)
(.catch handle-failure))
;; V2
(get
{:url "api/courses"
:opts opts
:on-success handle-success
:on-failure handle-failure}
@athomasoriginal
Copy link
Author

athomasoriginal commented Nov 25, 2020

Convenience V1

Pros

  • more control of handling the promise chain

Cons

  • A description of how to do it

Convenience V2

Pros

  • Build requests programmatically because the arg is just a data structure
  • Don't have to think about chaining
  • All the options are named and therefore (perhaps) more discoverable
  • call site looks cleaner
  • predictable as the implementation is the same no matter the method (yes, more keys for some over others)
  • The handle-success might not need to think about the callsite requirement of handling a promise e.g. (fn e) is the expectation. With the above, the user only considers the return value of the a successful API call (which is often just the body)
  • A description of what I want to do

Cons

  • less control over the promise chain

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