argumentParsers.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.parseBlockOption = exports.parseSecondsArgument = void 0;
  4. /**
  5. * Parses a command parameter to a number.
  6. * @param arg - The command parameter to parse (number, string, or Buffer)
  7. * @returns The parsed number, or undefined if parsing fails or arg is undefined
  8. */
  9. const parseNumberArgument = (arg) => {
  10. if (typeof arg === "number") {
  11. return arg;
  12. }
  13. if (Buffer.isBuffer(arg)) {
  14. return parseNumberArgument(arg.toString());
  15. }
  16. if (typeof arg === "string") {
  17. const value = Number(arg);
  18. return Number.isFinite(value) ? value : undefined;
  19. }
  20. return undefined;
  21. };
  22. /**
  23. * Parses a command parameter to a string.
  24. * @param arg - The command parameter to parse (string or Buffer)
  25. * @returns The parsed string, or undefined if arg is not a string/Buffer or is undefined
  26. */
  27. const parseStringArgument = (arg) => {
  28. if (typeof arg === "string") {
  29. return arg;
  30. }
  31. if (Buffer.isBuffer(arg)) {
  32. return arg.toString();
  33. }
  34. return undefined;
  35. };
  36. /**
  37. * Parses a command parameter as seconds and converts to milliseconds.
  38. * @param arg - The command parameter representing seconds
  39. * @returns The value in milliseconds, 0 if value is <= 0, or undefined if parsing fails
  40. */
  41. const parseSecondsArgument = (arg) => {
  42. const value = parseNumberArgument(arg);
  43. if (value === undefined) {
  44. return undefined;
  45. }
  46. if (value <= 0) {
  47. return 0;
  48. }
  49. return value * 1000;
  50. };
  51. exports.parseSecondsArgument = parseSecondsArgument;
  52. /**
  53. * Parses the BLOCK option from Redis command arguments (e.g., XREAD, XREADGROUP).
  54. * @param args - Array of command parameters to search for the BLOCK option
  55. * @returns The block duration in milliseconds, 0 if duration is <= 0,
  56. * null if BLOCK option is not found, or undefined if BLOCK is found but duration is invalid
  57. */
  58. const parseBlockOption = (args) => {
  59. for (let i = 0; i < args.length; i++) {
  60. const token = parseStringArgument(args[i]);
  61. if (token && token.toLowerCase() === "block") {
  62. const duration = parseNumberArgument(args[i + 1]);
  63. if (duration === undefined) {
  64. return undefined;
  65. }
  66. if (duration <= 0) {
  67. return 0;
  68. }
  69. return duration;
  70. }
  71. }
  72. return null;
  73. };
  74. exports.parseBlockOption = parseBlockOption;