This library helps implement caching using Cloudflare Workers KV

Overview

codecov npm version

🔑 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 😩

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! 🥳

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
)
You might also like...

A MySQL Library for Node.js

A MySQL Library for Node.js

Mar 14, 2022

A database library stores JSON file for Node.js.

concisedb English | 简体中文 A database library stores JSON file for Node.js. Here is what updated every version if you want to know. API Document Usage B

Sep 4, 2022

XML/HTML parser and processing library for JavaScript and TypeScript

XML/HTML parser and processing library for JavaScript and TypeScript

[VIEW DOCUMENTATION] Robin is an XML parser and processing library that supports a sane version of HTML. It features a set of DOM utilities, including

Oct 5, 2022

A node.js locks library with support of Redis and MongoDB

locco A small and simple library to deal with race conditions in distributed systems by applying locks on resources. Currently, supports locking via R

Dec 13, 2022

A Node.js library for retrieving data from a PostgreSQL database with an interesting query language included.

RefQL A Node.js library for retrieving data from a PostgreSQL database with an interesting query language included. Introduction RefQL is about retrie

Nov 2, 2022

Fast File is a quick and easy-to-use library to convert data sources to a variety of options.

Fast File is a quick and easy-to-use library to convert data sources to a variety of options.

Fast File Converter The Express.js's Fast File Converter Library Fast File Converter Library is a quick and easy-to-use library to convert data source

Nov 16, 2022

A Full Stack Amazon Clone which created using ReactJS with full E-Commerce Functionality!!

Amazon Clone with ReactJS A small web app that tries to imitate the desktop web version of amazon site, you can add items to the basket, delete them,

Oct 3, 2022

Burger builder project using React, Hooks and Context API.

Burger builder project using React, Hooks and Context API.

Burger Builder In this project, I made a context-api project by creating hamburgers with 3 different materials. Project setup npm install Project star

Jun 17, 2021

A simple url shorter API built with nodejs running on Kubernetes in Google Cloud, using PostgreSQL for storage and cloud sql proxy.

Simple URL Shorter - Google Cloud - Kubernetes A simple url shorter API built with nodejs running on Kubernetes in Google Cloud, using PostgreSQL for

Nov 25, 2021
Comments
  • The automated release is failing 🚨

    The automated release is failing 🚨

    :rotating_light: The automated release from the main branch failed. :rotating_light:

    I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

    You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

    Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

    Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

    If you are not sure how to resolve this, here are some links that can help you:

    If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


    No npm token specified.

    An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

    Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


    Good luck with your project ✨

    Your semantic-release bot :package::rocket:

    semantic-release 
    opened by github-actions[bot] 1
Releases(v1.1.1)
Owner
AijiUejima
I'm working for an IT company in Nagoya, Japan on web development
AijiUejima
A template for WebSockets powered Cloudflare Worker project using graphql-ws

?? graphql-ws on Cloudflare Workers A template for WebSockets powered Cloudflare Worker project using graphql-ws. The worker serves the following rout

Denis Badurina 26 Dec 18, 2022
WASM-based implementation of Cloudflare's HTML Rewriter for use in Deno, browsers, etc.

HTML Rewriter WASM-based implementation of Cloudflare's HTML Rewriter for use in Deno, browsers, etc. It uses lol-html under the hood, the same implem

Worker Tools 36 Dec 6, 2022
WriterAI is an AI based content writing tool that helps users easily write high quality emails, blogs, letters, thesis and other stuff.

WriterAI is an AI based content writing tool that helps users easily write high quality emails, blogs, letters, thesis and other stuff. One can also share their project with others and work as a team.

Ishant Chauhan 67 Jan 2, 2023
A javascript library to run SQLite on the web.

SQLite compiled to JavaScript sql.js is a javascript SQL database. It allows you to create a relational database and query it entirely in the browser.

SQL.JS 11k Jan 7, 2023
Couchbase Node.js Client Library (Official)

Couchbase Node.js Client The Node.js SDK library allows you to connect to a Couchbase cluster from Node.js. It is a native Node.js module and uses the

null 460 Nov 13, 2022
Nano: The official Apache CouchDB library for Node.js

Nano Offical Apache CouchDB library for Node.js. Features: Minimalistic - There is only a minimum of abstraction between you and CouchDB. Pipes - Prox

The Apache Software Foundation 578 Dec 24, 2022
The Cassandra/Scylla library you didn't want but got anyways.

Installation Using npm: npm install scyllo or if you prefer to use the yarn package manager: yarn add scyllo Usage import { ScylloClient } from 'scyll

LVK.SH 7 Jul 20, 2022
A tiny javascript + Flash library that enables the creation and download of text files without server interaction.

Downloadify: Client Side File Creation Important! The swf has been compiled for online use only. Testing from the file path (i.e. file:// ) will not w

Doug Neiner 853 Nov 21, 2022
HLS, DASH, and future HTTP streaming protocols library for video.js

videojs-http-streaming (VHS) Play HLS, DASH, and future HTTP streaming protocols with video.js, even where they're not natively supported. Included in

Video.js 2.2k Jan 5, 2023
DolphinDB JavaScript API is a JavaScript library that encapsulates the ability to operate the DolphinDB database, such as: connecting to the database, executing scripts, calling functions, uploading variables, etc.

DolphinDB JavaScript API English | 中文 Overview DolphinDB JavaScript API is a JavaScript library that encapsulates the ability to operate the DolphinDB

DolphinDB 6 Dec 12, 2022