-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (51 loc) · 1.7 KB
/
index.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
'use strict'
const typeKeys = {
date: '$$$date$$$',
buffer: '$$$buffer$$$'
}
module.exports.serialize = (obj, { prettify = false, prettifySpace = 2 } = {}) => {
let res
const originalDateToJSON = Date.prototype.toJSON
const originalBufferToJSON = Buffer.prototype.toJSON
// Keep track of the fact that this is a Date object
Date.prototype.toJSON = function () { // eslint-disable-line
return { [typeKeys.date]: this.getTime() }
}
Buffer.prototype.toJSON = function (...args) { // eslint-disable-line
return { [typeKeys.buffer]: this.toString('base64') }
}
res = JSON.stringify(obj, (key, value) => {
if (typeof value === 'undefined') {
return null
}
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || value === null) {
return value
}
return value
}, prettify ? prettifySpace : null)
// Return Date to its original state
Date.prototype.toJSON = originalDateToJSON // eslint-disable-line
// Return Buffer to its original state
Buffer.prototype.toJSON = originalBufferToJSON // eslint-disable-line
return res
}
module.exports.parse = (json) => {
return JSON.parse(json, (key, value) => {
if (key === typeKeys.date) {
return new Date(value)
}
if (key === typeKeys.buffer && value != null && typeof value === 'string') {
return Buffer.from(value, 'base64')
}
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || value === null) {
return value
}
if (value && value[typeKeys.date]) {
return value[typeKeys.date]
}
if (value && value[typeKeys.buffer]) {
return value[typeKeys.buffer]
}
return value
})
}