-
Notifications
You must be signed in to change notification settings - Fork 225
/
handleTransactionsWebhook.js
55 lines (49 loc) · 1.73 KB
/
handleTransactionsWebhook.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* @file Defines the handler for Transactions webhooks.
* https://plaid.com/docs/#transactions-webhooks
*/
const {
retrieveItemByPlaidItemId,
} = require('../db/queries');
const updateTransactions = require('../update_transactions');
/**
* Handles all transaction webhook events. The transaction webhook notifies
* you that a single item has new transactions available.
*
* @param {Object} requestBody the request body of an incoming webhook event
* @param {Object} io a socket.io server instance.
*/
const handleTransactionsWebhook = async (requestBody, io) => {
const {
webhook_code: webhookCode,
item_id: plaidItemId,
} = requestBody;
const serverLogAndEmitSocket = (additionalInfo, itemId) => {
console.log(
`WEBHOOK: TRANSACTIONS: ${webhookCode}: Plaid_item_id ${plaidItemId}: ${additionalInfo}`
);
// use websocket to notify the client that a webhook has been received and handled
if (webhookCode) io.emit(webhookCode, { itemId });
};
switch (webhookCode) {
case 'SYNC_UPDATES_AVAILABLE': {
// Fired when new transactions data becomes available.
const {
addedCount,
modifiedCount,
removedCount,
} = await updateTransactions(plaidItemId);
const { id: itemId } = await retrieveItemByPlaidItemId(plaidItemId);
serverLogAndEmitSocket(`Transactions: ${addedCount} added, ${modifiedCount} modified, ${removedCount} removed`, itemId);
break;
}
case 'DEFAULT_UPDATE':
case 'INITIAL_UPDATE':
case 'HISTORICAL_UPDATE':
/* ignore - not needed if using sync endpoint + webhook */
break;
default:
serverLogAndEmitSocket(`unhandled webhook type received.`, plaidItemId);
}
};
module.exports = handleTransactionsWebhook;