{"size": 1954, "ext": "js", "max_stars_repo_path": "src/handlers/account/createAccount.js", "max_stars_repo_name": "ajsutton/moolah-server", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/handlers/account/createAccount.js", "max_issues_repo_name": "ajsutton/moolah-server", "max_issues_repo_issues_event_min_datetime": "2018-10-16T21:27:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-14T09:13:42.000Z", "max_forks_repo_path": "src/handlers/account/createAccount.js", "max_forks_repo_name": "ajsutton/moolah-server", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 4, "max_forks_count": null, "avg_line_length": 37.5769230769, "max_line_length": 101, "alphanum_fraction": 0.4544524053}
const Joi = require('joi');
const types = require('../types');
const db = require('../../db/database');
const idGenerator = require('../../utils/idGenerator');
const session = require('../../auth/session');

module.exports = {
    auth: 'session',
    handler: async function(request, h) {
        while (true) {
            try {
                const account = Object.assign({id: idGenerator()}, request.payload, {hidden: false});
                const userId = session.getUserId(request);
                await db.withTransaction(request, async daos => {
                    await daos.accounts.create(userId,
                        {
                            id: account.id,
                            name: account.name,
                            type: account.type,
                        });
                    await daos.transactions.create(userId,
                        {
                            id: account.id,
                            accountId: account.id,
                            type: 'openingBalance',
                            date: account.date !== null ? account.date : new Date(),
                            amount: account.balance,
                        });
                });
                delete account.date;
                return h.response(account).created(`/accounts/${encodeURIComponent(account.id)}/`);
            } catch (error) {
                if (error.code !== 'ER_DUP_ENTRY') {
                    throw error;
                }
            }
        }
    },
    validate: {
        payload: Joi.object({
            name: types.name.required(),
            type: types.accountType.required(),
            balance: types.money.required(),
            position: types.position,
            date: types.date.default(null),
        }),
        headers: Joi.object({
            'Content-Type': types.jsonContentType,
        }).unknown(true),
        failAction: types.failAction
    },
};