Hey there, fellow JavaScript devs! Ready to dive into the world of Uber API integration? Let's get our hands dirty with some code and learn how to sync data for a slick user-facing integration. Buckle up!
First things first, let's get you set up with the Uber API. Head over to the Uber Developer Portal, grab your API credentials, and install the necessary dependencies:
npm install uber-api axios
Now, let's kick things off with a quick setup:
const axios = require('axios'); const UberAPI = require('uber-api'); const uber = new UberAPI({ client_id: 'YOUR_CLIENT_ID', client_secret: 'YOUR_CLIENT_SECRET', server_token: 'YOUR_SERVER_TOKEN', redirect_uri: 'YOUR_REDIRECT_URI', name: 'YOUR_APP_NAME' });
Time to fetch some data! Let's start with grabbing user profile info and ride history:
async function getUserProfile(accessToken) { try { const response = await axios.get('https://api.uber.com/v1.2/me', { headers: { 'Authorization': `Bearer ${accessToken}` } }); return response.data; } catch (error) { console.error('Error fetching user profile:', error); } } async function getRideHistory(accessToken) { try { const response = await axios.get('https://api.uber.com/v1.2/history', { headers: { 'Authorization': `Bearer ${accessToken}` } }); return response.data.history; } catch (error) { console.error('Error fetching ride history:', error); } }
Now, let's write some data back to Uber. Here's how you can create a ride request and update user preferences:
async function createRideRequest(accessToken, rideData) { try { const response = await axios.post('https://api.uber.com/v1.2/requests', rideData, { headers: { 'Authorization': `Bearer ${accessToken}` } }); return response.data; } catch (error) { console.error('Error creating ride request:', error); } } async function updateUserPreferences(accessToken, preferences) { try { const response = await axios.put('https://api.uber.com/v1.2/preferences', preferences, { headers: { 'Authorization': `Bearer ${accessToken}` } }); return response.data; } catch (error) { console.error('Error updating user preferences:', error); } }
Let's create a sync function that keeps your local data up-to-date with Uber's:
async function syncUserData(accessToken) { try { const profile = await getUserProfile(accessToken); const rideHistory = await getRideHistory(accessToken); // Update local storage or database with fetched data updateLocalStorage({ profile, rideHistory }); console.log('Data sync completed successfully'); } catch (error) { console.error('Error during data sync:', error); // Implement retry logic here } } // Run sync every 5 minutes setInterval(() => syncUserData(userAccessToken), 5 * 60 * 1000);
To keep things snappy, let's implement some caching and parallel requests:
const cache = new Map(); async function getCachedData(key, fetchFunction) { if (cache.has(key)) { return cache.get(key); } const data = await fetchFunction(); cache.set(key, data); return data; } async function syncUserDataOptimized(accessToken) { try { const [profile, rideHistory] = await Promise.all([ getCachedData('profile', () => getUserProfile(accessToken)), getCachedData('rideHistory', () => getRideHistory(accessToken)) ]); updateLocalStorage({ profile, rideHistory }); console.log('Optimized data sync completed successfully'); } catch (error) { console.error('Error during optimized data sync:', error); } }
When dealing with potential conflicts, implement a simple resolution strategy:
function resolveConflict(localData, remoteData) { return remoteData.updated_at > localData.updated_at ? remoteData : localData; } async function syncWithConflictResolution(accessToken) { const localData = getLocalData(); const remoteData = await fetchRemoteData(accessToken); const resolvedData = resolveConflict(localData, remoteData); updateLocalStorage(resolvedData); }
Always keep security in mind. Here's a quick tip for storing API credentials:
const crypto = require('crypto'); function encryptCredentials(credentials, secretKey) { const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv('aes-256-cbc', secretKey, iv); let encrypted = cipher.update(JSON.stringify(credentials), 'utf8', 'hex'); encrypted += cipher.final('hex'); return { iv: iv.toString('hex'), encryptedData: encrypted }; } // Use environment variables for the secret key const secretKey = process.env.SECRET_KEY; const encryptedCreds = encryptCredentials(uberCredentials, secretKey);
Don't forget to test your integration thoroughly. Here's a simple unit test example using Jest:
jest.mock('axios'); test('getUserProfile fetches user data correctly', async () => { const mockUserData = { name: 'Test User', email: '[email protected]' }; axios.get.mockResolvedValue({ data: mockUserData }); const result = await getUserProfile('fake_access_token'); expect(result).toEqual(mockUserData); expect(axios.get).toHaveBeenCalledWith('https://api.uber.com/v1.2/me', expect.objectContaining({ headers: { 'Authorization': 'Bearer fake_access_token' } }) ); });
And there you have it! You're now equipped to read and write data like a pro using the Uber API. Remember to always respect rate limits, handle errors gracefully, and keep your users' data secure.
Happy coding, and may your integrations be ever smooth and your API calls always successful! 🚗💨