-
Notifications
You must be signed in to change notification settings - Fork 1
/
handleItemWebhook.js
88 lines (82 loc) · 2.44 KB
/
handleItemWebhook.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* @file Defines the handler for Item webhooks.
* https://plaid.com/docs/#item-webhooks
*/
const {
updateItemStatus,
retrieveItemByPlaidItemId,
} = require('../db/queries');
/**
* Handles Item errors received from item webhooks. When an error is received
* different operations are needed to update an item based on the the error_code
* that is encountered.
*
* @param {string} plaidItemId the Plaid ID of an item.
* @param {Object} error the error received from the webhook.
*/
const itemErrorHandler = async (plaidItemId, error) => {
const { error_code: errorCode } = error;
switch (errorCode) {
case 'ITEM_LOGIN_REQUIRED': {
const { id: itemId } = await retrieveItemByPlaidItemId(plaidItemId);
await updateItemStatus(itemId, 'bad');
break;
}
default:
console.log(
`WEBHOOK: ITEMS: Plaid item id ${plaidItemId}: unhandled ITEM error`
);
}
};
/**
* Handles all Item webhook events.
*
* @param {Object} requestBody the request body of an incoming webhook event.
* @param {Object} io a socket.io server instance.
*/
const itemsHandler = async (requestBody, io) => {
const {
webhook_code: webhookCode,
item_id: plaidItemId,
error,
} = requestBody;
const serverLogAndEmitSocket = (additionalInfo, itemId, errorCode) => {
console.log(
`WEBHOOK: ITEMS: ${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, errorCode });
};
switch (webhookCode) {
case 'WEBHOOK_UPDATE_ACKNOWLEDGED':
serverLogAndEmitSocket('is updated', plaidItemId, error);
break;
case 'ERROR': {
itemErrorHandler(plaidItemId, error);
const { id: itemId } = await retrieveItemByPlaidItemId(plaidItemId);
serverLogAndEmitSocket(
`ERROR: ${error.error_code}: ${error.error_message}`,
itemId,
error.error_code
);
break;
}
case 'PENDING_EXPIRATION': {
const { id: itemId } = await retrieveItemByPlaidItemId(plaidItemId);
await updateItemStatus(itemId, 'bad');
serverLogAndEmitSocket(
`user needs to re-enter login credentials`,
itemId,
error
);
break;
}
default:
serverLogAndEmitSocket(
'unhandled webhook type received.',
plaidItemId,
error
);
}
};
module.exports = itemsHandler;