Skip to content
Snippets Groups Projects
cozy.js 1.67 KiB
Newer Older
  • Learn to ignore specific revisions
  • 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)
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      log('info', `saveAccountData account: ${JSON.stringify(account)}`)
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      log(
        'info',
        `saveAccountData account: ${JSON.stringify({
          ...account,
          data: accountData,
        })}`
      )
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      const id = account._id
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      log(
        'info',
        `saveAccountData account after id: ${JSON.stringify({
          ...account,
          data: accountData,
        })}`
      )
    
      account = await updateOrCreate(
        [{ ...account, data: accountData }],
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
        'io.cozy.accounts',
        null,
        { sourceAccount: id }
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      log('info', `saveAccountData account reply: ${JSON.stringify(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')
    
    Hugo SUBTIL's avatar
    Hugo SUBTIL committed
      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 }