From 97761f0b33f2c6b11d6c4a676b2fb1d50e1aa214 Mon Sep 17 00:00:00 2001 From: Matt Mazzola Date: Thu, 18 Aug 2016 13:30:58 -0700 Subject: [PATCH] Update AdvancedFilter constructor to throw Error if logical operator is not And and there is only single condition. Also fixes bug which performs validation on conditions after they are extracted from the array. --- src/models.ts | 23 +++++++++++++++-------- test/models.spec.ts | 14 +++++++++++++- 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/src/models.ts b/src/models.ts index f6be96f..a790dc9 100644 --- a/src/models.ts +++ b/src/models.ts @@ -260,24 +260,31 @@ export class AdvancedFilter extends Filter { this.logicalOperator = logicalOperator; - if(conditions.length === 0) { - throw new Error(`conditions must be a non-empty array. You passed: ${conditions}`); - } - if(conditions.length > 2) { - throw new Error(`AdvancedFilters may not have more than two conditions. You passed: ${conditions.length}`); - } + let extractedConditions: IAdvancedFilterCondition[]; /** * Accept conditions as array instead of as individual arguments * new AdvancedFilter('a', 'b', "And", { value: 1, operator: "Equals" }, { value: 2, operator: "IsGreaterThan" }); * new AdvancedFilter('a', 'b', "And", [{ value: 1, operator: "Equals" }, { value: 2, operator: "IsGreaterThan" }]); */ if(Array.isArray(conditions[0])) { - this.conditions = conditions[0]; + extractedConditions = conditions[0]; } else { - this.conditions = conditions; + extractedConditions = conditions; } + + if(extractedConditions.length === 0) { + throw new Error(`conditions must be a non-empty array. You passed: ${conditions}`); + } + if(extractedConditions.length > 2) { + throw new Error(`AdvancedFilters may not have more than two conditions. You passed: ${conditions.length}`); + } + if(extractedConditions.length === 1 && logicalOperator !== "And") { + throw new Error(`Logical Operator must be "And" when there is only one condition provided`); + } + + this.conditions = extractedConditions; } toJSON(): IAdvancedFilter { diff --git a/test/models.spec.ts b/test/models.spec.ts index 4926196..5d28b99 100644 --- a/test/models.spec.ts +++ b/test/models.spec.ts @@ -406,6 +406,18 @@ describe("Unit | Filters", function () { expect(attemptToCreateFilter).toThrowError(); }); + it("should throw an error if logical operator is not And when only 1 condition is provided", function () { + // Arrange + + // Act + const attemptToCreateFilter = () => { + return new models.AdvancedFilter({ table: "Table", column: "c" }, "Or", { value: "a", operator: "Contains" }); + }; + + // Assert + expect(attemptToCreateFilter).toThrowError(); + }); + it("should output the correct json when toJSON is called", function () { // Arrange const expectedFilter: models.IAdvancedFilter = { @@ -445,7 +457,7 @@ describe("Unit | Filters", function () { table: "a", column: "b" }, - logicalOperator: "x", + logicalOperator: "Or", conditions: [ { value: "v1",