forked from meteor/meteor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
64 lines (57 loc) · 1.77 KB
/
utils.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
DDPCommon.SUPPORTED_DDP_VERSIONS = [ '1', 'pre2', 'pre1' ];
DDPCommon.parseDDP = function (stringMessage) {
try {
var msg = JSON.parse(stringMessage);
} catch (e) {
Meteor._debug("Discarding message with invalid JSON", stringMessage);
return null;
}
// DDP messages must be objects.
if (msg === null || typeof msg !== 'object') {
Meteor._debug("Discarding non-object DDP message", stringMessage);
return null;
}
// massage msg to get it into "abstract ddp" rather than "wire ddp" format.
// switch between "cleared" rep of unsetting fields and "undefined"
// rep of same
if (_.has(msg, 'cleared')) {
if (!_.has(msg, 'fields'))
msg.fields = {};
_.each(msg.cleared, function (clearKey) {
msg.fields[clearKey] = undefined;
});
delete msg.cleared;
}
_.each(['fields', 'params', 'result'], function (field) {
if (_.has(msg, field))
msg[field] = EJSON._adjustTypesFromJSONValue(msg[field]);
});
return msg;
};
DDPCommon.stringifyDDP = function (msg) {
var copy = EJSON.clone(msg);
// swizzle 'changed' messages from 'fields undefined' rep to 'fields
// and cleared' rep
if (_.has(msg, 'fields')) {
var cleared = [];
_.each(msg.fields, function (value, key) {
if (value === undefined) {
cleared.push(key);
delete copy.fields[key];
}
});
if (!_.isEmpty(cleared))
copy.cleared = cleared;
if (_.isEmpty(copy.fields))
delete copy.fields;
}
// adjust types to basic
_.each(['fields', 'params', 'result'], function (field) {
if (_.has(copy, field))
copy[field] = EJSON._adjustTypesToJSONValue(copy[field]);
});
if (msg.id && typeof msg.id !== 'string') {
throw new Error("Message id is not a string");
}
return JSON.stringify(copy);
};