-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathserialize.js
More file actions
27 lines (24 loc) · 780 Bytes
/
serialize.js
File metadata and controls
27 lines (24 loc) · 780 Bytes
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
module.exports = function serialize (value, asBuffer) {
if (value === null ||
value === undefined ||
value === '' ||
(Buffer.isBuffer(value) && value.length === 0)) {
return {NULL: true}
}
const type = value.constructor.name
const reduce = function (value) {
return Object.keys(value).reduce((acc, key) => {
acc[key] = serialize(value[key], asBuffer)
return acc
}, {})
}
switch (type) {
case 'String' : return {S: value}
case 'Buffer' : return {B: value}
case 'Boolean' : return {BOOL: value}
case 'Number' : return {N: String(value)}
case 'Array' : return {L: value.map(serialize, asBuffer)}
case 'Object' : return {M: reduce(value)}
default : throw new Error(`cannot serialize ${type}`)
}
}