Skip to content
thefaqappthefaqapp
Browse docs

Patterns and recipes

Drop-in patterns for error handling, exhaustive pagination, debounced search, request batching, and periodic export.

Updated 2026-10-11

Copy-paste-ready patterns for the situations the reference does not cover. All examples use @faqapp/core and a client named faq, created as in CRUD workflows.

Error handler

One helper that maps every SDK error class to an action, with a bounded retry on rate limits:

import {
  FAQAPIError,
  FAQNetworkError,
  FAQNotFoundError,
  FAQRateLimitError,
  FAQTimeoutError,
  FAQValidationError
} from "@faqapp/core";

export async function safeCall<T>(fn: () => Promise<T>, attempts = 2): Promise<T | null> {
  try {
    return await fn();
  } catch (err) {
    if (err instanceof FAQValidationError) {
      console.warn("validation failed", err.errors);
      return null;
    }
    if (err instanceof FAQNotFoundError) return null;
    if (err instanceof FAQRateLimitError && attempts > 1) {
      await new Promise(resolve => setTimeout(resolve, (err.retryAfter ?? 1) * 1000));
      return safeCall(fn, attempts - 1);
    }
    if (err instanceof FAQTimeoutError || err instanceof FAQNetworkError) {
      console.warn("transient", err.message);
      return null;
    }
    if (err instanceof FAQAPIError) {
      console.error(`[${err.code}] ${err.message} (request: ${err.requestId})`);
      return null;
    }
    throw err;
  }
}

const result = await safeCall(() => faq.questions.get("how-do-i-cancel"));
console.log(result?.data.question ?? "not found");

The SDK already retries network errors and 5xx responses with backoff before it throws.

Exhaustive pagination

Every list returns a page that is also an async iterable source. iter() streams items as each page arrives:

let count = 0;
for await (const question of faq.questions.list({ status: "published", limit: 100 }).iter()) {
  count += 1;
  console.log(question.question);
}
console.log(count);

Use iterPages() when you want whole pages instead of items.

For a search box that queries as the user types, call search.query after a pause. It works with a publishable key:

import type { SearchResult } from "@faqapp/core";

export function createDebouncedSearch(onResults: (results: SearchResult[]) => void, delay = 250) {
  let handle: ReturnType<typeof setTimeout> | undefined;
  return (query: string) => {
    clearTimeout(handle);
    if (query.trim().length < 2) {
      onResults([]);
      return;
    }
    handle = setTimeout(async () => {
      const { data } = await faq.search.query({ q: query, limit: 8 });
      onResults(data.results);
    }, delay);
  };
}

In React, useSearch(query) from @faqapp/react does the same thing with a 250 ms debounce.

Request batching for high-write workloads

When you have hundreds of writes in a short window, run them in small concurrent chunks:

async function batchWrite<T, R>(items: T[], fn: (item: T) => Promise<R>, concurrency = 5): Promise<R[]> {
  const out: R[] = [];
  for (let i = 0; i < items.length; i += concurrency) {
    const chunk = items.slice(i, i + concurrency);
    out.push(...(await Promise.all(chunk.map(fn))));
  }
  return out;
}

const rows = [{ q: "How do refunds work?", a: "Refunds land in five business days.", cat: "billing" }];

await batchWrite(rows, row =>
  faq.questions.create({ question: row.q, answer: row.a, categorySlug: row.cat })
);

Write limits are per minute: 6 on Free, 60 on Starter, 600 on Pro. For more than a few hundred rows, prefer faq.questions.bulk, which takes 100 questions per call.

Periodic export

Mirror your FAQ to a JSON file on disk every hour, atomically:

import { rename, writeFile } from "node:fs/promises";
import type { Question } from "@faqapp/core";

async function exportAll() {
  const all: Question[] = [];
  for await (const question of faq.questions.list({ limit: 100 }).iter()) all.push(question);

  const tmp = "/var/lib/faq-cache/questions.json.tmp";
  const final = "/var/lib/faq-cache/questions.json";
  await writeFile(tmp, JSON.stringify(all));
  await rename(tmp, final);
}

setInterval(exportAll, 60 * 60 * 1000);
await exportAll();

The temp file plus rename means readers never see a half-written file. Pair it with a CDN cache that revalidates against the exported file for high-traffic public pages.

Polling for changes without webhooks

Webhooks are available on Starter and above: subscribe to question and category events and receive signed payloads. See the webhooks guide.

On Free, or when you would rather not run an endpoint, poll instead:

import type { Question } from "@faqapp/core";

let lastSeen = new Date(0);

async function tick(onUpdated: (question: Question) => void) {
  const startedAt = new Date();
  for await (const question of faq.questions.list({ limit: 100, sortBy: "updated" }).iter()) {
    if (question.updatedAt && new Date(question.updatedAt) > lastSeen) onUpdated(question);
  }
  lastSeen = startedAt;
}

setInterval(() => tick(question => console.log("updated", question.slug)), 5 * 60 * 1000);

Polling works on any plan. For push delivery, use webhooks.