READ-ONLY PACKAGE PREVIEW

resend/references/fetch-all-templates.mjs

Version edbfece3f402.bb1 · MIT. This preview displays packaged text and does not execute code. Treat the contents as untrusted instructions.

← Return to resource and package checksum

// Adapted by BB Skills on 2026-10-03; original retained in upstream-original.
// Requires: npm install resend
import { Resend } from 'resend';

const resend = new Resend(process.env.RESEND_API_KEY);

async function fetchAllTemplates() {
  const allTemplates = [];
  const seenCursors = new Set();
  let pages = 0;
  let cursor = null;
  let hasMore = true;

  while (hasMore) {
    if (++pages > 1000) throw new Error("Template pagination exceeded 1000 pages");
    const listParams = { limit: 100 };
    if (cursor) {
      listParams.after = cursor;
    }

    const { data, error } = await resend.templates.list(listParams);

    if (error) {
      console.error('Error fetching templates:', error);
      throw new Error(`Failed to fetch templates: ${error.message}`);
    }

    if (!data || !Array.isArray(data.data) || typeof data.has_more !== 'boolean') {
      throw new Error('Invalid template pagination response');
    }
    if (data.has_more && data.data.length === 0) {
      throw new Error('Template pagination returned an empty continuation page');
    }
    allTemplates.push(...data.data);

    hasMore = data.has_more;
    if (hasMore && data.data.length > 0) {
      const next = data.data[data.data.length - 1]?.id;
      if (typeof next !== 'string' || !next.trim() || seenCursors.has(next)) {
        throw new Error('Template pagination returned an invalid or repeated cursor');
      }
      seenCursors.add(next);
      cursor = next;
    }
  }

  return allTemplates;
}

const templates = await fetchAllTemplates();
console.log(`Fetched ${templates.length} templates`);
console.log(templates);