Caching
The PerspectAPI v2 SDK includes an optional caching layer for reducing API calls in server-side rendering and edge environments.
Configuration
Enable caching when creating the client:
import { PerspectApiV2Client } from 'perspectapi-ts-sdk';
import { InMemoryCacheAdapter } from 'perspectapi-ts-sdk';
const client = new PerspectApiV2Client({
baseUrl: 'https://api.example.com',
apiKey: 'your-api-key',
cache: {
adapter: new InMemoryCacheAdapter(),
defaultTtl: 300 // 5 minutes
}
});
Cache Adapters
In-Memory (Default)
Suitable for short-lived processes (serverless functions, edge workers):
import { InMemoryCacheAdapter } from 'perspectapi-ts-sdk';
const adapter = new InMemoryCacheAdapter();
No-Op (Disabled)
Explicitly disable caching:
import { NoopCacheAdapter } from 'perspectapi-ts-sdk';
const adapter = new NoopCacheAdapter();
Custom Adapters
Implement the CacheAdapter interface for Redis, KV, or other stores:
interface CacheAdapter {
get<T>(key: string): Promise<T | null>;
set<T>(key: string, value: T, ttl?: number): Promise<void>;
delete(key: string): Promise<void>;
deleteByTag(tag: string): Promise<void>;
}
Cursor Pagination and Caching
Since v2 uses cursor-based pagination, cache keys automatically include the cursor position:
// These produce different cache keys:
await client.content.list('my-site', { limit: 10 });
await client.content.list('my-site', { limit: 10, starting_after: 'cnt_42' });
Webhook-Based Invalidation
Use outgoing webhooks to invalidate cache when content changes:
// In your webhook handler:
app.post('/webhook', async (req) => {
const event = req.body;
if (event.type === 'content.updated' || event.type === 'content.created') {
await cacheAdapter.deleteByTag(`content:${event.data.site_name}`);
}
if (event.type === 'product.updated') {
await cacheAdapter.deleteByTag(`products:${event.data.site_name}`);
}
return new Response('ok');
});