|
| 1 | +# Debounce Hook |
| 2 | + |
| 3 | +This is a utility "meta" hook, which can be used to effectively debounce or rate limit other hooks based on various parameters. |
| 4 | +This can be especially useful for certain UI frameworks and SDKs that frequently re-render and re-evaluate flags (React, Angular, etc). |
| 5 | + |
| 6 | +## Installation |
| 7 | + |
| 8 | +``` |
| 9 | +$ npm install @openfeature/debounce-hook |
| 10 | +``` |
| 11 | + |
| 12 | +### Peer dependencies |
| 13 | + |
| 14 | +This package only requires the `@openfeature/core` dependency, which is installed automatically no matter which OpenFeature JavaScript SDK you are using. |
| 15 | + |
| 16 | +## Usage |
| 17 | + |
| 18 | +Simply wrap your hook with the debounce hook by passing it as a constructor arg, and then configure the remaining options. |
| 19 | +In the example below, we wrap a logging hook. |
| 20 | +This debounces all its stages, so it only logs a maximum of once a minute for each flag key, no matter how many times that flag is evaluated. |
| 21 | + |
| 22 | +```ts |
| 23 | +const debounceHook = new DebounceHook(loggingHook, { |
| 24 | + debounceTime: 60_000, // how long to wait before the hook can fire again |
| 25 | + maxCacheItems: 100, // max amount of items to keep in the cache; if exceeded, the oldest item is dropped |
| 26 | +}); |
| 27 | + |
| 28 | +// add the hook globally |
| 29 | +OpenFeature.addHooks(debounceHook); |
| 30 | + |
| 31 | +// or at a specific client |
| 32 | +client.addHooks(debounceHook); |
| 33 | +``` |
| 34 | + |
| 35 | +The hook maintains a simple expiring cache with a fixed max size and keeps a record of recent evaluations based on an optional key-generation function (cacheKeySupplier). |
| 36 | +Be default, the key-generation function is purely based on the flag key. |
| 37 | +Particularly in server use-cases, you may want to take the targetingKey or other contextual information into account in your debouncing. |
| 38 | +Below we see an example using this, as well as other advanced options: |
| 39 | + |
| 40 | +```ts |
| 41 | +const debounceHook = new DebounceHook<string>(loggingHook, { |
| 42 | + cacheKeySupplier: (flagKey, context) => flagKey + context.targetingKey, // cache on a combination of user and flag key |
| 43 | + debounceTime: 60_000, // debounce for 60 seconds (per user due to our cacheKeySupplier above) |
| 44 | + maxCacheItems: 1000, // cache a maximum of 1000 records |
| 45 | + cacheErrors: false, // don't debounce errors; always re-run if the last run threw |
| 46 | + logger: console, // optional logger |
| 47 | +}); |
| 48 | +``` |
| 49 | + |
| 50 | +## Development |
| 51 | + |
| 52 | +### Building |
| 53 | + |
| 54 | +Run `nx package hooks-debounce` to build the library. |
| 55 | + |
| 56 | +### Running unit tests |
| 57 | + |
| 58 | +Run `nx test hooks-debounce` to execute the unit tests via [Jest](https://jestjs.io). |
0 commit comments