managarten/nutriphi/apps/mobile/services/DataClearingService.ts
Till-JS 6537863696 feat(nutriphi): migrate from Supabase to PostgreSQL + Hetzner S3
- Add nutriphi-database package with Drizzle ORM
  - meals and nutrition_goals schemas
  - PostgreSQL 16 Docker setup
  - Drizzle Kit configuration

- Migrate backend from Supabase to Drizzle
  - Add DatabaseModule with connection pooling
  - Add StorageService for Hetzner Object Storage (S3-compatible)
  - Update MealsService with Drizzle queries
  - Add /api/meals/upload endpoint for image upload + analysis

- Update web app to use backend for uploads
  - Remove Supabase Storage direct upload
  - Update uploadService to send images to backend
  - Remove Supabase dependencies from package.json
  - Simplify hooks.server.ts

- Add Coolify deployment configuration
  - Dockerfile for production build
  - docker-compose.coolify.yml

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-25 17:52:14 +01:00

145 lines
4.3 KiB
TypeScript

import AsyncStorage from '@react-native-async-storage/async-storage';
import * as FileSystem from 'expo-file-system';
import { SQLiteService } from './database/SQLiteService';
import { PhotoService } from './storage/PhotoService';
import { useMealStore } from '../store/MealStore';
import { useAppStore } from '../store/AppStore';
export class DataClearingService {
private static instance: DataClearingService;
public static getInstance(): DataClearingService {
if (!DataClearingService.instance) {
DataClearingService.instance = new DataClearingService();
}
return DataClearingService.instance;
}
async clearAllData(): Promise<{ success: boolean; errors: string[] }> {
const errors: string[] = [];
try {
// 1. Clear SQLite database
await this.clearDatabase();
} catch (error) {
errors.push(`Database clearing failed: ${error}`);
}
try {
// 2. Clear photo storage
await this.clearPhotoStorage();
} catch (error) {
errors.push(`Photo storage clearing failed: ${error}`);
}
try {
// 3. Reset Zustand stores
this.resetZustandStores();
} catch (error) {
errors.push(`State reset failed: ${error}`);
}
try {
// 4. Clear AsyncStorage
await this.clearAsyncStorage();
} catch (error) {
errors.push(`AsyncStorage clearing failed: ${error}`);
}
// Note: Supabase integration will be added later
// For now, we skip Supabase sign out
return {
success: errors.length === 0,
errors,
};
}
private async clearDatabase(): Promise<void> {
const db = SQLiteService.getInstance();
// Clear all main tables while preserving structure
await db.executeRaw('DELETE FROM meals');
await db.executeRaw('DELETE FROM food_items');
await db.executeRaw('DELETE FROM sync_metadata');
// Reset user preferences to defaults but keep the table
await db.executeRaw('DELETE FROM user_preferences');
// Don't delete schema_migrations to preserve database version
}
private async clearPhotoStorage(): Promise<void> {
const photosDir = `${FileSystem.documentDirectory}photos/`;
// Check if photos directory exists
const dirInfo = await FileSystem.getInfoAsync(photosDir);
if (!dirInfo.exists) return;
// Get all files in photos directory
const files = await FileSystem.readDirectoryAsync(photosDir);
// Delete all photo files
for (const file of files) {
const filePath = `${photosDir}${file}`;
await FileSystem.deleteAsync(filePath, { idempotent: true });
}
// Also cleanup any temp photos
await PhotoService.getInstance().cleanupTempPhotos();
}
private resetZustandStores(): void {
// Reset MealStore
const mealStore = useMealStore.getState();
mealStore.clearAllMeals();
mealStore.setSelectedMeal(null);
// Reset AppStore (but preserve theme preference as it will be handled by AsyncStorage)
const appStore = useAppStore.getState();
appStore.resetStats();
// Reset other app store states except theme
const currentTheme = appStore.theme;
appStore.resetToDefaults();
appStore.setTheme(currentTheme); // Preserve current theme
}
private async clearAsyncStorage(): Promise<void> {
// Get all keys
const keys = await AsyncStorage.getAllKeys();
// Define keys to clear (all except we might want to preserve some)
const keysToRemove = keys.filter(
(key) => key !== 'user-theme-preference' // We might want to preserve theme preference
);
// Clear selected keys
if (keysToRemove.length > 0) {
await AsyncStorage.multiRemove(keysToRemove);
}
}
// TODO: Implement when Supabase is configured
// private async signOutSupabase(): Promise<void> {
// const { error } = await supabase.auth.signOut();
// if (error) {
// throw new Error(`Supabase sign out error: ${error.message}`);
// }
// }
// Optional: Clear everything including theme preference
async clearAllDataIncludingTheme(): Promise<{ success: boolean; errors: string[] }> {
const result = await this.clearAllData();
try {
// Also clear theme preference
await AsyncStorage.removeItem('user-theme-preference');
} catch (error) {
result.errors.push(`Theme preference clearing failed: ${error}`);
result.success = false;
}
return result;
}
}