npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-cache-helper

v0.2406.1102

Published

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

Downloads

1,131

Readme

use-cache-helper

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

Initialize

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.

init({ redis: redis, maxPaginatedItems: 200 });

Upstash redis

init({
  upstashRedis: redis,
});

Getter function

Use getOrRefresh with SupabaseDB

Declare query function

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];
};
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.

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.

// 200 items limit by default
init({ redis: redis, maxPaginatedItems: 200 });

Inserting data

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.

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 Documentation

License

Licensed under MIT.