feat: add tags/revalidate options to PocketBase fetch client
PB_URL falls back through PB_URL → NEXT_PUBLIC_PB_URL → localhost so
internal Docker hostname is used server-side without leaking into the
client bundle. cache: force-cache replaced with next: { tags, revalidate }
for ISR tag-based invalidation.
This commit is contained in:
+21
-11
@@ -4,13 +4,10 @@ import type { ListResponse } from './types';
|
||||
* Native fetch wrapper for PocketBase API requests.
|
||||
*/
|
||||
|
||||
const PB_URL =
|
||||
process.env.NEXT_PUBLIC_PB_URL ||
|
||||
(process.env.NODE_ENV === 'production'
|
||||
? (() => {
|
||||
throw new Error('NEXT_PUBLIC_PB_URL is not set');
|
||||
})()
|
||||
: 'http://127.0.0.1:8090');
|
||||
/* Prefer the server-only var (not exposed to the browser bundle),
|
||||
* fall back to the public var for client-side usage, then to the
|
||||
* local dev default. */
|
||||
const PB_URL = process.env.PB_URL ?? process.env.NEXT_PUBLIC_PB_URL ?? 'http://127.0.0.1:8090';
|
||||
|
||||
/**
|
||||
* Options for PocketBase collection fetching.
|
||||
@@ -28,13 +25,23 @@ export type PBFetchOptions = {
|
||||
* Fields to expand (e.g., "stack")
|
||||
*/
|
||||
expand?: string;
|
||||
/**
|
||||
* Cache tags for on-demand revalidation via `revalidateTag`.
|
||||
* Typically set to the collection name.
|
||||
*/
|
||||
tags?: string[];
|
||||
/**
|
||||
* ISR revalidation interval in seconds.
|
||||
* @default 3600
|
||||
*/
|
||||
revalidate?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetch a list of records from a PocketBase collection.
|
||||
*/
|
||||
export async function getCollection<T>(collection: string, options: PBFetchOptions = {}): Promise<ListResponse<T>> {
|
||||
const { sort, filter, expand } = options;
|
||||
const { sort, filter, expand, tags, revalidate } = options;
|
||||
|
||||
const params = new URLSearchParams();
|
||||
if (sort) {
|
||||
@@ -49,9 +56,12 @@ export async function getCollection<T>(collection: string, options: PBFetchOptio
|
||||
|
||||
const url = `${PB_URL}/api/collections/${collection}/records?${params.toString()}`;
|
||||
|
||||
/* force-cache deduplicates identical fetches during the static build phase;
|
||||
* it has no runtime effect in `output: 'export'` mode. */
|
||||
const res = await fetch(url, { cache: 'force-cache' });
|
||||
const res = await fetch(url, {
|
||||
next: {
|
||||
tags: tags ?? [],
|
||||
revalidate: revalidate ?? 3600,
|
||||
},
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`PocketBase ${res.status} ${res.statusText} on collection "${collection}"`);
|
||||
|
||||
Reference in New Issue
Block a user