{"size": 1094, "ext": "js", "max_stars_repo_path": "src/lib/realtime.js", "max_stars_repo_name": "cozy/cozy-bar", "max_stars_repo_stars_event_min_datetime": "2017-07-10T14:52:40.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-16T13:13:38.000Z", "max_issues_repo_path": "src/lib/realtime.js", "max_issues_repo_name": "cozy/cozy-bar", "max_issues_repo_issues_event_min_datetime": "2017-01-23T11:37:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T13:11:01.000Z", "max_forks_repo_path": "src/lib/realtime.js", "max_forks_repo_name": "cozy/cozy-bar", "max_forks_repo_forks_event_min_datetime": "2017-01-19T21:11:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-15T08:50:59.000Z"}
{"max_stars_count": 6, "max_issues_count": 605, "max_forks_count": 17, "avg_line_length": 24.8636363636, "max_line_length": 76, "alphanum_fraction": 0.6617915905}
import CozyRealtime from 'cozy-realtime'

const APPS_DOCTYPE = 'io.cozy.apps'

/**
 * Initialize realtime sockets
 *
 * @private
 * @param {object}
 * @returns {Promise}
 */
function initializeRealtime({ getApp, onCreate, onDelete, cozyClient }) {
  const handleAppCreation = async app => {
    // Fetch directly the app to get attributes `related` as well.
    let fullApp
    try {
      fullApp = await getApp(app.slug)
    } catch (error) {
      throw new Error(`Cannot fetch app ${app.slug}: ${error.message}`)
    }

    if (typeof onCreate === 'function') {
      onCreate(fullApp)
    }
  }

  const handleAppRemoval = app => {
    if (typeof onDelete === 'function') {
      onDelete(app)
    }
  }

  try {
    const realtime = new CozyRealtime({ client: cozyClient })
    realtime.subscribe('created', APPS_DOCTYPE, handleAppCreation)
    realtime.subscribe('deleted', APPS_DOCTYPE, handleAppRemoval)
  } catch (error) {
    // eslint-disable-next-line no-console
    console.warn(`Cannot initialize realtime in Cozy-bar: ${error.message}`)
  }
}

export default initializeRealtime
