/
template.js
249 lines (218 loc) · 6.66 KB
/
template.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
'use strict';
const {remakeError} = require('../common/utils');
const assert = require('assert');
const vm = require('vm');
const ast = require('@horizon/client/lib/ast');
const validIndexValue = require('@horizon/client/lib/util/valid-index-value').default;
class Any {
constructor(values) {
this._values = values || [];
}
matches(value, context) {
if (value === undefined) {
return false;
} else if (this._values.length === 0) {
return true;
}
for (const item of this._values) {
if (template_compare(value, item, context)) {
return true;
}
}
return false;
}
}
// This works the same as specifying a literal object in a template, except that
// unspecified key/value pairs are allowed.
class AnyObject {
constructor(obj) {
this._obj = obj || { };
}
matches(value, context) {
if (value === null || typeof value !== 'object') {
return false;
}
for (const key in this._obj) {
if (!template_compare(value[key], this._obj[key], context)) {
return false;
}
}
return true;
}
}
// This matches an array where each item matches at least one of the values
// specified at construction.
class AnyArray {
constructor(values) {
this._values = values || [];
}
matches(value, context) {
if (!Array.isArray(value)) {
return false;
}
for (const item of value) {
let match = false;
for (const template of this._values) {
if (template_compare(item, template, context)) {
match = true;
break;
}
}
if (!match) {
return false;
}
}
return true;
}
}
class UserId { }
const wrap_write = (query, docs) => {
if (docs instanceof AnyArray ||
Array.isArray(docs)) {
query.data = docs;
} else {
query.data = [docs];
}
return query;
};
const wrap_remove = (doc) => {
if (validIndexValue(doc)) {
return {id: doc};
}
return doc;
};
// Add helper methods to match any subset of the current query for reads or writes
ast.TermBase.prototype.anyRead = function() {
return this._sendRequest(new Any(['query', 'subscribe']),
new AnyObject(this._query));
};
ast.Collection.prototype.anyWrite = function() {
let docs = arguments;
if (arguments.length === 0) {
docs = new AnyArray(new Any());
}
return this._sendRequest(
new Any(['store', 'upsert', 'insert', 'replace', 'update', 'remove']),
wrap_write(new AnyObject(this._query), docs));
};
// Monkey-patch the ast functions so we don't clobber certain things
ast.TermBase.prototype.watch = function() {
return this._sendRequest('subscribe', this._query);
};
ast.TermBase.prototype.fetch = function() {
return this._sendRequest('query', this._query);
};
ast.Collection.prototype.store = function(docs) {
return this._sendRequest('store', wrap_write(this._query, docs));
};
ast.Collection.prototype.upsert = function(docs) {
return this._sendRequest('upsert', wrap_write(this._query, docs));
};
ast.Collection.prototype.insert = function(docs) {
return this._sendRequest('insert', wrap_write(this._query, docs));
};
ast.Collection.prototype.replace = function(docs) {
return this._sendRequest('replace', wrap_write(this._query, docs));
};
ast.Collection.prototype.update = function(docs) {
return this._sendRequest('update', wrap_write(this._query, docs));
};
ast.Collection.prototype.remove = function(doc) {
return this._sendRequest('remove', wrap_write(this._query, wrap_remove(doc)));
};
ast.Collection.prototype.removeAll = function(docs) {
return this._sendRequest('remove', wrap_write(this._query,
docs.map((doc) => wrap_remove(doc))));
};
const env = {
collection: (name) => new ast.Collection((type, options) =>
({request_id: new Any(),
type: Array.isArray(type) ? new Any(type) : type,
options}), name, false),
any: function() { return new Any(Array.from(arguments)); },
anyObject: function(obj) { return new AnyObject(obj); },
anyArray: function() { return new AnyArray(Array.from(arguments)); },
userId: function() { return new UserId(); },
};
const make_template = (str) => {
try {
const sandbox = Object.assign({}, env);
return vm.runInNewContext(str, sandbox);
} catch (err) {
throw remakeError(err);
}
};
// eslint-disable-next-line prefer-const
function template_compare(query, template, context) {
if (template === undefined) {
return false;
} else if (template instanceof Any ||
template instanceof AnyObject ||
template instanceof AnyArray) {
if (!template.matches(query, context)) {
return false;
}
} else if (template instanceof UserId) {
if (query !== context.id) {
return false;
}
} else if (template === null) {
if (query !== null) {
return false;
}
} else if (Array.isArray(template)) {
if (!Array.isArray(query) ||
template.length !== query.length) {
return false;
}
for (let i = 0; i < template.length; ++i) {
if (!template_compare(query[i], template[i], context)) {
return false;
}
}
} else if (typeof template === 'object') {
if (typeof query !== 'object') {
return false;
}
for (const key in query) {
if (!template_compare(query[key], template[key], context)) {
return false;
}
}
// Make sure all template keys were handled
for (const key in template) {
if (query[key] === undefined) {
return false;
}
}
} else if (template !== query) {
return false;
}
return true;
}
const incomplete_template_message = (str) =>
`Incomplete template "${str}", ` +
'consider adding ".fetch()", ".watch()", ".anyRead()", or ".anyWrite()"';
class Template {
constructor(str) {
this._value = make_template(str);
assert(this._value !== null, `Invalid template: ${str}`);
assert(!Array.isArray(this._value), `Invalid template: ${str}`);
assert(typeof this._value === 'object', `Invalid template: ${str}`);
if (!(this._value instanceof Any) && !(this._value instanceof AnyObject)) {
if (this._value.request_id === undefined &&
this._value.type === undefined &&
this._value.options === undefined &&
this._value.anyRead) {
this._value = this._value.anyRead();
}
assert(this._value.request_id !== undefined, incomplete_template_message(str));
assert(this._value.type !== undefined, incomplete_template_message(str));
assert(this._value.options !== undefined, incomplete_template_message(str));
}
}
is_match(raw_query, context) {
return template_compare(raw_query, this._value, context);
}
}
module.exports = {Template};