const { log, updateOrCreate } = require('cozy-konnector-libs') const { isLocal } = require('../helpers/env') const cozyClient = require('cozy-konnector-libs/dist/libs/cozyclient') async function saveAccountData(accountId, accountData) { log('info', `saveAccountData: ${accountId}`) let account = await getAccount(accountId) log('info', `saveAccountData account: ${JSON.stringify(account)}`) log( 'info', `saveAccountData account: ${JSON.stringify({ ...account, data: accountData, })}` ) const id = account._id log( 'info', `saveAccountData account after id: ${JSON.stringify({ ...account, data: accountData, })}` ) account = await updateOrCreate( [{ ...account, data: accountData }], 'io.cozy.accounts', [], { sourceAccount: id } ) log('info', `saveAccountData account reply: ${JSON.stringify(account)}`) return account } /** * Return account * @param {string} accountId * @returns {Account} */ async function getAccount(accountId) { log('info', `getAccount: ${accountId}`) const accounts = await cozyClient.data.findAll('io.cozy.accounts') log('info', `getAccount data: ${JSON.stringify(accounts)}`) return accounts.filter(account => isLocal() ? account._id === accountId : account.account_type === accountId )[0] } async function getAccountForDelete(accountId, accountRev) { log('info', `getAccountForDelete: ${accountId} ${accountRev}`) const body = await cozyClient.fetchJSON( 'GET', `/data/io.cozy.accounts/${accountId}?rev=${accountRev}` ) log('debug', `getAccountForDelete: ${body}`) return body } module.exports = { getAccount, saveAccountData, getAccountForDelete }