Caching
Using a custom cache for resources.
The NextDrupal
client has support for caching resources.
This is handy when dealing with global data: you can fetch data once and re-use during builds.
You can provide your own cache implementation using the cache
option.
Example
Here's an example on how you can use Redis to cache resources.
Note: as of next-drupal 1.3.0
, only getResource
and getMenu
support caching.
lib/drupal.ts
import { NextDrupal, DataCache } from "next-drupal"import Redis from "ioredis"
const redis = new Redis(process.env.REDIS_URL)
export const redisCache: DataCache = { async set(key, value) { return await redis.set(key, value) },
async get(key) { return await redis.get(key) },}
export const drupal = new NextDrupal(process.env.NEXT_PUBLIC_DRUPAL_BASE_URL, { cache: redisCache,})
Now when you make a getResource
or getMenu
call you can tell the client to cache and re-use responses.
lib/get-menu.ts
import { PHASE_PRODUCTION_BUILD } from "next/constants"import { DrupalMenuLinkContent } from "next-drupal"
import { drupal } from "lib/drupal"
export async function getMenu(name: string): Promise<DrupalMenuLinkContent[]> { const menu = await drupal.getMenu(name, { // Cache resource during build. withCache: process.env.NEXT_PHASE === PHASE_PRODUCTION_BUILD, cacheKey: `menu:${name}`, })
return menu.items}
lib/get-block.ts
import { PHASE_PRODUCTION_BUILD } from "next/constants"import { DrupalBlock } from "next-drupal"
import { drupal } from "lib/drupal"
export async function getBlock( type: string, uuid: string): Promise<DrupalBlock> { return await drupal.getResource(type, uuid, { withCache: process.env.NEXT_PHASE === PHASE_PRODUCTION_BUILD, cacheKey: `block:${type}:${uuid}`, })}