horizon/resources/messages.js

import { ResourceGroupBase } from '../../resource_group_base'
import { SUBMIT_TRANSACTION_TIMEOUT } from '../constants'
import { safeAccountId } from '../../utils/safe_account_id'

/**
 * Messages.
 *
 * @class
 */
export class Messages extends ResourceGroupBase {
  /**
   * Get messages.
   *
   * @param {object} [query] Request options.
   * @param {Number} [query.page.number] Page number.
   * @param {Number} [query.page.size] Page size.
   * @param {string[]} [query.sort] Sorting params.
   * @param {string} query.sender Account id of the sender.
   * @param {Number} query.lotId ID of the lot.
   * @param {string} query.search Full text search.
   * @return {JsonApiResponse}
   */
  getPage (query) {
    return this
      ._makeCallBuilder()
      .get(query)
  }

  /**
   * Get unread messages counter.
   *
   * @param {object} [query] Request options.
   * @param {string} query.sender Account id of the sender.
   * @param {Number} query.lotId ID of the lot.
   * @return {JsonApiResponse}
   */
  getUnreadCounter (query) {
    return this
      ._makeCallBuilder()
      .appendUrlSegment('unread')
      .get(query)
  }

  /**
   * Get dialogs list.
   *
   * @param {object} [query] Request options.
   * @param {string} query.with Account id of dialog companion.
   * @param {Number} query.lotId ID of the lot.
   * @return {JsonApiResponse}
   */
  getDialogs (query) {
    return this
      ._makeCallBuilder()
      .appendUrlSegment('dialogs')
      .get(query)
  }

  /**
   * Mark messages as read.
   *
   * @param {object} opts Account options.
   * @param {string} [opts.sender] Account ID of the sender.
   * @param {Number} [opts.lotId] ID of the lot.
   * @param {Number} [opts.receiver] ID of the lot.
   */
  markRead (opts) {
    return this
      ._makeCallBuilder()
      .patch({
        data: {
          attributes: opts
        }
      })
  }

  /**
   * Send a message.
   *
   * @param {object} opts Message options.
   * @param {string} opts.receiver Message receiver.
   * @param {string} opts.lotId Lot ID.
   * @param {string} opts.text Message text.
   * @param {string} [opts.sender] Message sender.
   *
   * @return {Promise.<JsonApiResponse>}
   */
  send (opts) {
    opts.sender = safeAccountId(opts.sender, this._sdk)

    return this._makeCallBuilder()
      .withTimeout(SUBMIT_TRANSACTION_TIMEOUT)
      .post({
        data: {
          type: 'messages',
          attributes: opts
        }
      })
  }

  _makeCallBuilder () {
    return this._server
      ._makeCallBuilder()
      .withCredentials()
      .appendUrlSegment('messages')
  }
}