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

cf-workers-query

v0.7.1

Published

Automatically cache and revalidate data in Cloudflare Workers. Using the Cache API and Execution Context

Downloads

472

Readme

Cf-Workers-Query

Automatically cache and revalidate data in Cloudflare Workers. Using the Cache API and Execution Context.

Example:

import { createQuery } from 'cf-workers-query';

const { data, error, invalidate } = await createQuery({
  queryKey: ['user', userId],
  queryFn: async () => {
    const user = await fetchUser(userId);
    return user;
  },
  gcTime: 60 * 1000,
});

Stale revalidation

import { createQuery } from 'cf-workers-query';

export default {
  async fetch(request, env, ctx) {
    const { data } = await createQuery({
      queryKey: ['user', userId],
      queryFn: async () => {
        const user = await fetchUser(userId);
        return user;
      },
      staleTime: 30 * 1000,
      gcTime: 60 * 1000,
      executionCtx: ctx,
    });
    
    return new Response(JSON.stringify(data), {
      headers: {
        'content-type': 'application/json',
      },
    });
  },
};

To have revalidation automatically when the stale time is reached, you need to provide the executionCtx to the createQuery function.

You can also use the defineCFExecutionContext function to define a custom execution context for the query. Can be useful if you are using a something like hono or remix.

Example using defineCFExecutionContext:

Hono example

In this case you don't need to use defineCFExecutionContext as the execution context is provided automatically.

import { cache } from 'cf-workers-query/hono';


app.get('/user/:id', cache({
  handler: async (ctx, next) => {
    const user = await fetchUser(ctx.req.param('id'));
    return ctx.json(user)
  },
  cacheKey: (ctx) => ['user', ctx.req.param('id')], 
  cacheTime: 60 * 60,
  staleTime: 60
}));

API Reference

queryKey

Type: QueryKey | null

Description: An optional key that uniquely identifies the query. This can be used to cache and retrieve query results more effectively. If set to null, the query may not be cached.

queryFn

Type: () => Promise

Description: A function that returns a promise resolving with the data for the query. It is the primary function that runs to fetch the data.

staleTime

Type: number

Description: Optional. The amount of time in milliseconds before the query data is considered stale. Default is 0.

gcTime

Type: number

Description: Optional. The amount of time in milliseconds to keep unused data in the cache before garbage collection.

revalidate

Type: boolean

Description: Optional. If true, the query will directly revalidate data.

retry

Type: number | ((failureCount: number, error: Error) => boolean)

Description: Optional. Specifies the number of retry attempts in case of a query failure. Alternatively, a function that receives the failure count and error and returns a boolean indicating whether to retry the query.

retryDelay

Type: RetryDelay

Description: Optional. Specifies the delay between retry attempts. This can be a number indicating milliseconds or a function returning the delay based on the failure count and error.

executionCtx

Type: ExecutionContext

Description: Optional. The execution context to use.

cacheName

Type: string

Description: Optional. The name of the cache to use. Default is cf-workers-query-cache.

Credits

Inspired by tanstack query but for Cloudflare Workers.