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

@payload-enchants/cached-local-api

v1.2.2

Published

## Description:

Downloads

168

Readme

Cached Local API for Payload 3.0 using Next.js unstable_cache (experimental)

Description:

This package allows to cache the following operations:

  1. find
  2. findByID
  3. findOne - new operation, find one by specific field, for example slug
  4. findGlobal
  5. count

Features

  1. Revalidation of the needed data is handled automatically using revalidateTag on Create / Change / Delete.
  2. Respects revalidation of the related documents in the current depth value. In the context of a cached operation, this package replaces payload population handling.
  3. Adds cached findOne operation, to be used, for example, with the slug field.

Install

pnpm add @payload-enchants/cached-local-api

Add to the separated file (see below for the config type)

import { buildCachedPayload } from '@payload-enchants/cached-local-api';
import { revalidateTag, unstable_cache } from 'next/cache';

export const { cachedPayloadPlugin, getCachedPayload } = buildCachedPayload({
  // collections list to cache
  collections: [
    {
      findOneFields: ['slug'],
      slug: 'posts',
    },
  ],
  // Log when revalidation runs or operation cache HIT / SKIP
  loggerDebug: true,
  globals: [{ slug: 'header' }],
  revalidateTag,
  options: {},
  unstable_cache,
});

Add into your payload.config.ts:

import { cachedPayloadPlugin } from './cached-local-api';

export default buildConfig({
  // ...your config
  plugins: [cachedPayloadPlugin],
});

Example of the usage on Next Page

import configPromise from '@payload-config';
import { getPayloadHMR } from '@payloadcms/next/utilities';

import { getCachedPayload } from '../../../cached-local-api';

const Page = async () => {
  const payload = await getPayloadHMR({
    config: configPromise,
  });

  const cachedPayload = getCachedPayload(payload);

  const posts = await cachedPayload.find({ collection: 'posts' });

  const postBySlug = await cachedPayload.findOne({ collection: 'posts', value: 'home', depth: 2 });

  // In this case it's not required as `slug` field is the first item in `findOneFields` array.
  const postBySlugExplict = await cachedPayload.findOne({
    collection: 'posts',
    field: 'slug',
    value: 'home',
  });

  // by id
  if (postBySlug) {
    const postByID = await cachedPayload.findByID({
      collection: 'posts',
      id: postBySlug?.id ?? '',
    });
  }

  // count
  const { totalDocs } = await cachedPayload.count({ collection: 'posts' });

  return (
    <div>
      {posts.docs.map((each) => (
        <div key={each.id}>{each.title}</div>
      ))}
    </div>
  );
};

export default Page;

Args

export type Args = {
  /** List of collections slugs that should use cache */
  collections?: Array<{
    /** array with the fields to use in findOne (name or config, see below) */
    findOneFields?: (FindOneFieldConfig | string)[];

    slug: keyof GeneratedTypes['collections'];
  }>;

  /** List of globals slugs that should use cache */
  globals?: Array<{
    slug: keyof GeneratedTypes['globals'];
  }>;

  /** Additional options */
  options?: Options;

  /** Next.js revalidateTag */
  revalidateTag: (tag: string) => void;

  /** Next.js unstable_cache */
  unstable_cache: UnstableCache;

  /**
   * (experiment): Instead of revalidating each collection document separately
   * 'simpleCache' revalidates all cached data on Payload database update
   *  */
  useSimpleCacheStrategy?: boolean;
};

export type FindOneFieldConfig = {
  buildWhere?: (args: {
    args: FindOneArgs<any>;
    fieldName: string;
    shouldCache: boolean;
    value: unknown;
  }) => Where;
  getFieldFromDoc?: (doc: Record<string, any>) => unknown;
  name: string;
};

Options

export type Options = {
  // custom tag build
  buildTagFind?: (args: { slug: string }) => string;
  buildTagFindByID?: (args: { id: number | string; slug: string }) => string;
  buildTagFindGlobal?: (args: { slug: string }) => string;

  // If not provided - returns `true`
  shouldCacheCountOperation?: (args: CountArgs) => Promise<boolean> | boolean;
  shouldCacheFindByIDOperation?: (args: FindByIDArgs) => Promise<boolean> | boolean;
  shouldCacheFindGlobalOperation?: (args: FindGlobalArgs) => Promise<boolean> | boolean;
  shouldCacheFindOperation?: (args: FindArgs) => Promise<boolean> | boolean;

  // If not provided - returns `true`
  shouldRevalidateGlobalOnChange?: (
    args: Parameters<GlobalAfterChangeHook>[0],
  ) => Promise<boolean> | boolean;
  shouldRevalidateOnChange?: (
    args: Parameters<CollectionAfterChangeHook>[0],
  ) => Promise<boolean> | boolean;
  shouldRevalidateOnDelete?: (
    args: Parameters<CollectionAfterDeleteHook>[0],
  ) => Promise<boolean> | boolean;

  // Completely disable caching in any operation
  disableCache?: boolean;
};