Skip to content

Data and API

Pulze ships with a fake API full of believable sample data for one company, Acme. Every page reads data through it, so connecting your real backend means replacing the fake functions one area at a time. Nothing in the pages changes.

The sample company

  • The team: Maya Patel (CEO), Rohan Mehta (Sales), Sofia Lindqvist (Support), Kenji Watanabe (Engineering), Amara Okafor (Design), Lucas Martin (Sales), plus six more people.
  • Clients: Northwind Traders, Kestrel Logistics, Cobalt Systems, Brightline Health, Lumen Labs, Orchard & Co., Bluefin Retail, Meridian Foods, Tidewater Media, Summit Analytics.
  • The rest of the dataset:
    • 128 users;
    • 120 shop customers;
    • 40 products;
    • 1,284 orders in the last 30 days, plus 12 months of totals;
    • 240 deals;
    • 52 invoices;
    • 3 projects with 94 tasks, plus this week's tracked time;
    • 54 emails, 6 chats, about 100 calendar events, 26 files in 4 folders;
    • a year of daily website traffic.

The numbers agree with each other:

  • this month's revenue is the sum of this month's orders;
  • the 23 refunds all come from one bad batch of Aero Headphones;
  • the Northwind renewal deal ($42,000, owned by Rohan) is also invoice INV-1048.

Where things live

Path (downloaded project) What it is
src/data/types.ts The shape of every record (User, Order, Deal, Invoice, …)
src/data/seed.config.ts Company, team, clients and counts used to generate the data
src/data/generated/*.json The generated data (don't edit by hand)
src/data/api/*.ts The fake API: one file per area
src/data/content/*.ts Words for Pricing, FAQ, Timeline and the sign-in showcase
src/data/auth/*.ts Sign-in adapter: demo now, your provider later (Authentication)
scripts/seed.ts The generator

1. Using the API in a page

Pages fetch with TanStack Query, which caches results and handles loading and error states:

import { getOrders, useQuery } from "@pulze/data"

const orders = useQuery({
  queryKey: ["orders", { page, status }],
  queryFn: () => getOrders({ page, pageSize: 20, filters: { status } }),
})

if (orders.isPending) return <Skeleton />
if (orders.isError) return <ErrorState onRetry={orders.refetch} />
return <OrdersTable rows={orders.data.items} total={orders.data.total} />

List endpoints accept the same parameters:

Param Example
page, pageSize { page: 2, pageSize: 20 }
sort { key: "createdAt", dir: "desc" }
search "northwind" (matches the fields that endpoint searches)
filters { status: ["paid", "shipped"] }

…and return { items, total, page, pageSize, pageCount }.

Every endpoint

Area Functions
People getUsers, getUser, getTeam, getClients, getCustomers
Commerce getProducts, getOrders, getRecentOrders, getSalesSummary, getMonthlySales, getTopProducts
CRM getDeals, getPipeline, getCrmSummary, getClosingDeals, getTeamActivity, getLeadSources
Invoices getInvoices, getInvoice, getInvoiceTotals
Analytics getTraffic, getBreakdowns, getLiveVisitors
Projects getProjects, getTasks, getTaskWeeks, getUpcomingDeadlines, getWorkload, getTimeTracked
Notifications getNotifications, markNotificationsRead
Search searchAll (every type at once, with a "did you mean" suggestion)
Settings getProfile, saveProfile, getNotificationPrefs, saveNotificationPrefs, getBilling, setDefaultPaymentMethod, removePaymentMethod, getSecurity, setTwoStep, endSessions, changePassword, getApiKeys, createApiKey, revokeApiKey, getIntegrations, setIntegration
Kanban moveTask, createTask, updateTask, deleteTask, getChecklist, setChecklist, getTaskComments, addTaskComment
Mail getMail, getMailCounts, updateMail, sendMail
Chat getConversations, getMessages, sendMessage, markConversationRead
Calendar getEvents, createEvent, deleteEvent
Files getFolders, getFiles, getStorage, addFile, updateFile, deleteFiles, restoreFiles, createFolder
Writes createInvoice, setInvoiceStatus, inviteUsers, updateUsers, removeUsers, restoreUsers

Changes made through the fake API live in memory (api/store.ts) and reset on reload. Each app's page in Each app shows how to point it at a real backend.

useCurrentUser() returns the signed-in person (the sample user until you connect sign-in).

2. Test loading, empty and error states

Add these to any page's address:

URL Result
?empty=1 Every call returns no data, so you see each empty state
?error=1 Every call fails, so you see each error state with "Try again"

Each call waits 300–600 ms, so loading skeletons are visible. To change or remove the delay:

import { configureApi } from "@pulze/data"
configureApi({ latency: [0, 0] })

3. Dates always look current

The sample data was generated with "today" set to anchor in seed.config.ts. When the app runs, the fake API moves every date forward by the time that has passed since then. "12 minutes ago" stays 12 minutes ago, and the charts end today. To turn it off: configureApi({ shiftDates: false }).

4. Make the sample data your own

  1. Edit seed.config.ts: company name and domain, team members, clients, and how many of each record to create.

  2. Run the generator:

    pnpm seed
    
  3. Restart pnpm dev.

The same seed number always gives the same data. Change it to get a different, still realistic, set.

5. Connect your real backend

Do it one area at a time. For example, orders:

  1. Open src/data/api/commerce.ts.

  2. Replace the body of getOrders with a real request. Keep the function name, parameters and return shape:

    export async function getOrders(
      params: ListParams<Order> = {}
    ): Promise<ListResult<Order>> {
      const qs = new URLSearchParams({
        page: String(params.page ?? 1),
        pageSize: String(params.pageSize ?? 20),
        ...(params.search ? { q: params.search } : {}),
      })
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/orders?${qs}`, {
        credentials: "include",
      })
      if (!res.ok) throw new ApiError("Couldn't load orders", res.status)
      return res.json()
    }
    
  3. If your API returns a different shape, convert it in this function (rename fields, turn decimal prices into cents), so the pages don't need to change.

  4. Repeat for the next area. When none of them uses respond() any more, delete api/client.ts's fake helpers and generated/.

The same function with Supabase

pnpm add @supabase/supabase-js
// src/data/supabase.ts
import { createClient } from "@supabase/supabase-js"

export const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!, // Vite: import.meta.env.VITE_SUPABASE_URL
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
)
// src/data/api/commerce.ts
import { supabase } from "../supabase"

export async function getOrders(
  params: ListParams<Order> = {}
): Promise<ListResult<Order>> {
  const page = params.page ?? 1
  const pageSize = params.pageSize ?? 20
  let q = supabase.from("orders").select("*", { count: "exact" })

  if (params.search) q = q.ilike("customer_name", `%${params.search}%`)
  for (const [key, value] of Object.entries(params.filters ?? {}))
    q = Array.isArray(value) ? q.in(key, value) : q.eq(key, value as string)
  if (params.sort) q = q.order(params.sort.key, { ascending: params.sort.dir === "asc" })

  const { data, count, error } = await q.range((page - 1) * pageSize, page * pageSize - 1)
  if (error) throw new ApiError("Couldn't load orders", 500)

  const total = count ?? 0
  return {
    items: data.map(toOrder),
    total,
    page,
    pageSize,
    pageCount: Math.ceil(total / pageSize),
  }
}

/** Database row (snake_case) → Pulze's Order. */
function toOrder(row: Record<string, unknown>): Order {
  return {
    id: String(row.id),
    number: Number(row.number),
    customerId: String(row.customer_id),
    items: (row.items as Order["items"]) ?? [],
    total: Number(row.total_cents), // keep money in cents
    status: row.status as Order["status"],
    channel: row.channel as Order["channel"],
    createdAt: String(row.created_at),
  }
}

Turn on Row Level Security for every table, so the anon key only reads what the signed-in person may see.

The same function with Firebase (Firestore)

Firestore can't jump to "page 7" or count matches cheaply, so for collections up to a few thousand rows the simplest correct approach is to load them once and let Pulze's own list() helper search, filter, sort and page them in the browser:

// src/data/api/commerce.ts
import { collection, getDocs, getFirestore, orderBy, query } from "firebase/firestore"

import { list } from "./list"

const db = getFirestore() // after initializeApp (see the Firebase Auth guide)

export async function getOrders(
  params: ListParams<Order> = {}
): Promise<ListResult<Order>> {
  const snap = await getDocs(
    query(collection(db, "orders"), orderBy("createdAt", "desc"))
  )
  const rows = snap.docs.map((d) => ({ id: d.id, ...d.data() }) as Order)
  return list(rows, params, ["number"])
}

TanStack Query caches the result, so moving between pages doesn't read again. For larger collections, filter and page on the server with where(), orderBy(), limit() and startAfter(), and keep the total in a counter document that you update when rows are added or removed.

Set up Firebase itself (keys, initializeApp) as in steps 1–2 of the Firebase Auth guide. Real-time updates for Chat are in Each app › Chat.

6. Money

Every amount is an integer in minor units: cents for USD, paise for INR. $84,320.00 is stored as 8432000. This avoids rounding errors. Format with formatMoney() (see Formatting). If your API sends decimals, convert once in the API function: Math.round(price * 100).