0.1.0 • Published 5 months ago

flood-barrier v0.1.0

Weekly downloads
-
License
ISC
Repository
github
Last release
5 months ago

flood-barrier

Limit how often your event handler can be called within a certain duration. Basically a debounce that allows multiple invocations before it triggers.

API

This module exports one function:

floodBarrier(config, func)

Return a "guard function" that proxies your function func when called at an acceptable rate (tracked as "heat"), and does something else when called excessively. The config argument is passed to floodBarrier.makeAdvisor and is described there below.

The config argument can be any of the following:

  • A config object as described below.
  • A false-y value, which means to use all defaults.
  • A positive finite number, which will be used as both the maxRepeats and cooldownSec option.

When giving a config object, these keys are understood:

  • maxRepeats: Intervene after this amount of repeated invocations. (The first invocation is not a repeat.) Default: 1
  • initialHeat: The number of invocations already accumulated. Default: 0
  • cooldownSec: The duration (in seconds) that must pass without an invocation in order to reset the heat, i.e. accept normal invocations again. Default: maxRepeats
  • memoValue: The initial value for the "memo" behavior (see onHot). Default: undefined
  • onHot: What to do when the guard function is called excessively.
    • 'noop', 'ignore', 'false', false or any false-y value (default): Just return false.
    • 'memo': Return the last known result of an acceptable invocation.
    • 'err': Throw a generic error.
    • an object with a .message property: Throw a custom error with that message and all other own properties of that object.
    • a function: Call this function instead of func. The context (this) of the invocation will be the guard function.

The guard function will hold these properties:

  • advisor: A function that just decides (returns a boolean) whether the invocation is acceptable. Increases heat if it is.

floodBarrier.makeAdvisor(config)

Return an advisor function as described above. Exposed for cases where you want to handle the guard decision in your own code.

Usage

:TODO: see test/usage.mjs.

See also

Known issues

  • Needs more/better tests and docs.

 

License

ISC

0.1.0

5 months ago