@rsweeten/dropbox-sync
Version:
Reusable Dropbox synchronization module with framework adapters
123 lines (105 loc) • 3.76 kB
text/typescript
// Example Next.js implementation
// For a private module, you would import from your private registry or local path
// import { useNextDropboxSync, getCredentialsFromCookies } from '@yourcompany/dropbox-sync';
import { useNextDropboxSync, getCredentialsFromCookies } from 'dropbox-sync'
import { useState, useEffect } from 'react'
// Client-side component
export function useDropboxSync() {
const [isConnected, setIsConnected] = useState(false)
const [isSyncing, setIsSyncing] = useState(false)
const [progress, setProgress] = useState(0)
const [message, setMessage] = useState('')
const [error, setError] = useState<string | null>(null)
// Initialize the Dropbox client
const dropboxSync = useNextDropboxSync({
clientId: process.env.NEXT_PUBLIC_DROPBOX_APP_KEY || '',
// Access token will be added automatically in server components via cookies
})
// Check connection status
useEffect(() => {
async function checkConnection() {
try {
const response = await fetch('/api/dropbox/status')
const data = await response.json()
setIsConnected(data.connected)
} catch (error) {
console.error('Error checking connection:', error)
}
}
checkConnection()
}, [])
// Set up socket listeners for real-time updates
useEffect(() => {
if (!dropboxSync) return
// Connect to socket
dropboxSync.socket.connect()
// Listen for progress updates
dropboxSync.socket.on('sync:progress', (data) => {
setProgress(data.progress)
setMessage(data.message)
})
// Listen for completion
dropboxSync.socket.on('sync:complete', (data) => {
setProgress(100)
setMessage(data.message)
setIsSyncing(false)
})
// Listen for errors
dropboxSync.socket.on('sync:error', (data) => {
setError(data.message)
setIsSyncing(false)
})
// Cleanup on unmount
return () => {
dropboxSync.socket.off('sync:progress')
dropboxSync.socket.off('sync:complete')
dropboxSync.socket.off('sync:error')
}
}, [dropboxSync])
// Connect to Dropbox
const connectDropbox = () => {
window.location.href = '/api/dropbox/auth/start'
}
// Disconnect from Dropbox
const disconnectDropbox = async () => {
try {
await fetch('/api/dropbox/logout', { method: 'POST' })
setIsConnected(false)
} catch (error) {
console.error('Error disconnecting:', error)
}
}
// Start sync process
const startSync = async () => {
try {
setIsSyncing(true)
setProgress(0)
setMessage('Initializing Dropbox sync...')
setError(null)
// Emit sync start event via Socket.IO
dropboxSync.socket.emit('dropbox:sync')
} catch (error: any) {
console.error('Error starting sync:', error)
setError(error.message || 'Error starting sync')
setIsSyncing(false)
}
}
// Cancel sync process
const cancelSync = () => {
if (!isSyncing) return
dropboxSync.sync.cancelSync()
setIsSyncing(false)
setMessage('Sync cancelled')
}
return {
isConnected,
isSyncing,
progress,
message,
error,
connectDropbox,
disconnectDropbox,
startSync,
cancelSync,
}
}