Contentful Personalization & Analytics
    Preparing search index...
    • Decorator factory that guards class methods behind a synchronous predicate.

      When a decorated method is invoked:

      • If the predicate returns a value that evaluates to allowed (see invert), the original method is executed and its result is returned.
      • If the call is blocked, the optional onBlocked hook is invoked (if configured) and:
        • undefined is returned for sync methods; or
        • Promise<undefined> is returned for async methods (to preserve await compatibility).

      Type Parameters

      • T extends object

        The instance type that owns both the predicate and the decorated method.

      Parameters

      • predicateName: keyof T & (string | symbol)

        The name (string or symbol) of a synchronous instance method on this that acts as the predicate. It is called as this[predicateName](methodName, argsArray).

      • Optionalopts: GuardedByOptions<T>

        Optional GuardedByOptions | options to configure inversion and onBlocked.

      Returns GuardedByFunction<T>

      A methods-only class decorator compatible with Stage-3 decorators that wraps the method.

      TypeError Thrown at initialization time (first instance construction) if predicateName does not resolve to a synchronous function on the instance.

      • This is a methods-only decorator; applying it to accessors/fields is a no-op.
      • The decorator preserves the original method's sync/async shape.
      • The predicate is invoked with (decoratedMethodName, argsArray) to support context-aware checks.

      Here, canRun allows the call when it returns truthy:

      class Runner {
      canRun(method: string, _args: readonly unknown[]) { return method !== 'stop'; }

      @guardedBy<Runner>('canRun')
      go() { console.log('running'); }
      }

      Invert the predicate and call a handler on block:

      class Door {
      isLocked() { return true } // truthy means "locked"
      onBlocked(method: string) { console.warn(`${method} blocked`) }

      @guardedBy<Door>('isLocked', { invert: true, onBlocked: 'onBlocked' })
      open() { /* ... */ }
      }