Hey there, fellow JavaScript dev! Ready to supercharge your OneDrive integration with webhooks? Let's dive right in and get those real-time notifications flowing!
Webhooks are like your app's personal news feed for OneDrive events. They'll ping you whenever something interesting happens, saving you from constantly polling the API. Trust me, your servers (and your users) will thank you.
Before we jump into the code, make sure you've got:
axios
and express
installed (npm install axios express
)Got all that? Great! Let's get our hands dirty.
First things first, we need a URL for OneDrive to hit when it's got news for us. Here's a quick Express server to handle that:
const express = require('express'); const app = express(); app.post('/webhook', express.json(), (req, res) => { // We'll fill this in soon! res.sendStatus(202); }); app.listen(3000, () => console.log('Webhook server running on port 3000'));
Now, let's tell OneDrive we're all ears:
const axios = require('axios'); async function createSubscription() { try { const response = await axios.post('https://graph.microsoft.com/v1.0/subscriptions', { changeType: 'created,updated', notificationUrl: 'https://your-app.com/webhook', resource: '/me/drive/root', expirationDateTime: new Date(Date.now() + 4230 * 60000).toISOString(), clientState: 'secretClientState' }, { headers: { 'Authorization': 'Bearer YOUR_ACCESS_TOKEN' } }); console.log('Subscription created:', response.data); } catch (error) { console.error('Error creating subscription:', error.response.data); } } createSubscription();
OneDrive's gonna make sure you're you before spilling the beans. Here's how to handle that validation request:
app.post('/webhook', express.json(), (req, res) => { if (req.query && req.query.validationToken) { res.set('Content-Type', 'text/plain'); res.send(req.query.validationToken); } else { // Handle actual notifications here res.sendStatus(202); } });
When the real notifications start rolling in, you'll want to parse them like this:
app.post('/webhook', express.json(), (req, res) => { if (req.query && req.query.validationToken) { // Validation handling (as above) } else { const notifications = req.body.value; notifications.forEach(notification => { console.log('Change type:', notification.changeType); console.log('Resource:', notification.resource); // Do something awesome with this info! }); res.sendStatus(202); } });
Subscriptions don't last forever, so let's keep them fresh:
async function renewSubscription(subscriptionId) { try { const response = await axios.patch(`https://graph.microsoft.com/v1.0/subscriptions/${subscriptionId}`, { expirationDateTime: new Date(Date.now() + 4230 * 60000).toISOString() }, { headers: { 'Authorization': 'Bearer YOUR_ACCESS_TOKEN' } }); console.log('Subscription renewed:', response.data); } catch (error) { console.error('Error renewing subscription:', error.response.data); } }
Need to make changes or say goodbye? Here's how:
// Update a subscription async function updateSubscription(subscriptionId, newResource) { // Similar to renewSubscription, but include the new resource } // Delete a subscription async function deleteSubscription(subscriptionId) { try { await axios.delete(`https://graph.microsoft.com/v1.0/subscriptions/${subscriptionId}`, { headers: { 'Authorization': 'Bearer YOUR_ACCESS_TOKEN' } }); console.log('Subscription deleted'); } catch (error) { console.error('Error deleting subscription:', error.response.data); } }
Always expect the unexpected! Here's a quick error handling snippet to get you started:
app.use((err, req, res, next) => { console.error('Error:', err.message); res.status(500).send('Something went wrong!'); });
And remember:
And there you have it! You're now armed with the knowledge to implement webhooks in your OneDrive integration. Remember, webhooks are powerful tools, so use them wisely and your app will be more responsive than ever.
Want to dive deeper? Check out these resources:
Now go forth and webhook like a pro! Happy coding! 🚀