@@ -25,6 +25,11 @@ Algebraic effects bring a multitude of advantages:
25
25
It's easier to understand what it allows by seeing it in action:
26
26
27
27
``` javascript
28
+ // create your effects
29
+ const getAuth = effect ()
30
+ const getUser = effect ()
31
+ const sendNotification = effect ()
32
+
28
33
// write your program in direct style using the generator do notation
29
34
const onUserClick = eff (function * () {
30
35
// get the current request from express
@@ -43,22 +48,28 @@ It's easier to understand what it allows by seeing it in action:
43
48
const result = yield sendNotification (subscriber, ' clicked' , { details: mouseEvent, user, token })
44
49
45
50
return { user, subscriber, result }
46
- }) // returns [{ user, subscriber1, result1 }, { user, subscriber2, result2 }, ...],
47
- // the return value depends on how you use the handlers
51
+ })
52
+
53
+ // handle your effects
54
+ express .post (' actions/user-clicked' , async (req , res ) => {
55
+ const withDependencies = handler ({
56
+ getAuth : () => resume (req .auth ),
57
+ getUser : (id ) => getFirebaseUser (... ),
58
+ sendNotification : (subscriber , type , data ) => sendFirebaseNotification (... ),
59
+ })
60
+ const result = await run (pipe (
61
+ onUserClick,
62
+ handleError ((e ) => e instanceof MissingTokenError && cachedUser ? resume (cachedUser, k) : raise (e)) // recover with CachedUser if possible
63
+ withDependencies,
64
+ withForEach,
65
+ ))
66
+ // the final value depends on how you order the handlers
67
+ console .log (result) // [{ user, subscriber1, result1 }, { user, subscriber2, result2 }, ...],
68
+
69
+ res .send (result)
70
+ })
48
71
```
49
72
50
- Handle them later
51
-
52
- ``` javascript
53
- express .post (' actions/user-clicked' , (req , res ) => {
54
- const withDependencies = handler ({
55
- getAuth : () => resume (req .auth ),
56
- error : (e ) => e instanceof MissingTokenError && cachedUser ? resume (cachedUser) : raise (e),
57
- sendNotification : (subscriber , type , data ) => sendFirebaseNotification (... ),
58
- })
59
- run (withDependencies (onUserClick))
60
- })
61
- ```
62
73
63
74
All of the effects (request, getUser, sendNotification, etc) are highly testable, and can be replaced with testing/production/alternative versions.
64
75
0 commit comments