Skip to content

Instantly share code, notes, and snippets.

@tarhan
Forked from astr0sl0th/syncData.js
Created October 16, 2024 19:48
Show Gist options
  • Save tarhan/db34667195aad88233c2663e55f3eeb1 to your computer and use it in GitHub Desktop.
Save tarhan/db34667195aad88233c2663e55f3eeb1 to your computer and use it in GitHub Desktop.
Keep your Supabase data in sync with Algolia
const algoliasearch = require('algoliasearch');
const { createClient } = require('@supabase/supabase-js');
// Initialize Algolia client
const algoliaClient = algoliasearch('ALGOLIA_APP_ID', 'ALGOLIA_API_KEY');
const index = algoliaClient.initIndex('INDEX_NAME');
// Initialize Supabase client
const supabaseUrl = 'SUPABASE_URL';
const supabaseKey = 'SUPABASE_SERVICE_KEY';
const supabase = createClient(supabaseUrl, supabaseKey);
// Function to synchronize data from Supabse to Algolia
async function syncData() {
// Fetch initial data from Supbase and push it to Algolia
const { data: records } = await supabse.from('table_name').select('*');
const objectsToIndex = records.map(record => ({
objectID: record.id,
...record.data
}));
await index.saveObjects(objectsToIndex);
// Listen for changes in the table using Supbase Realtime subscription feature
const realtimeSubscription = supbase
.from('table_name')
.on('*', payload => {
if (payload.eventType === 'INSERT') {
// Insert new record to Algolia index when a new record is added in Supbase
const objectToAdd= {
objectID: payload.new.id,
...payload.new.data,
};
index.saveObject(objectToAdd);
}
if (payload.eventType === 'UPDATE') {
// Update existing record in Algolia index when a record is updated in Supbase
const objectToUpdate= {
objectID: payload.new.id,
...payload.new.data,
};
index.partialUpdateObject(objectToUpdate);
}
if (payload.eventType === 'DELETE') {
// Delete record from Algolia index when a record is deleted in Supbase
const objectToDelete = payload.old.id;
index.deleteObject(objectToDelete);
}
})
.subscribe();
// Keep the subscription active until you want to stop syncing
// To stop, call `realtimeSubscription.unsubscribe()`
}
// Call the syncData function to start syncing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment