127.0.0.1:8000 budget / master server / routes / api / account / linked_accounts.js
master

Tree @master (Download .tar.gz)

linked_accounts.js @masterraw · history · blame

const utils = require('../../../utils');

const available_accounts = [
    require('../../../external_apis/gmail/gmail_api')
].reduce(function (acc, available_account) {
    return {
        ...acc,
        [available_account.name]: available_account
    }
}, {});

async function get_linked_accounts(user_id) {
    const linked_accounts = {};
    await Promise.allSettled(Object.entries(available_accounts).map(async function ([linked_account_name, available_accounts]) {
        const linked_account = await available_accounts.get_status(user_id);
        if (linked_account.linked_account_username) {
            linked_accounts[linked_account_name] = linked_account
        }
    }));
    return linked_accounts;
}

module.exports = {
    get: {
        "": async function (req, res) {
            const linked_accounts = await get_linked_accounts(req.user.user_id);
            res.send(utils.ok({
                linked_accounts
            }));
        },
        "available": async function (req, res) {
            const remaining_available_accounts = [];
            const linked_accounts = await get_linked_accounts(req.user.user_id);
            for (const available_account_name of Object.keys(available_accounts)) {
                if (!linked_accounts[available_account_name]) {
                    remaining_available_accounts.push(available_account_name);
                }
            }
            res.send(utils.ok({
                available_accounts: remaining_available_accounts
            }));
        }
    },
    post: {
        "refresh": async function (req, res) {
            const linked_accounts = await get_linked_accounts(req.user.user_id);
            Promise.allSettled(Object.keys(linked_accounts).map(async function (linked_account_name) {
                await available_accounts[linked_account_name].populate_all_new_transactions(req.user.user_id);
            })).then(function () {
                res.send(utils.ok());
            }).catch(function (errors) {
                utils.handle_err.res(res, `Failed to refresh data from linked accounts: ${errors.join(',')}`);
            });
        },
        "link": async function (req, res) {
            await available_accounts[req.body.linked_account_name].link(req.user.user_id);
            res.send(utils.ok());
        }
    },
    delete: {
        "unlink/:linked_account_name": async function (req, res) {
            await available_accounts[req.params.linked_account_name].unlink(req.user.user_id);
            res.send(utils.ok());
        }
    }
};