Skip to main content
The Gmail service provides methods for connecting Gmail accounts, managing OAuth tokens, and monitoring Gmail watches for automatic transaction detection.

Installation

import { gmailService } from '../services/gmail.service';

Types

GmailConnection

Represents a Gmail OAuth connection.
id
string
required
Unique identifier for the connection
gmail_email
string
required
The connected Gmail email address
connected_at
string
required
ISO 8601 timestamp when the connection was established
expires_at
string
ISO 8601 timestamp when the OAuth token expires
is_active
boolean
required
Whether the connection is currently active
status
'connected' | 'needs_reconnect' | 'disconnected'
required
Current status of the connection

GmailStatus

Aggregated status information for all Gmail connections.
connections
GmailConnection[]
required
Array of all Gmail connections
total
number
required
Total number of connections
activeTotal
number
required
Number of active connections (connected + needs_reconnect)
connectedTotal
number
required
Number of fully connected accounts
needsReconnectTotal
number
required
Number of accounts that need reconnection
disconnectedTotal
number
required
Number of disconnected accounts

GmailWatch

Represents a Gmail API watch for push notifications.
id
string
required
Unique identifier for the watch
gmail_email
string
required
Email address being watched
watch_id
string
required
Gmail API watch identifier
topic_name
string
required
Pub/Sub topic name for notifications
expiration
string
required
ISO 8601 timestamp when the watch expires
is_active
boolean
required
Whether the watch is currently active

Methods

getConnectionStatus

Retrieves the Gmail connection status for a user with caching.
async getConnectionStatus(userId: string): Promise<GmailStatus>
userId
string
required
The user ID to fetch connection status for
returns
Promise<GmailStatus>
The aggregated Gmail connection status
Results are cached for 60 seconds to reduce database queries. Use clearConnectionStatusCache() to invalidate the cache when making connection changes.

Example

import { gmailService } from '../services/gmail.service';

const status = await gmailService.getConnectionStatus(userId);

if (status.connectedTotal > 0) {
  console.log(`User has ${status.connectedTotal} connected Gmail accounts`);
}

if (status.needsReconnectTotal > 0) {
  console.log(`${status.needsReconnectTotal} accounts need reconnection`);
}

getWatches

Retrieves active Gmail watches for a user.
async getWatches(userId: string): Promise<GmailWatch[]>
userId
string
required
The user ID to fetch watches for
returns
Promise<GmailWatch[]>
Array of active Gmail watches, empty array if none found or on error

Example

const watches = await gmailService.getWatches(userId);

watches.forEach(watch => {
  console.log(`Watching ${watch.gmail_email} until ${watch.expiration}`);
});

connectGmail

Initiates the Gmail OAuth connection flow by redirecting to the authentication endpoint.
async connectGmail(): Promise<void>
This method redirects the user to the OAuth flow and does not return. It requires an active Supabase session.
Throws:
  • Error if no active session exists
  • Error if user cannot be retrieved

Example

import { gmailService } from '../services/gmail.service';

try {
  await gmailService.connectGmail();
  // User will be redirected to OAuth flow
} catch (error) {
  console.error('Failed to start Gmail connection:', error);
  alert('Please refresh the page and try again.');
}

disconnectGmail

Disconnects a Gmail account by revoking the OAuth token.
async disconnectGmail(connectionId: string): Promise<{
  success: boolean;
  error?: string;
}>
connectionId
string
required
The ID of the Gmail connection to disconnect
success
boolean
required
Whether the disconnection was successful
error
string
Error message if the disconnection failed

Example

const result = await gmailService.disconnectGmail(connectionId);

if (result.success) {
  // Clear the cache to refresh UI
  gmailService.clearConnectionStatusCache(userId);
  console.log('Gmail account disconnected successfully');
} else {
  console.error('Failed to disconnect:', result.error);
}

clearConnectionStatusCache

Clears the cached Gmail connection status.
clearConnectionStatusCache(userId?: string): void
userId
string
Optional user ID. If provided, clears cache only for that user. If omitted, clears all cached statuses.

Example

// Clear cache for specific user
gmailService.clearConnectionStatusCache(userId);

// Clear all cached statuses
gmailService.clearConnectionStatusCache();

Error Handling

All async methods may throw errors. It’s recommended to wrap calls in try-catch blocks:
try {
  const status = await gmailService.getConnectionStatus(userId);
  // Handle success
} catch (error) {
  console.error('Failed to fetch Gmail status:', error);
  // Handle error
}

Dependencies

  • Supabase Client: Uses getSupabase() for database queries and authentication
  • Edge Functions: Calls the following Supabase Edge Functions:
    • auth-start: Initiates OAuth flow
    • gmail-disconnect: Revokes OAuth tokens
  • Database Tables:
    • user_oauth_tokens: Stores OAuth connection data
    • gmail_watches: Stores Gmail watch configurations

Usage with React Query

The service is typically used with React Query hooks for automatic caching and updates:
import { useQuery } from '@tanstack/react-query';
import { gmailService } from '../services/gmail.service';

function useGmailStatus(userId?: string) {
  return useQuery({
    queryKey: ['gmail', 'status', userId],
    queryFn: () => gmailService.getConnectionStatus(userId!),
    enabled: !!userId,
    staleTime: 2 * 60 * 1000, // 2 minutes
  });
}

Build docs developers (and LLMs) love