hiredis.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict'
  2. var hiredis = require('hiredis')
  3. var ReplyError = require('../lib/replyError')
  4. var ParserError = require('../lib/parserError')
  5. /**
  6. * Parse data
  7. * @param parser
  8. * @returns {*}
  9. */
  10. function parseData (parser, data) {
  11. try {
  12. return parser.reader.get()
  13. } catch (err) {
  14. // Protocol errors land here
  15. // Reset the parser. Otherwise new commands can't be processed properly
  16. parser.reader = new hiredis.Reader(parser.options)
  17. parser.returnFatalError(new ParserError(err.message, JSON.stringify(data), -1))
  18. }
  19. }
  20. /**
  21. * Hiredis Parser
  22. * @param options
  23. * @constructor
  24. */
  25. function HiredisReplyParser (options) {
  26. this.returnError = options.returnError
  27. this.returnFatalError = options.returnFatalError || options.returnError
  28. this.returnReply = options.returnReply
  29. this.name = 'hiredis'
  30. this.options = {
  31. return_buffers: !!options.returnBuffers
  32. }
  33. this.reader = new hiredis.Reader(this.options)
  34. }
  35. HiredisReplyParser.prototype.execute = function (data) {
  36. this.reader.feed(data)
  37. var reply = parseData(this, data)
  38. while (reply !== undefined) {
  39. if (reply && reply.name === 'Error') {
  40. this.returnError(new ReplyError(reply.message))
  41. } else {
  42. this.returnReply(reply)
  43. }
  44. reply = parseData(this, data)
  45. }
  46. }
  47. /**
  48. * Reset the parser values to the initial state
  49. *
  50. * @returns {undefined}
  51. */
  52. HiredisReplyParser.prototype.reset = function () {
  53. this.reader = new hiredis.Reader(this.options)
  54. }
  55. module.exports = HiredisReplyParser