{"size": 960, "ext": "js", "max_stars_repo_path": "src/server/services/chatService/createDirectMessage.js", "max_stars_repo_name": "eastnorthwest/echo", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/server/services/chatService/createDirectMessage.js", "max_issues_repo_name": "eastnorthwest/echo", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/server/services/chatService/createDirectMessage.js", "max_forks_repo_name": "eastnorthwest/echo", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.2631578947, "max_line_length": 86, "alphanum_fraction": 0.671875}
import {apiFetch} from './util'
import {getUserId} from './cache'

export default async function createDirectMessage(handleOrHandles, text) {
  const handles = Array.isArray(handleOrHandles) ? handleOrHandles : [handleOrHandles]
  const userIds = await Promise.all(handles.map(handle => getUserId(handle)))
  const channel = userIds.length > 1 ?
    (await _openMultiPartyDirectMessage(userIds)).group.id :
    (await _openDirectMessage(userIds[0])).channel.id

  const result = await apiFetch('/api/chat.postMessage', {
    method: 'POST',
    body: {
      channel,
      text,
      as_user: true, // eslint-disable-line camelcase
    },
  })

  return result.ok
}

function _openDirectMessage(userId) {
  return apiFetch('/api/im.open', {
    method: 'POST',
    body: {user: userId},
  })
}

function _openMultiPartyDirectMessage(userIds) {
  return apiFetch('/api/mpim.open', {
    method: 'POST',
    body: {
      users: userIds.join(',')
    }
  })
}
