UNPKG

2.43 kBJavaScriptView Raw
1// Copyright IBM Corp. 2016,2019. All Rights Reserved.
2// Node module: loopback-connector
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6'use strict';
7
8const createPromiseCallback = require('./utils').createPromiseCallback;
9
10module.exports = JSONStringPacker;
11
12const ISO_DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
13
14/**
15 * Create a new Packer instance that can be used to convert between JavaScript
16 * objects and a JsonString representation in a String.
17 *
18 * @param {String} encoding Buffer encoding refer to https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
19 */
20function JSONStringPacker(encoding) {
21 this.encoding = encoding || 'base64';
22}
23
24/**
25 * Encode the provided value to a `JsonString`.
26 *
27 * @param {*} value Any value (string, number, object)
28 * @callback {Function} cb The callback to receive the parsed result.
29 * @param {Error} err
30 * @param {Buffer} data The encoded value
31 * @promise
32 */
33JSONStringPacker.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 * Decode the JsonString value back to a JavaScript value.
62 * @param {String} jsonString The JsonString input.
63 * @callback {Function} cb The callback to receive the composed value.
64 * @param {Error} err
65 * @param {*} value Decoded value.
66 * @promise
67 */
68JSONStringPacker.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};