UNPKG

2.49 kBMarkdownView Raw
1 build_backend = ({changes,view_changes,semantic,get_key,view_key,fromJS}) ->
2
3The backend return a function that can be provided to `backend_join`.
4
5 (sources) ->
6
7For `update` events it will update the document.
8
9 route = sources
10 .filter operation UPDATE
11 .thru changes_semantic
12
13 route.create.forEach semantic.create
14 route.update.forEach semantic.update
15 route.delete.forEach semantic.delete
16
17For `subscribe` events it will GET the document and then notify on that current value
18and on any future changes. (This is equivalent to a `@most/hold` on the entire database
19viewed as a stream, basically, but uses little ressources.)
20
21 subscriptions_keys =
22 sources
23 .filter operation SUBSCRIBE
24 .map Key
25 .multicast()
26
27No action is needed for `unsubscribe` events.
28
29Fetch current value, return a message similar to a row from `_all_docs`.
30
31 values =
32 subscriptions_keys
33 .filter is_string # Can only retrieve string keys from a database
34 .map get_key
35 .chain most.fromPromise
36 .filter not_null
37
38Compute values for wandering-country-view/all by querying the server-side view.
39
40 view_values =
41 subscriptions_keys
42 .chain view_key
43
44
45The output is the combination of:
46
47 most.mergeArray [
48
49- subscriptions to document changes in the database
50
51 changes.map (msg) ->
52 Immutable.fromJS msg
53 .merge
54 op: NOTIFY
55 value: rev: msg.doc._rev # or msg.changes[0].rev
56 doc: fromJS msg.doc
57 key: msg.id
58
59- requested documents in the database
60
61 values.map (doc) ->
62 Immutable.Map
63 op: NOTIFY
64 id: doc._id
65 key: doc._id
66 value: rev: doc._rev
67 doc: fromJS doc
68
69- subscriptions to changes in the view
70
71 view_changes.map (msg) ->
72 Immutable.fromJS msg
73 .set 'op', NOTIFY
74
75- requested entries in the view
76
77 view_values.map (msg) ->
78 Immutable.fromJS msg
79 .set 'op', NOTIFY
80
81 ]
82
83 module.exports = build_backend
84 changes_semantic = require 'red-rings-semantic'
85 {operation,Key,is_string,is_object,not_null,has_key} = require 'abrasive-ducks-transducers'
86 Immutable = require 'immutable'
87 most = require 'most'
88 {UPDATE,SUBSCRIBE,UNSUBSCRIBE,NOTIFY} = require 'red-rings/operations'