forked from meteor/meteor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
117 lines (93 loc) · 2.52 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
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
"use strict";
export const hasOwn = Object.prototype.hasOwnProperty;
export const slice = Array.prototype.slice;
export function keys(obj) {
return Object.keys(Object(obj));
}
export function isEmpty(obj) {
if (obj == null) {
return true;
}
if (Array.isArray(obj) ||
typeof obj === "string") {
return obj.length === 0;
}
for (const key in obj) {
if (hasOwn.call(obj, key)) {
return false;
}
}
return true;
}
export function last(array, n, guard) {
if (array == null) {
return;
}
if ((n == null) || guard) {
return array[array.length - 1];
}
return slice.call(array, Math.max(array.length - n, 0));
}
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 (hasOwn.call(msg, 'cleared')) {
if (! hasOwn.call(msg, 'fields')) {
msg.fields = {};
}
msg.cleared.forEach(clearKey => {
msg.fields[clearKey] = undefined;
});
delete msg.cleared;
}
['fields', 'params', 'result'].forEach(field => {
if (hasOwn.call(msg, field)) {
msg[field] = EJSON._adjustTypesFromJSONValue(msg[field]);
}
});
return msg;
};
DDPCommon.stringifyDDP = function (msg) {
const copy = EJSON.clone(msg);
// swizzle 'changed' messages from 'fields undefined' rep to 'fields
// and cleared' rep
if (hasOwn.call(msg, 'fields')) {
const cleared = [];
Object.keys(msg.fields).forEach(key => {
const value = msg.fields[key];
if (typeof 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
['fields', 'params', 'result'].forEach(field => {
if (hasOwn.call(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);
};