compression.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. var Snappy = require('../connection/utils').retrieveSnappy(),
  3. zlib = require('zlib');
  4. var compressorIDs = {
  5. snappy: 1,
  6. zlib: 2
  7. };
  8. var uncompressibleCommands = [
  9. 'ismaster',
  10. 'saslStart',
  11. 'saslContinue',
  12. 'getnonce',
  13. 'authenticate',
  14. 'createUser',
  15. 'updateUser',
  16. 'copydbSaslStart',
  17. 'copydbgetnonce',
  18. 'copydb'
  19. ];
  20. // Facilitate compressing a message using an agreed compressor
  21. var compress = function(self, dataToBeCompressed, callback) {
  22. switch (self.options.agreedCompressor) {
  23. case 'snappy':
  24. Snappy.compress(dataToBeCompressed, callback);
  25. break;
  26. case 'zlib':
  27. // Determine zlibCompressionLevel
  28. var zlibOptions = {};
  29. if (self.options.zlibCompressionLevel) {
  30. zlibOptions.level = self.options.zlibCompressionLevel;
  31. }
  32. zlib.deflate(dataToBeCompressed, zlibOptions, callback);
  33. break;
  34. default:
  35. throw new Error(
  36. 'Attempt to compress message using unknown compressor "' +
  37. self.options.agreedCompressor +
  38. '".'
  39. );
  40. }
  41. };
  42. // Decompress a message using the given compressor
  43. var decompress = function(compressorID, compressedData, callback) {
  44. if (compressorID < 0 || compressorID > compressorIDs.length) {
  45. throw new Error(
  46. 'Server sent message compressed using an unsupported compressor. (Received compressor ID ' +
  47. compressorID +
  48. ')'
  49. );
  50. }
  51. switch (compressorID) {
  52. case compressorIDs.snappy:
  53. Snappy.uncompress(compressedData, callback);
  54. break;
  55. case compressorIDs.zlib:
  56. zlib.inflate(compressedData, callback);
  57. break;
  58. default:
  59. callback(null, compressedData);
  60. }
  61. };
  62. module.exports = {
  63. compressorIDs: compressorIDs,
  64. uncompressibleCommands: uncompressibleCommands,
  65. compress: compress,
  66. decompress: decompress
  67. };