You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

259 lines
7.5 KiB

/**
* Advanced usage examples for the Daily Notification plugin
* Demonstrates complex scenarios and best practices
*/
import { registerPlugin } from '@capacitor/core';
import { DailyNotificationPlugin, NotificationOptions, NotificationSettings } from '../src/definitions';
const DailyNotification = registerPlugin<DailyNotificationPlugin>('DailyNotification');
/**
* Example of handling multiple notification schedules
*/
async function handleMultipleSchedules() {
try {
// Morning notification
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/morning-content',
time: '08:00',
title: 'Morning Briefing',
body: 'Your morning briefing is ready',
priority: 'high'
});
// Evening notification
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/evening-content',
time: '20:00',
title: 'Evening Summary',
body: 'Your daily summary is ready',
priority: 'normal'
});
console.log('Multiple schedules set up successfully');
} catch (error) {
console.error('Failed to setup multiple schedules:', error);
}
}
/**
* Example of handling timezone changes
*/
async function handleTimezoneChanges() {
try {
// Get user's timezone
const userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
// Schedule notification with timezone consideration
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/timezone-aware-content',
time: '09:00',
title: 'Timezone-Aware Update',
body: 'Your timezone-aware content is ready',
timezone: userTimezone
});
// Listen for timezone changes
window.addEventListener('timezonechange', async () => {
const newTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
await DailyNotification.updateSettings({
timezone: newTimezone
});
});
} catch (error) {
console.error('Failed to handle timezone changes:', error);
}
}
/**
* Example of implementing retry logic with exponential backoff
*/
async function implementRetryLogic() {
const maxRetries = 3;
const baseDelay = 1000; // 1 second
async function fetchWithRetry(url: string, retryCount = 0): Promise<Response> {
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Network response was not ok');
return response;
} catch (error) {
if (retryCount >= maxRetries) throw error;
const delay = baseDelay * Math.pow(2, retryCount);
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithRetry(url, retryCount + 1);
}
}
try {
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/unstable-content',
time: '10:00',
title: 'Retry-Enabled Update',
body: 'Your content with retry logic is ready',
retryCount: maxRetries,
retryInterval: baseDelay / 1000, // Convert to seconds
contentHandler: async (response) => {
const data = await response.json();
return {
title: data.title,
body: data.content,
data: data.metadata
};
}
});
} catch (error) {
console.error('Failed to implement retry logic:', error);
}
}
/**
* Example of implementing offline support
*/
async function implementOfflineSupport() {
try {
// Check if we're online
const isOnline = navigator.onLine;
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/offline-aware-content',
time: '11:00',
title: 'Offline-Aware Update',
body: 'Your offline-aware content is ready',
offlineFallback: true,
cacheDuration: 24, // Cache for 24 hours
contentHandler: async (response) => {
const data = await response.json();
// Store in IndexedDB for offline access
if ('indexedDB' in window) {
const db = await openDB('notificationCache', 1, {
upgrade(db) {
db.createObjectStore('content');
}
});
await db.put('content', data, 'latest');
}
return {
title: data.title,
body: data.content,
data: data.metadata
};
}
});
// Listen for online/offline events
window.addEventListener('online', () => {
console.log('Back online, syncing content...');
// Trigger content sync
});
window.addEventListener('offline', () => {
console.log('Offline, using cached content...');
// Use cached content
});
} catch (error) {
console.error('Failed to implement offline support:', error);
}
}
/**
* Example of implementing user preferences
*/
async function implementUserPreferences() {
try {
// Get user preferences from storage
const preferences = {
notificationTime: '12:00',
soundEnabled: true,
priority: 'high' as const,
categories: ['news', 'weather', 'tasks']
};
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/personalized-content',
time: preferences.notificationTime,
title: 'Personalized Update',
body: 'Your personalized content is ready',
sound: preferences.soundEnabled,
priority: preferences.priority,
headers: {
'X-User-Categories': preferences.categories.join(',')
}
});
// Listen for preference changes
window.addEventListener('storage', (event) => {
if (event.key === 'notificationPreferences') {
const newPreferences = JSON.parse(event.newValue || '{}');
DailyNotification.updateSettings({
time: newPreferences.notificationTime,
sound: newPreferences.soundEnabled,
priority: newPreferences.priority
});
}
});
} catch (error) {
console.error('Failed to implement user preferences:', error);
}
}
/**
* Example of implementing analytics and monitoring
*/
async function implementAnalytics() {
try {
await DailyNotification.scheduleDailyNotification({
url: 'https://api.example.com/analytics-enabled-content',
time: '13:00',
title: 'Analytics-Enabled Update',
body: 'Your analytics-enabled content is ready',
contentHandler: async (response) => {
const data = await response.json();
// Track notification delivery
await trackEvent('notification_delivered', {
timestamp: new Date().toISOString(),
contentId: data.id,
contentType: data.type
});
return {
title: data.title,
body: data.content,
data: data.metadata
};
}
});
// Track notification interactions
document.addEventListener('notification_clicked', async (event) => {
await trackEvent('notification_clicked', {
timestamp: new Date().toISOString(),
notificationId: event.detail.id,
action: event.detail.action
});
});
} catch (error) {
console.error('Failed to implement analytics:', error);
}
}
// Helper function for analytics
async function trackEvent(eventName: string, properties: Record<string, any>) {
// Implement your analytics tracking logic here
console.log(`Tracking event: ${eventName}`, properties);
}
// Export all advanced example functions
export {
handleMultipleSchedules,
handleTimezoneChanges,
implementRetryLogic,
implementOfflineSupport,
implementUserPreferences,
implementAnalytics
};