From 97256855aceb63d74cf80dfa16c9c3af713e64b8 Mon Sep 17 00:00:00 2001 From: ssube Date: Sat, 2 Nov 2019 11:33:40 -0500 Subject: [PATCH] fix(visitor): handle missing errors gracefully --- src/rule/index.ts | 2 +- src/utils/index.ts | 11 ++++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/rule/index.ts b/src/rule/index.ts index 1c9dbee..ab5f7ec 100644 --- a/src/rule/index.ts +++ b/src/rule/index.ts @@ -189,7 +189,7 @@ export async function visitRules(ctx: VisitorContext, rules: Array, const itemResult = cloneDeep(item); const ruleResult = await rule.visit(ctx, itemResult); - if (ruleResult.errors.length > 0) { + if (hasItems(ruleResult.errors)) { ctx.logger.warn({ count: ruleResult.errors.length, rule }, 'rule failed'); ctx.mergeResult(ruleResult); continue; diff --git a/src/utils/index.ts b/src/utils/index.ts index 4e80cf0..dcf0d31 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -4,7 +4,16 @@ export function doesExist(val: T | null | undefined): val is T { return !isNil(val); } -export function hasItems(val: Array | null | undefined): val is Array { +/** + * Test if a value is an array with some items (length > 0). + * + * This is not a general replacement for `.length > 0`, since it is also a typeguard: + * `if (hasItems(val)) else { val }` will complain that `val` is `never` in the `else` + * branch, since it was proven not to be an array by this function. + */ +export function hasItems(val: Array | null | undefined): val is Array; +export function hasItems(val: ReadonlyArray | null | undefined): val is ReadonlyArray; +export function hasItems(val: ReadonlyArray | null | undefined): val is ReadonlyArray { return (Array.isArray(val) && val.length > 0); }