sync profile api

This commit is contained in:
2025-07-03 22:36:28 +05:00
parent b56a96f0ff
commit 77e3ca0f18
4 changed files with 498 additions and 30 deletions

View File

@@ -0,0 +1,82 @@
import authService from './authService';
class ApiService {
// Profile methods
async getProfile() {
return authService.getProfile();
}
async updateProfile(data) {
return authService.updateProfile(data);
}
async changePassword(currentPassword, newPassword) {
return authService.changePassword(currentPassword, newPassword);
}
async deleteAccount() {
return authService.deleteAccount();
}
// Balance and transactions
async getBalance() {
return authService.getBalance();
}
async getTransactions(page = 1, limit = 20) {
return authService.getTransactions(page, limit);
}
// Transfer and payments
async transferMoney(data) {
return authService.transferMoney(data);
}
async payBill(data) {
return authService.payBill(data);
}
// Cards management
async getCards() {
return authService.getCards();
}
async addCard(data) {
return authService.addCard(data);
}
async blockCard(cardId) {
return authService.blockCard(cardId);
}
async unblockCard(cardId) {
return authService.unblockCard(cardId);
}
// Utility methods for common operations
async getUserDashboardData() {
try {
const [balance, transactions, cards] = await Promise.all([
this.getBalance().catch(() => ({ balance: 0 })),
this.getTransactions(1, 5).catch(() => ({ transactions: [] })),
this.getCards().catch(() => ({ cards: [] }))
]);
return {
success: true,
data: {
balance: balance.balance || 0,
recentTransactions: transactions.transactions || [],
cards: cards.cards || []
}
};
} catch (error) {
return {
success: false,
error: error.message
};
}
}
}
export default new ApiService();

View File

@@ -1,30 +1,87 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
import { API_CONFIG } from '../constants/api';
class AuthService {
async makeRequest(endpoint, data, token = null) {
async getStoredToken() {
try {
return await AsyncStorage.getItem('auth_token');
} catch (error) {
return null;
}
}
async makeRequest(endpoint, data, requiresAuth = false, method = 'POST') {
const fullUrl = `${API_CONFIG.BASE_URL}${endpoint}`;
const requestId = Math.random().toString(36).substr(2, 9);
try {
const headers = {
...API_CONFIG.HEADERS,
};
if (token) {
headers.Authorization = `Bearer ${token}`;
// Auto-include token for authenticated requests
if (requiresAuth) {
const token = await this.getStoredToken();
if (token) {
headers.Authorization = `Bearer ${token}`;
}
}
const response = await fetch(`${API_CONFIG.BASE_URL}${endpoint}`, {
method: 'POST',
headers,
body: JSON.stringify(data),
// Log request details
console.log(`\n🚀 [${requestId}] API REQUEST`);
console.log(`📍 URL: ${method} ${fullUrl}`);
console.log(`🔐 Auth Required: ${requiresAuth}`);
console.log(`📝 Headers:`, {
...headers,
Authorization: headers.Authorization ? `Bearer ${headers.Authorization.slice(-10)}...` : 'None'
});
if (data) {
console.log(`📦 Body:`, data);
}
console.log(`⏰ Time: ${new Date().toISOString()}`);
const startTime = Date.now();
const response = await fetch(fullUrl, {
method,
headers,
body: data ? JSON.stringify(data) : undefined,
});
const endTime = Date.now();
const duration = endTime - startTime;
const result = await response.json();
// Log response details
console.log(`\n✅ [${requestId}] API RESPONSE`);
console.log(`📊 Status: ${response.status} ${response.statusText}`);
console.log(`⏱️ Duration: ${duration}ms`);
console.log(`📄 Response:`, result);
if (!response.ok) {
console.log(`❌ [${requestId}] API ERROR`);
console.log(`🔴 Status: ${response.status}`);
console.log(`💬 Error Message:`, result.message || 'Unknown error');
// Handle token expiration
if (response.status === 401 && requiresAuth) {
console.log(`🔓 [${requestId}] TOKEN EXPIRED - Clearing storage`);
await AsyncStorage.removeItem('auth_token');
await AsyncStorage.removeItem('user_data');
throw new Error('Session expired. Please login again.');
}
throw new Error(result.message || 'An error occurred');
}
console.log(`✨ [${requestId}] REQUEST COMPLETED SUCCESSFULLY\n`);
return result;
} catch (error) {
console.log(`\n💥 [${requestId}] API REQUEST FAILED`);
console.log(`📍 URL: ${method} ${fullUrl}`);
console.log(`🔴 Error:`, error.message);
console.log(`📅 Time: ${new Date().toISOString()}\n`);
throw new Error(error.message || 'Network error');
}
}
@@ -50,6 +107,58 @@ class AuthService {
code: parseInt(code),
});
}
// Authenticated API methods
async getProfile() {
return this.makeRequest('/profile', null, true, 'GET');
}
async updateProfile(data) {
return this.makeRequest('/profile', data, true, 'PUT');
}
async getTransactions(page = 1, limit = 20) {
return this.makeRequest(`/user/transactions?page=${page}&limit=${limit}`, null, true, 'GET');
}
async getBalance() {
return this.makeRequest('/user/balance', null, true, 'GET');
}
async transferMoney(data) {
return this.makeRequest('/user/transfer', data, true);
}
async payBill(data) {
return this.makeRequest('/user/pay-bill', data, true);
}
async getCards() {
return this.makeRequest('/user/cards', null, true, 'GET');
}
async addCard(data) {
return this.makeRequest('/user/cards', data, true);
}
async blockCard(cardId) {
return this.makeRequest(`/user/cards/${cardId}/block`, null, true);
}
async unblockCard(cardId) {
return this.makeRequest(`/user/cards/${cardId}/unblock`, null, true);
}
async changePassword(currentPassword, newPassword) {
return this.makeRequest('/user/change-password', {
current_password: currentPassword,
new_password: newPassword,
}, true);
}
async deleteAccount() {
return this.makeRequest('/user/delete-account', null, true, 'DELETE');
}
}
export default new AuthService();