1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | 'use strict';
|
7 |
|
8 | const createPromiseCallback = require('./utils').createPromiseCallback;
|
9 |
|
10 | module.exports = JSONStringPacker;
|
11 |
|
12 | const ISO_DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | function JSONStringPacker(encoding) {
|
21 | this.encoding = encoding || 'base64';
|
22 | }
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 | JSONStringPacker.prototype.encode = function(value, cb) {
|
34 | const encoding = this.encoding;
|
35 |
|
36 | cb = cb || createPromiseCallback();
|
37 | try {
|
38 | const data = JSON.stringify(value, function(key, value) {
|
39 | if (Buffer.isBuffer(this[key])) {
|
40 | return {
|
41 | type: 'Buffer',
|
42 | data: this[key].toString(encoding),
|
43 | };
|
44 | } else {
|
45 | return value;
|
46 | }
|
47 | });
|
48 |
|
49 | setImmediate(function() {
|
50 | cb(null, data);
|
51 | });
|
52 | } catch (err) {
|
53 | setImmediate(function() {
|
54 | cb(err);
|
55 | });
|
56 | }
|
57 | return cb.promise;
|
58 | };
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 | JSONStringPacker.prototype.decode = function(jsonString, cb) {
|
69 | const encoding = this.encoding;
|
70 |
|
71 | cb = cb || createPromiseCallback();
|
72 | try {
|
73 | const value = JSON.parse(jsonString, function(k, v) {
|
74 | if (v && v.type && v.type === 'Buffer') {
|
75 | return new Buffer(v.data, encoding);
|
76 | }
|
77 |
|
78 | if (ISO_DATE_REGEXP.exec(v)) {
|
79 | return new Date(v);
|
80 | }
|
81 |
|
82 | return v;
|
83 | });
|
84 |
|
85 | setImmediate(function() {
|
86 | cb(null, value);
|
87 | });
|
88 | } catch (err) {
|
89 | setImmediate(function() {
|
90 | cb(err);
|
91 | });
|
92 | }
|
93 | return cb.promise;
|
94 | };
|