-
Notifications
You must be signed in to change notification settings - Fork 226
/
update_transactions.js
102 lines (90 loc) · 2.69 KB
/
update_transactions.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* @file Defines helpers for updating transactions on an item
*/
const plaid = require('./plaid');
const {
retrieveItemByPlaidItemId,
createAccounts,
createOrUpdateTransactions,
deleteTransactions,
updateItemTransactionsCursor,
} = require('./db/queries');
/**
* Fetches transactions from the Plaid API for a given item.
*
* @param {string} plaidItemId the Plaid ID for the item.
* @returns {Object{}} an object containing transactions and a cursor.
*/
const fetchTransactionUpdates = async (plaidItemId) => {
// the transactions endpoint is paginated, so we may need to hit it multiple times to
// retrieve all available transactions.
// get the access token based on the plaid item id
const {
plaid_access_token: accessToken,
transactions_cursor: lastCursor,
} = await retrieveItemByPlaidItemId(
plaidItemId
);
let cursor = lastCursor;
// New transaction updates since "cursor"
let added = [];
let modified = [];
// Removed transaction ids
let removed = [];
let hasMore = true;
const batchSize = 100;
try {
// Iterate through each page of new transaction updates for item
/* eslint-disable no-await-in-loop */
while (hasMore) {
const request = {
access_token: accessToken,
cursor: cursor,
count: batchSize,
};
const response = await plaid.transactionsSync(request)
const data = response.data;
// Add this page of results
added = added.concat(data.added);
modified = modified.concat(data.modified);
removed = removed.concat(data.removed);
hasMore = data.has_more;
// Update cursor to the next cursor
cursor = data.next_cursor;
}
} catch (err) {
console.error(`Error fetching transactions: ${err.message}`);
cursor = lastCursor;
}
return { added, modified, removed, cursor, accessToken };
};
/**
* Handles the fetching and storing of new, modified, or removed transactions
*
* @param {string} plaidItemId the Plaid ID for the item.
*/
const updateTransactions = async (plaidItemId) => {
// Fetch new transactions from plaid api.
const {
added,
modified,
removed,
cursor,
accessToken
} = await fetchTransactionUpdates(plaidItemId);
const request = {
access_token: accessToken,
};
const {data: {accounts}} = await plaid.accountsGet(request);
// Update the DB.
await createAccounts(plaidItemId, accounts);
await createOrUpdateTransactions(added.concat(modified));
await deleteTransactions(removed);
await updateItemTransactionsCursor(plaidItemId, cursor);
return {
addedCount: added.length,
modifiedCount: modified.length,
removedCount: removed.length,
};
};
module.exports = updateTransactions;