CondExpression.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. "use strict";
  2. /**
  3. * $cond expression; @see evaluate
  4. * @class CondExpression
  5. * @namespace mungedb-aggregate.pipeline.expressions
  6. * @module mungedb-aggregate
  7. * @constructor
  8. */
  9. var CondExpression = module.exports = function CondExpression() {
  10. if (arguments.length !== 0) throw new Error(klass.name + ": expected args: NONE");
  11. base.call(this);
  12. }, klass = CondExpression, base = require("./FixedArityExpressionT")(CondExpression, 3), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  13. var Value = require("../Value"),
  14. Expression = require("./Expression");
  15. proto.evaluateInternal = function evaluateInternal(vars) {
  16. var cond = this.operands[0].evaluateInternal(vars);
  17. var idx = Value.coerceToBool(cond) ? 1 : 2;
  18. return this.operands[idx].evaluateInternal(vars);
  19. };
  20. klass.parse = function parse(expr, vps) {
  21. if (Value.getType(expr) !== "Object") {
  22. return base.parse(expr, vps);
  23. }
  24. // verify(str::equals(expr.fieldName(), "$cond")); //NOTE: DEVIATION FROM MONGO: we do not have fieldName any more and not sure this is even possible anyway
  25. var ret = new CondExpression();
  26. ret.operands.length = 3;
  27. var args = expr;
  28. for (var argfieldName in args) {
  29. if (!args.hasOwnProperty(argfieldName)) continue;
  30. if (argfieldName === "if") {
  31. ret.operands[0] = Expression.parseOperand(args.if, vps);
  32. } else if (argfieldName === "then") {
  33. ret.operands[1] = Expression.parseOperand(args.then, vps);
  34. } else if (argfieldName === "else") {
  35. ret.operands[2] = Expression.parseOperand(args.else, vps);
  36. } else {
  37. throw new Error("Unrecognized parameter to $cond: '" + argfieldName + "'; uasserted code 17083");
  38. }
  39. }
  40. if (!ret.operands[0]) throw new Error("Missing 'if' parameter to $cond; uassert code 17080");
  41. if (!ret.operands[1]) throw new Error("Missing 'then' parameter to $cond; uassert code 17081");
  42. if (!ret.operands[2]) throw new Error("Missing 'else' parameter to $cond; uassert code 17082");
  43. return ret;
  44. };
  45. Expression.registerExpression("$cond", CondExpression.parse);
  46. proto.getOpName = function getOpName() {
  47. return "$cond";
  48. };