# use-cache-helper

> use-cache-helper provides helper functions to easily manage and scale your redis and database caching strategies.

Latest version **0.2503.2801** (published 2025-03-28) · ISC license · 0 weekly downloads

## Install

```sh
npm install use-cache-helper
pnpm add use-cache-helper
yarn add use-cache-helper
bun add use-cache-helper
```

## Health

**Score 35/100 (D)** — status: maintenance-mode.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support; pre 1.0.

Negative: stale; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.2503.2801 |
| Published | 2025-03-28 |
| First published | 2024-05-08 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 2 |
| Unpacked size | 48.6 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Author | Robert Espina |
| Maintainers | robertespina |
| Keywords | Cache strat, Cache strategies, node, redis nodejs, redis cache strategies, use cache, use-cache, use-cache-helper, use cache helper |

## Links

- npm: https://www.npmjs.com/package/use-cache-helper
- Repository: https://github.com/officialrobert/use-cache
- Homepage: https://github.com/officialrobert/use-cache#readme
- Issues: https://github.com/officialrobert/use-cache/issues
- npm.io page: https://npm.io/package/use-cache-helper

## Dependencies (2)

- [ioredis](https://npm.io/package/ioredis.md) ^5.4.1
- [@upstash/redis](https://npm.io/package/@upstash/redis.md) ^1.30.1

## Alternatives

- [memory-cache](https://npm.io/package/memory-cache.md) — 795.0K weekly downloads
- [@httptoolkit/proxy-agent](https://npm.io/package/@httptoolkit/proxy-agent.md) — 11.2K weekly downloads
- [express-cache-controller](https://npm.io/package/express-cache-controller.md) — 5.3K weekly downloads
- [http-cache-middleware](https://npm.io/package/http-cache-middleware.md) — 4.5K weekly downloads
- [cache2](https://npm.io/package/cache2.md) — 1.5K weekly downloads

## Recent versions

- 0.2503.2801 (latest) — 2025-03-28
- 0.2409.2001 — 2024-09-20
- 0.2409.1801 — 2024-09-18
- 0.2408.3001 — 2024-08-30
- 0.2407.201 — 2024-07-01
- 0.2406.1102 — 2024-06-10
- 0.2406.1101 — 2024-06-10
- 0.2406.1001 — 2024-06-09
- 0.2405.2302 — 2024-05-22
- 0.2405.2301 — 2024-05-22
- 0.2405.2101 — 2024-05-20
- 0.2405.1602 — 2024-05-16
- 0.2405.1601 — 2024-05-15
- 0.2405.1502 — 2024-05-15
- 0.2405.1501 — 2024-05-15
- … 6 more at https://npm.io/package/use-cache-helper/versions

## README

# use-cache-helper

`use-cache-helper` provides helper functions to easily manage and scale your redis and database caching strategies.

## Initialize

```ts
import { init } from 'use-cache-helper';
import { redis } from 'lib';

// your ioredis instance
init({ redis: redis });
```

> Here's how to set the maximum number of items in the paginated list before we begin data eviction.

```ts
init({ redis: redis, maxPaginatedItems: 200 });
```

> Upstash redis

```ts
init({
  upstashRedis: redis,
});
```

## Getter function

Use `getOrRefresh` with `SupabaseDB`

> Declare query function

```ts
import { supabaseClient } from 'lib';

interface IUserProfile {
  id: string;
  name: string;
  email: string;
}

type GetUserReturn = IUserProfile | null;

const getUserById = async (): Promise<IUserProfile> => {
  const { error, data } = await supabaseClient
    .from('users')
    .select('*')
    .eq('id', userId)
    .limit(1);

  if (error?.message || !data) {
    return null;
  }

  return data[0];
};
```

```ts
import { getOrRefresh } from 'use-cache-helper';

const verifyUserHandler = async (userId: string) => {
  ////////////////////////////////////////////////
  /////////       Use getOrRefresh        ////////
  ////////////////////////////////////////////////
  const user = await getOrRefresh<GetUserReturn>({
    parseResult: true,
    key: `user:${userId}`,
    cacheRefreshHandler: async (): Promise<GetUserReturn> => {
      return await getUserById(userId);
    },
  });

  if (user?.id) {
    // valid user
  }
};
```

## Setter function

How to manually store cache using the `set` function.

```ts
import { set } from 'use-cache-helper';

const user = await getUserById(userId);
const res = await set({ key: `user:${userId}`, value: user });

if (res === 'OK') {
  // success
}
```

## Strategies for paginated list

This library uses `Redis Sorted Sets` to implement a paginated list. We store only the unique ID from your data, which is by default sorted by the date added or modified in ascending order. We use the LRU method to evict items from the paginated list.

You can configure the maximum number of items in the paginated list. When this limit is reached, it kicks out the least recently used data, determined by score.

```ts
// 200 items limit by default
init({ redis: redis, maxPaginatedItems: 200 });
```

> Inserting data

```ts
import { insertToPaginatedList } from 'use-cache-helper';

const handleInsertItem = async (id: string) => {
  await insertToPaginatedList({
    id,
    key: 'myPaginatedList',
    // The 'score' field is optional; if not provided, it uses the Date.now() value.
    score: Date.now(),
  });
};
```

## Insert array of records

Don't worry about duplicates as long as the ID values you're using are unique.

```ts
import { insertRecordsToPaginatedList } from 'use-cache-helper';

const list = [
  {
    id: 'id-xxx-1',
    score: 1,
    // .. more data
  },
  {
    id: 'id-xxx-2',
    score: 2,
    // .. more data
  },
];

await insertRecordsToPaginatedList({
  listKey: `listCacheKey`,
  listData: list,
  cachePayload: true, // cache each record using the id
  cachePayloadExpiry: 3_600, // payload cache expiry in seconds
});
```

## Documentation

See full API reference <a href="./docs/README.md"><b>Documentation</b></a>

## License

Licensed under [MIT](./LICENSE).

---
_Source: https://npm.io/package/use-cache-helper · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
