-
-
Save wilkerlucio/d9cdffb9e30570846a4297057e2dba6f to your computer and use it in GitHub Desktop.
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
(ns com.wsscode.pathom3.demos.api-quotas | |
(:require [com.wsscode.pathom3.connect.operation :as pco] | |
[com.wsscode.pathom3.connect.indexes :as pci] | |
[com.wsscode.pathom3.interface.eql :as p.eql] | |
[com.wsscode.pathom3.plugin :as p.plugin] | |
[com.wsscode.pathom3.connect.planner :as pcp])) | |
(defonce user-quotas (atom {})) | |
(pco/defresolver costly-resolver [] | |
{:quota/cost 10} | |
{:response "value"}) | |
(pco/defresolver free-resolver [] | |
{:free "value"}) | |
(p.plugin/defplugin quotas-plugin | |
{:com.wsscode.pathom3.connect.runner/wrap-resolve | |
(fn [resolve] | |
(fn [{:quota/keys [limit current-user] :as env} input] | |
(let [{:quota/keys [cost]} | |
(pci/resolver-config env | |
(-> env ::pcp/node ::pco/op-name))] | |
; check if resolver needs quota | |
(if cost | |
(let [user-quota (get @user-quotas current-user 0) | |
new-quota (+ user-quota cost)] | |
(if (<= new-quota limit) | |
(do | |
; add cost | |
(swap! user-quotas update current-user (fnil + 0) cost) | |
(resolve env input)) | |
(throw (ex-info "Exceed user quota" {:user-quota (- limit user-quota) | |
:required-quota cost})))) | |
(resolve env input)))))}) | |
(def env | |
(-> {:quota/limit 50} | |
(pci/register | |
[costly-resolver | |
free-resolver]) | |
(p.plugin/register quotas-plugin))) | |
(comment | |
(let [env (assoc env :quota/current-user "user-name")] | |
(p.eql/process env | |
[:response :free]))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment