fix(mobile): wire data-export button to real API, matching web fix 842be56e
The mobile GDPR export screen (app/backup/export.tsx) called backupService.exportData -> POST /compliance/export-data, an endpoint that never existed on the backend and always 404'd silently (same bug class as the web buttons fixed in 842be56e). Added requestDataExport/getDataExportStatus to backupService.ts and a new utils/dataExportFlow.ts (mirroring web/utils/dataExportFlow.ts) that drives the real async pipeline at /api/v1/data-export (request -> poll status -> download), confirmed live via backend/src/routes/dataExport.ts. Downloads the ready file to local storage with expo-file-system (already a dependency) and hands it to expo-sharing (newly added; no suitable dependency for file sharing already existed) so the user can save or share it via the OS share sheet. Collapsed the screen's fake JSON/CSV format picker to the one format the backend actually produces (JSON) and surfaces every failure (request, poll timeout, download, share) as a visible alert instead of failing silently. Added unit tests for the service calls and the export flow, plus a screen-level test for the button wiring and error paths. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
parent
842be56e80
commit
ca5c909077
99
gitgram/mobile/__tests__/app/backup/export.test.tsx
Normal file
99
gitgram/mobile/__tests__/app/backup/export.test.tsx
Normal file
@ -0,0 +1,99 @@
|
||||
import React from 'react';
|
||||
import { Alert } from 'react-native';
|
||||
import { render, fireEvent, waitFor, act } from '@testing-library/react-native';
|
||||
import ExportDataScreen from '../../../app/backup/export';
|
||||
import {
|
||||
requestAndDownloadDataExport,
|
||||
shareExportFile,
|
||||
DataExportTimeoutError,
|
||||
} from '../../../utils/dataExportFlow';
|
||||
|
||||
jest.mock('../../../utils/dataExportFlow');
|
||||
|
||||
describe('ExportDataScreen', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.spyOn(Alert, 'alert').mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
it('wires the export button to the real data-export flow and shares the result', async () => {
|
||||
(requestAndDownloadDataExport as jest.Mock).mockImplementation(async (onPhaseChange) => {
|
||||
onPhaseChange?.('requesting');
|
||||
onPhaseChange?.('processing');
|
||||
onPhaseChange?.('downloading');
|
||||
onPhaseChange?.('done');
|
||||
return { exportId: 'export-123', fileUri: 'file:///mock-cache/export.json' };
|
||||
});
|
||||
(shareExportFile as jest.Mock).mockResolvedValue(undefined);
|
||||
|
||||
const { getByText } = render(<ExportDataScreen />);
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.press(getByText('JSON'));
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(requestAndDownloadDataExport).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
expect(shareExportFile).toHaveBeenCalledWith('file:///mock-cache/export.json');
|
||||
expect(getByText('Your data export is ready.')).toBeTruthy();
|
||||
expect(Alert.alert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows a user-visible error instead of failing silently when the export request fails', async () => {
|
||||
(requestAndDownloadDataExport as jest.Mock).mockRejectedValue(
|
||||
new Error('Network request failed')
|
||||
);
|
||||
|
||||
const { getByText } = render(<ExportDataScreen />);
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.press(getByText('JSON'));
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(Alert.alert).toHaveBeenCalledWith('Export Failed', 'Network request failed');
|
||||
});
|
||||
expect(shareExportFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows a friendly timeout message when the export never becomes ready', async () => {
|
||||
(requestAndDownloadDataExport as jest.Mock).mockRejectedValue(
|
||||
new DataExportTimeoutError('export-slow')
|
||||
);
|
||||
|
||||
const { getByText } = render(<ExportDataScreen />);
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.press(getByText('JSON'));
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Export Failed',
|
||||
'Still preparing your export. Please check back in a few minutes.'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('tells the user the export downloaded even if sharing it fails', async () => {
|
||||
(requestAndDownloadDataExport as jest.Mock).mockResolvedValue({
|
||||
exportId: 'export-123',
|
||||
fileUri: 'file:///mock-cache/export.json',
|
||||
});
|
||||
(shareExportFile as jest.Mock).mockRejectedValue(new Error('Share sheet unavailable'));
|
||||
|
||||
const { getByText } = render(<ExportDataScreen />);
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.press(getByText('JSON'));
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(Alert.alert).toHaveBeenCalledWith(
|
||||
'Export Downloaded',
|
||||
'Your data export was downloaded but could not be opened for sharing. It is saved in app storage.'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
61
gitgram/mobile/__tests__/services/backupService.test.ts
Normal file
61
gitgram/mobile/__tests__/services/backupService.test.ts
Normal file
@ -0,0 +1,61 @@
|
||||
import { backupService } from '../../services/backupService';
|
||||
import api from '../../services/api';
|
||||
|
||||
jest.mock('../../services/api');
|
||||
|
||||
describe('backupService', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('requestDataExport', () => {
|
||||
it('calls the real GDPR export request endpoint', async () => {
|
||||
const mockResponse = {
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
exportId: 'export-123',
|
||||
estimatedTime: '2-5 minutes',
|
||||
createdAt: '2026-10-21T00:00:00.000Z',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
(api.post as jest.Mock).mockResolvedValue(mockResponse);
|
||||
|
||||
const result = await backupService.requestDataExport();
|
||||
|
||||
expect(api.post).toHaveBeenCalledWith('/data-export/request');
|
||||
expect(result).toEqual(mockResponse.data);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDataExportStatus', () => {
|
||||
it('calls the status endpoint with the exportId path param', async () => {
|
||||
const mockResponse = {
|
||||
data: {
|
||||
success: true,
|
||||
data: { exportId: 'export-123', status: 'processing', progress: 40 },
|
||||
},
|
||||
};
|
||||
|
||||
(api.get as jest.Mock).mockResolvedValue(mockResponse);
|
||||
|
||||
const result = await backupService.getDataExportStatus('export-123');
|
||||
|
||||
expect(api.get).toHaveBeenCalledWith('/data-export/export-123/status');
|
||||
expect(result).toEqual(mockResponse.data);
|
||||
});
|
||||
});
|
||||
|
||||
describe('exportData (legacy, deprecated)', () => {
|
||||
it('still calls the old non-existent compliance endpoint', async () => {
|
||||
const mockResponse = { data: { message: 'queued' } };
|
||||
(api.post as jest.Mock).mockResolvedValue(mockResponse);
|
||||
|
||||
await backupService.exportData('json');
|
||||
|
||||
expect(api.post).toHaveBeenCalledWith('/compliance/export-data', { format: 'json' });
|
||||
});
|
||||
});
|
||||
});
|
||||
212
gitgram/mobile/__tests__/utils/dataExportFlow.test.ts
Normal file
212
gitgram/mobile/__tests__/utils/dataExportFlow.test.ts
Normal file
@ -0,0 +1,212 @@
|
||||
import * as FileSystem from 'expo-file-system/legacy';
|
||||
import * as Sharing from 'expo-sharing';
|
||||
import {
|
||||
requestAndDownloadDataExport,
|
||||
shareExportFile,
|
||||
DataExportTimeoutError,
|
||||
} from '../../utils/dataExportFlow';
|
||||
import { backupService } from '../../services/backupService';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
|
||||
jest.mock('../../services/backupService');
|
||||
jest.mock('../../store/authStore');
|
||||
|
||||
describe('dataExportFlow', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.useRealTimers();
|
||||
|
||||
(useAuthStore.getState as jest.Mock) = jest.fn(() => ({
|
||||
accessToken: 'test-access-token',
|
||||
refreshAccessToken: jest.fn(),
|
||||
}));
|
||||
});
|
||||
|
||||
describe('requestAndDownloadDataExport', () => {
|
||||
it('requests the export, polls until ready, then downloads the file', async () => {
|
||||
(backupService.requestDataExport as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-abc', estimatedTime: '2-5 minutes', createdAt: 'now' },
|
||||
});
|
||||
|
||||
(backupService.getDataExportStatus as jest.Mock)
|
||||
.mockResolvedValueOnce({
|
||||
success: true,
|
||||
data: { exportId: 'export-abc', status: 'processing', progress: 20 },
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
success: true,
|
||||
data: { exportId: 'export-abc', status: 'ready', progress: 100 },
|
||||
});
|
||||
|
||||
jest.useFakeTimers();
|
||||
const phases: string[] = [];
|
||||
const resultPromise = requestAndDownloadDataExport((phase) => phases.push(phase));
|
||||
await jest.advanceTimersByTimeAsync(3000);
|
||||
const result = await resultPromise;
|
||||
jest.useRealTimers();
|
||||
|
||||
expect(backupService.requestDataExport).toHaveBeenCalledTimes(1);
|
||||
expect(backupService.getDataExportStatus).toHaveBeenCalledTimes(2);
|
||||
expect(FileSystem.downloadAsync).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/data-export/export-abc/download'),
|
||||
expect.stringContaining('export-abc'),
|
||||
{ headers: { Authorization: 'Bearer test-access-token' } }
|
||||
);
|
||||
expect(result).toEqual({
|
||||
exportId: 'export-abc',
|
||||
fileUri: 'file:///mock-cache/mock-export.json',
|
||||
});
|
||||
expect(phases).toEqual(['requesting', 'processing', 'downloading', 'done']);
|
||||
});
|
||||
|
||||
it('falls back to a refreshed token when there is no access token yet', async () => {
|
||||
const refreshAccessToken = jest.fn().mockResolvedValue('refreshed-token');
|
||||
(useAuthStore.getState as jest.Mock).mockReturnValue({
|
||||
accessToken: null,
|
||||
refreshAccessToken,
|
||||
});
|
||||
|
||||
(backupService.requestDataExport as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-xyz', estimatedTime: '2-5 minutes', createdAt: 'now' },
|
||||
});
|
||||
(backupService.getDataExportStatus as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-xyz', status: 'ready', progress: 100 },
|
||||
});
|
||||
|
||||
await requestAndDownloadDataExport();
|
||||
|
||||
expect(refreshAccessToken).toHaveBeenCalledTimes(1);
|
||||
expect(FileSystem.downloadAsync).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
expect.any(String),
|
||||
{ headers: { Authorization: 'Bearer refreshed-token' } }
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when the user is not signed in and cannot refresh a token', async () => {
|
||||
(useAuthStore.getState as jest.Mock).mockReturnValue({
|
||||
accessToken: null,
|
||||
refreshAccessToken: jest.fn().mockResolvedValue(null),
|
||||
});
|
||||
|
||||
(backupService.requestDataExport as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-xyz', estimatedTime: '2-5 minutes', createdAt: 'now' },
|
||||
});
|
||||
(backupService.getDataExportStatus as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-xyz', status: 'ready', progress: 100 },
|
||||
});
|
||||
|
||||
await expect(requestAndDownloadDataExport()).rejects.toThrow(
|
||||
'You must be signed in to export your data.'
|
||||
);
|
||||
});
|
||||
|
||||
it('throws a user-visible error when the export fails server-side', async () => {
|
||||
(backupService.requestDataExport as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-fail', estimatedTime: '2-5 minutes', createdAt: 'now' },
|
||||
});
|
||||
(backupService.getDataExportStatus as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-fail', status: 'failed', progress: 0 },
|
||||
});
|
||||
|
||||
await expect(requestAndDownloadDataExport()).rejects.toThrow(
|
||||
'Data export failed. Please try again.'
|
||||
);
|
||||
});
|
||||
|
||||
it('throws a user-visible error when the export expires before download', async () => {
|
||||
(backupService.requestDataExport as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-expired', estimatedTime: '2-5 minutes', createdAt: 'now' },
|
||||
});
|
||||
(backupService.getDataExportStatus as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-expired', status: 'expired', progress: 100 },
|
||||
});
|
||||
|
||||
await expect(requestAndDownloadDataExport()).rejects.toThrow(
|
||||
'Data export expired before it could be downloaded. Please request a new one.'
|
||||
);
|
||||
});
|
||||
|
||||
it('propagates the request error without silently swallowing it', async () => {
|
||||
(backupService.requestDataExport as jest.Mock).mockRejectedValue(
|
||||
new Error('Network request failed')
|
||||
);
|
||||
|
||||
await expect(requestAndDownloadDataExport()).rejects.toThrow('Network request failed');
|
||||
expect(backupService.getDataExportStatus).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws DataExportTimeoutError when the export never becomes ready', async () => {
|
||||
(backupService.requestDataExport as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-slow', estimatedTime: '2-5 minutes', createdAt: 'now' },
|
||||
});
|
||||
(backupService.getDataExportStatus as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-slow', status: 'processing', progress: 10 },
|
||||
});
|
||||
|
||||
jest.useFakeTimers();
|
||||
// Attach the rejection assertion synchronously, right when the promise
|
||||
// is created, so Node never sees it as unhandled while the fake timers
|
||||
// are advanced below.
|
||||
const assertion = expect(requestAndDownloadDataExport()).rejects.toBeInstanceOf(
|
||||
DataExportTimeoutError
|
||||
);
|
||||
// Let every poll's sleep() resolve without waiting real wall-clock time.
|
||||
await jest.advanceTimersByTimeAsync(3000 * 61);
|
||||
|
||||
await assertion;
|
||||
jest.useRealTimers();
|
||||
}, 15000);
|
||||
|
||||
it('surfaces a non-2xx download status as a thrown error', async () => {
|
||||
(backupService.requestDataExport as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-bad', estimatedTime: '2-5 minutes', createdAt: 'now' },
|
||||
});
|
||||
(backupService.getDataExportStatus as jest.Mock).mockResolvedValue({
|
||||
success: true,
|
||||
data: { exportId: 'export-bad', status: 'ready', progress: 100 },
|
||||
});
|
||||
(FileSystem.downloadAsync as jest.Mock).mockResolvedValueOnce({
|
||||
uri: 'file:///mock-cache/export-bad.json',
|
||||
status: 410,
|
||||
});
|
||||
|
||||
await expect(requestAndDownloadDataExport()).rejects.toThrow(
|
||||
'Failed to download export (status 410).'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('shareExportFile', () => {
|
||||
it('shares the downloaded file via the OS share sheet', async () => {
|
||||
await shareExportFile('file:///mock-cache/mock-export.json');
|
||||
|
||||
expect(Sharing.isAvailableAsync).toHaveBeenCalledTimes(1);
|
||||
expect(Sharing.shareAsync).toHaveBeenCalledWith('file:///mock-cache/mock-export.json', {
|
||||
mimeType: 'application/json',
|
||||
dialogTitle: 'Save or share your data export',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws a user-visible error when sharing is unavailable on this device', async () => {
|
||||
(Sharing.isAvailableAsync as jest.Mock).mockResolvedValueOnce(false);
|
||||
|
||||
await expect(shareExportFile('file:///mock-cache/mock-export.json')).rejects.toThrow(
|
||||
'Sharing is not available on this device. The file was saved to app storage.'
|
||||
);
|
||||
expect(Sharing.shareAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -11,23 +11,58 @@ import { Colors } from '../../constants/Colors';
|
||||
import Header from '../../components/navigation/Header';
|
||||
import LoadingSpinner from '../../components/common/LoadingSpinner';
|
||||
import { logger } from '../../utils/logger';
|
||||
import { backupService } from '../../services/backupService';
|
||||
import {
|
||||
requestAndDownloadDataExport,
|
||||
shareExportFile,
|
||||
DataExportTimeoutError,
|
||||
DataExportPhase,
|
||||
} from '../../utils/dataExportFlow';
|
||||
import Icon from 'react-native-vector-icons/MaterialIcons';
|
||||
|
||||
const PHASE_MESSAGES: Record<DataExportPhase, string> = {
|
||||
requesting: 'Requesting your export…',
|
||||
processing: 'Preparing your export… this can take a couple of minutes.',
|
||||
downloading: 'Export ready — downloading…',
|
||||
done: 'Export downloaded. Opening share sheet…',
|
||||
};
|
||||
|
||||
export default function ExportDataScreen() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [statusMessage, setStatusMessage] = useState<string | null>(null);
|
||||
|
||||
const handleExport = async (format: 'json' | 'csv') => {
|
||||
const handleExport = async () => {
|
||||
setLoading(true);
|
||||
setStatusMessage(null);
|
||||
try {
|
||||
await backupService.exportData(format);
|
||||
Alert.alert(
|
||||
'Export Started',
|
||||
`Your data export in ${format.toUpperCase()} format will be ready shortly. You'll receive a notification when it's complete.`
|
||||
);
|
||||
const { fileUri } = await requestAndDownloadDataExport((phase) => {
|
||||
setStatusMessage(PHASE_MESSAGES[phase]);
|
||||
});
|
||||
|
||||
try {
|
||||
await shareExportFile(fileUri);
|
||||
} catch (shareError) {
|
||||
// The export downloaded fine; sharing it is best-effort, so surface
|
||||
// this but don't treat it as a failed export.
|
||||
logger.error('Share export file error:', shareError);
|
||||
Alert.alert(
|
||||
'Export Downloaded',
|
||||
'Your data export was downloaded but could not be opened for sharing. It is saved in app storage.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setStatusMessage('Your data export is ready.');
|
||||
} catch (error) {
|
||||
logger.error('Export data error:', error);
|
||||
Alert.alert('Error', 'Failed to export data. Please try again.');
|
||||
Alert.alert(
|
||||
'Export Failed',
|
||||
error instanceof DataExportTimeoutError
|
||||
? 'Still preparing your export. Please check back in a few minutes.'
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: 'Failed to export data. Please try again.'
|
||||
);
|
||||
setStatusMessage(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@ -38,14 +73,14 @@ export default function ExportDataScreen() {
|
||||
<Header title="Export Data" />
|
||||
<ScrollView style={styles.content}>
|
||||
<Text style={styles.description}>
|
||||
Export a copy of your data including posts, comments, messages, and account information.
|
||||
Export a copy of your data including posts, snippets, collections, messages, and account information.
|
||||
</Text>
|
||||
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionTitle}>Export Format</Text>
|
||||
<TouchableOpacity
|
||||
style={styles.formatOption}
|
||||
onPress={() => handleExport('json')}
|
||||
style={[styles.formatOption, loading && styles.formatOptionDisabled]}
|
||||
onPress={handleExport}
|
||||
disabled={loading}
|
||||
>
|
||||
<Icon name="code" size={24} color={Colors.text} />
|
||||
@ -57,26 +92,17 @@ export default function ExportDataScreen() {
|
||||
</View>
|
||||
<Icon name="chevron-right" size={24} color={Colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
|
||||
<TouchableOpacity
|
||||
style={styles.formatOption}
|
||||
onPress={() => handleExport('csv')}
|
||||
disabled={loading}
|
||||
>
|
||||
<Icon name="table-chart" size={24} color={Colors.text} />
|
||||
<View style={styles.formatInfo}>
|
||||
<Text style={styles.formatLabel}>CSV</Text>
|
||||
<Text style={styles.formatDescription}>
|
||||
Spreadsheet format, easy to view
|
||||
</Text>
|
||||
</View>
|
||||
<Icon name="chevron-right" size={24} color={Colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
{statusMessage && (
|
||||
<View style={styles.statusBanner}>
|
||||
<Text style={styles.statusText}>{statusMessage}</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
<View style={styles.note}>
|
||||
<Text style={styles.noteText}>
|
||||
Note: Large exports may take several minutes to process. You'll receive a notification when your export is ready.
|
||||
Note: Large exports may take a couple of minutes to process. Keep this screen open while your export is prepared, then use the share sheet to save or send the file.
|
||||
</Text>
|
||||
</View>
|
||||
</ScrollView>
|
||||
@ -131,6 +157,19 @@ const styles = StyleSheet.create({
|
||||
fontSize: 14,
|
||||
color: Colors.textSecondary,
|
||||
},
|
||||
formatOptionDisabled: {
|
||||
opacity: 0.6,
|
||||
},
|
||||
statusBanner: {
|
||||
backgroundColor: Colors.surface,
|
||||
borderRadius: 8,
|
||||
padding: 12,
|
||||
marginBottom: 20,
|
||||
},
|
||||
statusText: {
|
||||
fontSize: 14,
|
||||
color: Colors.text,
|
||||
},
|
||||
note: {
|
||||
backgroundColor: Colors.surface,
|
||||
borderRadius: 8,
|
||||
|
||||
@ -38,6 +38,24 @@ jest.mock('expo-constants', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock expo-sharing (used to let the user save/share a downloaded file)
|
||||
jest.mock('expo-sharing', () => ({
|
||||
isAvailableAsync: jest.fn(() => Promise.resolve(true)),
|
||||
shareAsync: jest.fn(() => Promise.resolve()),
|
||||
}));
|
||||
|
||||
// Mock expo-file-system legacy API (used for downloading the GDPR export to
|
||||
// local app storage before handing it to expo-sharing)
|
||||
jest.mock('expo-file-system/legacy', () => ({
|
||||
cacheDirectory: 'file:///mock-cache/',
|
||||
downloadAsync: jest.fn(() =>
|
||||
Promise.resolve({ uri: 'file:///mock-cache/mock-export.json', status: 200 })
|
||||
),
|
||||
getInfoAsync: jest.fn(() => Promise.resolve({ exists: false, isDirectory: false })),
|
||||
readDirectoryAsync: jest.fn(() => Promise.resolve([])),
|
||||
deleteAsync: jest.fn(() => Promise.resolve()),
|
||||
}));
|
||||
|
||||
// Mock expo-notifications
|
||||
jest.mock('expo-notifications', () => ({
|
||||
setNotificationHandler: jest.fn(),
|
||||
|
||||
@ -44,6 +44,7 @@
|
||||
"expo-media-library": "^18.2.0",
|
||||
"expo-notifications": "^0.32.13",
|
||||
"expo-router": "^6.0.15",
|
||||
"expo-sharing": "~14.0.8",
|
||||
"expo-status-bar": "~3.0.8",
|
||||
"expo-video": "^3.0.14",
|
||||
"expo-web-browser": "^15.0.9",
|
||||
|
||||
@ -1,11 +1,50 @@
|
||||
import api from './api';
|
||||
|
||||
export type DataExportStatus = 'processing' | 'ready' | 'expired' | 'failed';
|
||||
|
||||
export interface DataExportRequestResponse {
|
||||
success: boolean;
|
||||
data: {
|
||||
exportId: string;
|
||||
estimatedTime: string;
|
||||
createdAt: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface DataExportStatusResponse {
|
||||
success: boolean;
|
||||
data: {
|
||||
exportId: string;
|
||||
status: DataExportStatus;
|
||||
progress: number;
|
||||
};
|
||||
}
|
||||
|
||||
export const backupService = {
|
||||
/**
|
||||
* @deprecated Hits `/compliance/export-data`, which does not exist on the
|
||||
* backend (always 404s). Use `requestDataExport` + `getDataExportStatus` +
|
||||
* `utils/dataExportFlow.ts`'s `requestAndDownloadDataExport`, which drive the
|
||||
* real GDPR export pipeline at `/api/v1/data-export` (see
|
||||
* backend/src/routes/dataExport.ts). Matches the web fix in commit 842be56e.
|
||||
*/
|
||||
exportData: async (format: 'json' | 'csv') => {
|
||||
const response = await api.post('/compliance/export-data', { format });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
// Data export (GDPR). Backend flow is async: request -> poll status -> download
|
||||
// once ready. See backend/src/routes/dataExport.ts + services/dataExportService.ts.
|
||||
requestDataExport: async (): Promise<DataExportRequestResponse> => {
|
||||
const { data } = await api.post('/data-export/request');
|
||||
return data;
|
||||
},
|
||||
|
||||
getDataExportStatus: async (exportId: string): Promise<DataExportStatusResponse> => {
|
||||
const { data } = await api.get(`/data-export/${exportId}/status`);
|
||||
return data;
|
||||
},
|
||||
|
||||
importData: async (fileUri: string) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', {
|
||||
|
||||
119
gitgram/mobile/utils/dataExportFlow.ts
Normal file
119
gitgram/mobile/utils/dataExportFlow.ts
Normal file
@ -0,0 +1,119 @@
|
||||
import * as FileSystem from 'expo-file-system/legacy';
|
||||
import * as Sharing from 'expo-sharing';
|
||||
import { API_BASE_URL } from '../constants/Config';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { backupService } from '../services/backupService';
|
||||
|
||||
/**
|
||||
* Drives the full GDPR data-export flow against the real backend
|
||||
* (backend/src/routes/dataExport.ts): request -> poll status -> download ->
|
||||
* share/save. Mirrors web/utils/dataExportFlow.ts (fixed in commit 842be56e).
|
||||
*
|
||||
* The backend generates the export asynchronously (2-5 min estimate), so this
|
||||
* polls until the job is 'ready' (or fails/expires), downloads the resulting
|
||||
* file into app storage via expo-file-system, then hands it to expo-sharing
|
||||
* so the user can save or share it. Used by app/backup/export.tsx, which
|
||||
* previously called `backupService.exportData` -> `/compliance/export-data`,
|
||||
* an endpoint that never existed on the backend and always 404'd.
|
||||
*/
|
||||
|
||||
const POLL_INTERVAL_MS = 3000;
|
||||
const MAX_POLL_ATTEMPTS = 60; // ~3 minutes
|
||||
|
||||
export type DataExportPhase = 'requesting' | 'processing' | 'downloading' | 'done';
|
||||
|
||||
export interface DataExportFlowResult {
|
||||
exportId: string;
|
||||
fileUri: string;
|
||||
}
|
||||
|
||||
export class DataExportTimeoutError extends Error {
|
||||
constructor(public exportId: string) {
|
||||
super('Export is taking longer than expected. Check back in a few minutes.');
|
||||
this.name = 'DataExportTimeoutError';
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function getAuthHeader(): Promise<Record<string, string>> {
|
||||
const { accessToken, refreshAccessToken } = useAuthStore.getState();
|
||||
const token = accessToken ?? (await refreshAccessToken());
|
||||
|
||||
if (!token) {
|
||||
throw new Error('You must be signed in to export your data.');
|
||||
}
|
||||
|
||||
return { Authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
async function downloadExportFile(exportId: string): Promise<string> {
|
||||
const headers = await getAuthHeader();
|
||||
const url = `${API_BASE_URL}/data-export/${exportId}/download`;
|
||||
const destUri = `${FileSystem.cacheDirectory}gitgram-data-export-${exportId}.json`;
|
||||
|
||||
const result = await FileSystem.downloadAsync(url, destUri, { headers });
|
||||
|
||||
if (result.status < 200 || result.status >= 300) {
|
||||
throw new Error(`Failed to download export (status ${result.status}).`);
|
||||
}
|
||||
|
||||
return result.uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests a new export, polls until it is ready, and downloads the file to
|
||||
* local app storage. Does not share/save the file — call `shareExportFile`
|
||||
* with the returned `fileUri` to let the user save or share it.
|
||||
*/
|
||||
export async function requestAndDownloadDataExport(
|
||||
onPhaseChange?: (phase: DataExportPhase) => void
|
||||
): Promise<DataExportFlowResult> {
|
||||
onPhaseChange?.('requesting');
|
||||
const requested = await backupService.requestDataExport();
|
||||
const { exportId } = requested.data;
|
||||
|
||||
onPhaseChange?.('processing');
|
||||
for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt += 1) {
|
||||
const statusResult = await backupService.getDataExportStatus(exportId);
|
||||
const { status } = statusResult.data;
|
||||
|
||||
if (status === 'ready') {
|
||||
onPhaseChange?.('downloading');
|
||||
const fileUri = await downloadExportFile(exportId);
|
||||
onPhaseChange?.('done');
|
||||
return { exportId, fileUri };
|
||||
}
|
||||
|
||||
if (status === 'failed') {
|
||||
throw new Error('Data export failed. Please try again.');
|
||||
}
|
||||
|
||||
if (status === 'expired') {
|
||||
throw new Error('Data export expired before it could be downloaded. Please request a new one.');
|
||||
}
|
||||
|
||||
await sleep(POLL_INTERVAL_MS);
|
||||
}
|
||||
|
||||
throw new DataExportTimeoutError(exportId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands the downloaded export file to the OS share sheet so the user can
|
||||
* save it (Files app, Drive, etc.) or share it elsewhere.
|
||||
*/
|
||||
export async function shareExportFile(fileUri: string): Promise<void> {
|
||||
const canShare = await Sharing.isAvailableAsync();
|
||||
|
||||
if (!canShare) {
|
||||
throw new Error('Sharing is not available on this device. The file was saved to app storage.');
|
||||
}
|
||||
|
||||
await Sharing.shareAsync(fileUri, {
|
||||
mimeType: 'application/json',
|
||||
dialogTitle: 'Save or share your data export',
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user