notifications/server.js

import { JsonApiServer } from '../json_api'
import { notificationTypes } from './constants'

/**
 * Facilitates interaction with the Notifications server.
 *
 * @class
 */
export class NotificationServer extends JsonApiServer {
  /**
   * Create a new Notifications server instance.
   *
   * @constructor
   * @param {ShelfNetwork} sdk Parent SDK instance.
   * @param {string} serverUrl Notifications URL.
   * @param {Object} opts
   * @param {boolean} [opts.allowHttp] Allow connecting to http servers, default: `false`. This must be set to false in production deployments!
   * @param {Object} [opts.proxy] Proxy configuration. Look [axios docs](https://github.com/axios/axios#request-config) for more info
   * @param {Object} [opts.httpBasicAuth] HTTP basic auth credentials. Look [axios docs](https://github.com/axios/axios#request-config) for more info.
   * @param {Object} [opts.customHeaders] Custom headers for request.
   * @param {boolean} [opts.withCredentials] Indicates whether or not cross-site Access-Control requests should be made using credentials.
   * @param {string} [opts.responseType='json'] Indicates the type of data that the server will respond with options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'.
   */
  constructor (sdk, serverUrl, opts = {}) {
    opts.alias = 'notification_hub'
    super(sdk, serverUrl, opts)
  }

  /**
   * Available notification types.
   *
   * @type {NotificationTypes}
   */
  get types () {
    return notificationTypes
  }

  /**
   * Get all notifications.
   *
   * @param {object} [opts] Request options.
   * @param {string} [opts.sort] Sort mode.
   *
   * @return {Promise<JsonApiResponse>}
   */
  async getAll (opts) {
    return this._makeCallBuilder().get(opts)
  }

  /**
   * Get notification counters.
   *
   * @return {Promise<JsonApiResponse>}
   */
  async getCounters () {
    return super._makeCallBuilder()
      .withCredentials()
      .appendUrlSegment('counts')
      .get()
  }

  /**
   * Mark some type of notifications as seen.
   *
   * @param {string} id ID of the notification to mark as seen.
   * @return {Promise.<JsonApiResponse>}
   */
  async markAsSeen (id) {
    return this._makeCallBuilder()
      .appendUrlSegment(id)
      .delete()
  }

  /**
   * Mark an array of notifications as seen.
   *
   * @param {string[]} ids IDs of the notifications to mark as seen.
   * @return {Promise.<JsonApiResponse>}
   */
  async markAsSeenBulk (ids) {
    return this._makeCallBuilder().post({
      data: ids.map(id => ({
        type: 'notifications',
        id
      }))
    })
  }

  _makeCallBuilder () {
    return super._makeCallBuilder()
      .withCredentials()
      .appendUrlSegment('notifications')
  }
}