Developers
Menu

A copy of every time entry

For payroll detail, a data warehouse, BI dashboards or a backup, the simplest dependable design is a copy of every entry, refreshed on a schedule. Each run asks for what changed since the last one, so a run takes one request when little has happened.

Before you start

A workspace key with Read-only access (or at least time:read), from Workspace settings → Integrations → API keys.

The script

It keeps the copy in a JSON file so it runs as-is; replace save and remove with writes to your database.

js
// Keep a copy of every time entry, up to date: run it as often as you like.
// Node 18 or later; no packages. Usage:
//   PUNCHLY_API_KEY=pkw_… node time-sync.mjs
// The copy and where the last run stopped live in punchly-entries.json; replace `save` and
// `remove` with writes to your own database.

import { existsSync, readFileSync, writeFileSync } from 'node:fs';

const API = process.env.PUNCHLY_API_URL ?? 'https://api.punchly.work/v1';
const KEY = process.env.PUNCHLY_API_KEY;
const STATE = process.env.PUNCHLY_SYNC_FILE ?? 'punchly-entries.json';
if (!KEY) throw new Error('Set PUNCHLY_API_KEY');

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function punchly(method, path) {
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(`${API}${path}`, { method, headers: { 'X-Api-Key': KEY } });
    if (res.status === 429 && attempt < 5) {
      await sleep(Number(res.headers.get('retry-after') ?? 5) * 1000);
      continue;
    }
    const text = await res.text();
    if (!res.ok) throw new Error(`${method} ${path}: ${res.status} ${text}`);
    return JSON.parse(text);
  }
}

async function workspaceId() {
  if (process.env.PUNCHLY_WORKSPACE_ID) return process.env.PUNCHLY_WORKSPACE_ID;
  const { items } = await punchly('GET', '/me/workspaces');
  if (items.length !== 1) throw new Error('Set PUNCHLY_WORKSPACE_ID: the key reaches several');
  return items[0].workspaceId;
}

// Where the last run stopped; the first run starts 30 days back.
const state = existsSync(STATE)
  ? JSON.parse(readFileSync(STATE, 'utf8'))
  : { since: new Date(Date.now() - 30 * 86_400_000).toISOString(), entries: {} };

const save = (entry) => (state.entries[entry.id] = entry);
const remove = (id) => delete state.entries[id];

const wid = await workspaceId();
let cursor = null;
let saved = 0;
let removed = 0;
do {
  const query = new URLSearchParams({
    updatedSince: state.since,
    includeDeleted: 'true',
    limit: '1000',
    ...(cursor && { cursor }),
  });
  const page = await punchly('GET', `/workspaces/${wid}/time-entries/search?${query}`);
  for (const entry of page.items) {
    if (entry.deletedAt) {
      remove(entry.id);
      removed++;
    } else {
      save(entry);
      saved++;
    }
    // Resume from the last change we saw, not from our own clock (the docs say why).
    state.since = entry.updatedAt;
  }
  cursor = page.nextCursor;
} while (cursor);

writeFileSync(STATE, JSON.stringify(state, null, 2));
console.log(
  `saved ${saved}, removed ${removed}; ${Object.keys(state.entries).length} entries kept; next run from ${state.since}`,
);
bash
PUNCHLY_API_KEY=pkw_… node time-sync.mjs
text
saved 123, removed 72; 123 entries kept; next run from 2026-09-30T08:38:26.000Z

Run it every few minutes, every hour, or every night: each run carries on from where the last stopped.

Why it's shaped like this

Joining in names

Entries carry ids: memberId, projectId, taskId, tagIds. Keep a copy of members, projects, clients, tasks and tags the same way (updatedSince works on each list; see Projects and clients in another tool) and join on the ids.