Skip to main content
POST
/
api
/
services
/
[id]
/
sync
Sync Service Emails
curl --request POST \
  --url 'https://api.example.com/api/services/[id]/sync'
{
  "ok": true,
  "mode": "<string>",
  "threadsProcessed": 123,
  "messagesProcessed": 123
}
Synchronizes emails from Gmail into the DelightBridge database. Supports both full sync (all emails) and incremental sync (only new emails since last sync).

Authentication

Requires admin session. Only users with admin permission can trigger email synchronization.
This endpoint requires admin privileges and the service must be connected to Gmail via OAuth.

Path parameters

id
string
required
The unique identifier of the service to sync

Query parameters

mode
string
default:"incremental"
Sync mode: full or incremental
  • incremental - Only fetch new emails since last sync
  • full - Re-sync all emails from Gmail

Sync modes

Incremental sync (default)

Fetches only new emails since the last sync by using Gmail’s history API:
  • Uses stored lastHistoryId to determine starting point
  • More efficient for regular updates
  • Recommended for scheduled sync jobs
  • Faster execution time

Full sync

Re-downloads all emails from Gmail:
  • Ignores lastHistoryId
  • Fetches complete email history
  • Useful after connection issues or data corruption
  • Slower but ensures data consistency

Response

ok
boolean
required
Whether the sync completed successfully
mode
string
required
The sync mode that was used: full or incremental
threadsProcessed
number
Number of email threads processed (optional, implementation-dependent)
messagesProcessed
number
Number of individual messages processed (optional, implementation-dependent)

Response examples

{
  "ok": true,
  "mode": "incremental",
  "threadsProcessed": 12,
  "messagesProcessed": 18
}

Code examples

curl --request POST \
  --url 'https://your-domain.com/api/services/service-123/sync' \
  --cookie 'authjs.session-token=YOUR_ADMIN_SESSION_TOKEN'

Implementation details

The sync process performs the following operations:
  1. Authentication check: Validates admin session
  2. Mode determination: Reads mode query parameter
  3. Function routing: Calls syncAccountFull() or syncAccountIncremental()
  4. Gmail API calls: Fetches emails using service’s OAuth tokens
  5. Data transformation: Converts Gmail messages to database schema
  6. Database updates: Inserts/updates threads and messages
  7. History tracking: Updates lastHistoryId for incremental syncs

Gmail API integration

The sync functions use the Gmail API with the service’s stored OAuth tokens:
// Pseudocode of sync implementation
async function syncAccountIncremental(accountId: string) {
  const account = await db.query.gmailAccounts.findFirst({
    where: eq(gmailAccounts.id, accountId)
  });
  
  const gmail = google.gmail({
    version: 'v1',
    auth: oauthClient.setCredentials({
      access_token: account.accessToken,
      refresh_token: account.refreshToken,
    }),
  });
  
  const response = await gmail.users.history.list({
    userId: 'me',
    startHistoryId: account.lastHistoryId,
  });
  
  // Process and store new messages
  // ...
}

Error handling

Common errors:
  • Service not connected: No refresh token in database
  • Token expired: Automatic refresh attempted
  • Token refresh failed: OAuth connection needs to be re-established
  • Gmail API quota exceeded: Rate limiting in effect
  • Network errors: Temporary Gmail API unavailability
If sync fails due to invalid OAuth tokens, reconnect the service using the Connect endpoint.

Performance considerations

  • Incremental sync: Typically completes in 1-5 seconds
  • Full sync: Can take several minutes for accounts with large email volumes
  • Rate limits: Gmail API has quota limits; avoid frequent full syncs
  • Concurrency: Do not sync the same service simultaneously
Schedule incremental syncs every 5-15 minutes for near real-time email updates. Use full sync only when necessary.

Next steps

After syncing emails:
  1. View email threads using GET /api/threads
  2. Generate AI drafts with POST /api/drafts/generate
  3. Send responses through POST /api/threads/send

Build docs developers (and LLMs) love