Re-service allows re-frame user to easily define services. A service here is a named set of functions which provide co-effects and execute effects required or issued by re-frame event handlers. What re-service does is it translates re-frame co-effects/effects descriptors into service function calls return values.
A service can be defined using macros or function calls from maximgb.re-service.core
namespace.
To define a service and it’s implementation one have to:
-
define a service having application unique id
-
define set of named commands by providing command id and implementing function for the service registed
(ns my.service.core
(:require [maximgb.re-service.core :refer [def-re-service
def-re-service-command]
:include-macros true])) ;; (1)
(def-re-service ::my-service) ;; (2)
(def-re-service-command ::my-service ;; (3)
:sum ;; (4)
[cofx & args] ;; (5)
(apply + args)) ;; (6)
-
Require
maximgb.re-service.core
namespace and refer to service and command definition macros. -
Define service with application unique id
-
Define service command with:
-
- id
:sum
-
- variable list of arguments (non-variable lists are also allowed)
-
- implementing function body
When service is defined a corresponding re-frame’s co-effect and effect are registered using provided service id as co-effect/effect id.
Thus each service command can be invoked as co-effect via re-frame’s (inject-cofx)
or as effect requested
via (reg-event-fx)
or (reg-event-ctx)
return value.
To call service command as co-effect a user have to use (inject-cofx service-id [key? command-1-id [& args] command-2-id [& args]] …)
syntax.
Commands are executed in the order each command is called with the given arguments. The results will be added to re-frame’s co-effects
map under service-id
or key?
(if one has been provided) key. The key value will be a map keyed by command ids, map values will be set to
corresponding command invokation results.
ℹ️
|
If command is called as co-effect the first argument it recieves will be set to re-frame’s co-effects map. |
(reg-event-fx
::my-command
[(inject-cofx ::my-service [:sum [1 2 3 4] :mul [1 2 3 4]])] ;; (1)
(fn [cofx]
(let [my-sum (get-in cofx [::my-service :sum]) ;; (2)
my-mul (get-in cofx [::my-service :mul])] ;; (3)
(is (= my-sum 10) "Sum is correct")
(is (= my-mul 24) "Mul is correct"))
{}))
-
Injecting service co-effect, requesting two commands invokation (
:sum
and:mul
) each will recieve the same list of parameters -
Getting
:sum
command result -
Getting
:mul
command result
To call service command as effect a user have to add to re-frame’s effects map using service-id
as effect id a value designating
service commands invokation request (the value syntax is the same as for co-effect case)
(reg-event-fx
::my-command
(fn [cofx]
{::my-service [:sum [1 2 3 4] :mul [1 2 3 4]})) ;; (1)
-
Of course
:sum
and:mul
has no side-effects, thus calling’em as effects is meaningless, so here they are called for illustrative reasons only.