diff --git a/packages/cactus-common/src/main/typescript/checks.ts b/packages/cactus-common/src/main/typescript/checks.ts index 9c3c66e93b..b14f35d06d 100644 --- a/packages/cactus-common/src/main/typescript/checks.ts +++ b/packages/cactus-common/src/main/typescript/checks.ts @@ -18,4 +18,23 @@ export class Checks { throw new CodedError(message, code); } } + + /** + * Verifies that a string is indeed not a blank string. + * Blank string can be one that only has whitespace characters for example. + * + * @param value The value that will be asserted for being a non-blank string. + * @param subject The error message if `value` is a blank string. + * @param code The code of the error if `checkResult is falsy. + */ + public static nonBlankString( + value: any, + subject: string = "variable", + code: string = "-1" + ): void { + if (typeof value !== "string" || value.trim().length === 0) { + const message = `"${subject}" is a blank string. Need non-blank.`; + throw new CodedError(message, code); + } + } } diff --git a/packages/cactus-common/src/test/typescript/unit/checks.test.ts b/packages/cactus-common/src/test/typescript/unit/checks.test.ts new file mode 100644 index 0000000000..b52807194f --- /dev/null +++ b/packages/cactus-common/src/test/typescript/unit/checks.test.ts @@ -0,0 +1,27 @@ +import test, { Test } from "tape"; + +import { v4 as uuidv4 } from "uuid"; + +import { Checks } from "../../../main/typescript"; + +test("Checks", (t: Test) => { + test("Checks#nonBlankString()", (t2: Test) => { + const subject = uuidv4(); + const pattern = new RegExp(`${subject}`); + + t2.throws(() => Checks.nonBlankString("", subject), pattern); + t2.throws(() => Checks.nonBlankString(" ", subject), pattern); + t2.throws(() => Checks.nonBlankString("\n", subject), pattern); + t2.throws(() => Checks.nonBlankString("\t", subject), pattern); + t2.throws(() => Checks.nonBlankString("\t\n", subject), pattern); + t2.throws(() => Checks.nonBlankString("\n\r", subject), pattern); + + t2.doesNotThrow(() => Checks.nonBlankString("-")); + t2.doesNotThrow(() => Checks.nonBlankString(" a ")); + t2.doesNotThrow(() => Checks.nonBlankString("\na\t")); + + t2.end(); + }); + + t.end(); +});