Blame view

node_modules/loopback-connector/lib/binary-packer.js 2.06 KB
f7563de62   Palak Handa   first commit
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
  // Copyright IBM Corp. 2014,2016. All Rights Reserved.
  // Node module: loopback-connector
  // This file is licensed under the MIT License.
  // License text available at https://opensource.org/licenses/MIT
  
  'use strict';
  
  var createPromiseCallback = require('./utils').createPromiseCallback;
  var msgpack = require('msgpack5');
  
  module.exports = BinaryPacker;
  
  /**
   * Create a new Packer instance that can be used to convert between JavaScript
   * objects and a binary representation in a Buffer.
   *
   * Compared to JSON, this encoding preserves the following JavaScript types:
   *  - Date
   */
  function BinaryPacker() {
    this._packer = msgpack({ forceFloat64: true });
    this._packer.register(1, Date, encodeDate, decodeDate);
  }
  
  /**
   * Encode the provided value to a `Buffer`.
   *
   * @param {*} value Any value (string, number, object)
   * @callback {Function} cb The callback to receive the parsed result.
   * @param {Error} err
   * @param {Buffer} data The encoded value
   * @promise
   */
  BinaryPacker.prototype.encode = function(value, cb) {
    cb = cb || createPromiseCallback();
    try {
      // msgpack5 returns https://www.npmjs.com/package/bl instead of Buffer
      // use .slice() to convert to a Buffer
      var data = this._packer.encode(value).slice();
      setImmediate(function() {
        cb(null, data);
      });
    } catch (err) {
      setImmediate(function() {
        cb(err);
      });
    }
    return cb.promise;
  };
  
  /**
   * Decode the binary value back to a JavaScript value.
   * @param {Buffer} binary The binary input.
   * @callback {Function} cb The callback to receive the composed value.
   * @param {Error} err
   * @param {*} value Decoded value.
   * @promise
   */
  BinaryPacker.prototype.decode = function(binary, cb) {
    cb = cb || createPromiseCallback();
    try {
      var value = this._packer.decode(binary);
      setImmediate(function() {
        cb(null, value);
      });
    } catch (err) {
      setImmediate(function() {
        cb(err);
      });
    }
    return cb.promise;
  };
  
  function encodeDate(obj) {
    return new Buffer(obj.toISOString(), 'utf8');
  }
  
  function decodeDate(buf) {
    return new Date(buf.toString('utf8'));
  }