UNPKG

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