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

kv-cacheable

v1.1.1

Published

This is a library to make Cloudflare Workers KV easier to use.

Downloads

4

Readme

codecov npm version

:key: kv-cacheable

What is this?

This library helps implement caching using Cloudflare Workers KV.
With a few lines of code, you can control the execution of functions that you want to cache for speed, store them in the cache, and skip execution of the function if the cache exists.

For example

The following is an example of a process that requests data from a server. The process is cached to speed up the process. If KV has a prior cache, it will be retrieved and the fetching process will not be executed. If there is no cache, the fetch process is executed and the results are stored in the KV for future use. However, it is necessary to assume the possibility that the fetch may fail and avoid storing the result in KV if it is not a valid value.

Do not use kv-cacheable case
This is redundant and uncool :weary:

import { fetchSomeData, isValid } from 'libs/api'

export const loader = async () => {
  let result = await KV_NAMESPACE.get('cache-key', 'json')
  if (!result) {
    result = await fetchSomeData()
    if (isValid(result)) {
      KV_NAMESPACE.put('cache-key', JSON.stringify(result), { expiration: 3600 })
    }
  }
  
  // do something
}

Use kv-cacheable case
This is simple and cool! :partying_face:

import { fetchSomeData, isValid } from 'libs/api'
import kvCacheable from 'kv-cacheable'

const cacheable = kvCacheable(KV_NAMESPACE, { expiration: 3600 })

export const loader = async () => {
  const result = await cacheable('cache-key', cacheable, isValid)
  // do something
}

Install

# npm
npm install kv-cacheable

# yarn
yarn add kv-cacheable

How to use

  1. Set up KV in advance.
  2. Create a wrapper using makeKVCacheable.
  3. Set the process to be cached and the key to be used for caching in the wrapper function and execute it.
// Examples for use with Remix
import makeCacheable from 'kv-cacheable'
import { exampleSlowCalculation } from '~/utils'

const cacheable = makeCacheable(KV)

export const loader = async () => {
  const result = await cacheable('cache-key', exampleSlowCalculation)
  
  // ...
}

If a value matching the key (first argument) exists in the KV, skip processing the second argument and return the cache.
If a cache matching the key does not exist, processing of the second argument is performed and the result is stored in KV as a cache.

Type Information and Supplemental

makeCacheable

  • Arguments
    • The first: Your KV object (required)
    • The second: An option object (optional)
      • debug: boolean (optional): If set to true, logs are output when the cache is hit and set.
      • expiration: number (optional): The cache expiration time.
      • expirationTtl: number (optional): The cache expiration time.
  • Return (function): Wrapper function to control cache (see below).

cacheable function
This is the return of makeCacheable.

  • Arguments
    • The first: A key of cache (required)
    • The second: Function, asynchronous function or Promise you want to cache and accelerate (required)
      • The return value must be a value that can be stringified with JSON.stringify.
    • The third: Option to control cache. Three types: boolean, object or function (optional)
      • Type is boolean: You can intentionally choose not to cache by setting false.
      • Type is object:
        • cacheable: boolean (optional): You can intentionally choose not to cache by setting false.
        • expiration: number (optional): The cache expiration time.
          • Overrides the value set by makeCacheable
        • expirationTtl: number (optional): The cache expiration time.
          • Overrides the value set by makeCacheable
      • Type is function: It takes the result of the execution of the second argument as the argument and returns the optional values (object or boolean) described above.
        • This is useful in cases where the function of the first argument can be expected to fail temporarily, such as when communicating with another server, to prevent the cache from being overwritten with its unexpected value.
        • See the example code below for details
  • Return (Promise): The result of the execution of the function or promise set as the first argument, or the cache retrieved from KV.
const isValid = (val) => {
  // do validation
  return boolean
}

// If fetchDataFromServer does not return the correct value, do not cache it.
const result = await cacheable(
  'cache-key',
  fetchDataFromServer,
  (res) => isValid(res) // res is the value returned by exampleFunc
)