Manual Reference Source Test

src/services/RuleService.js

import { deprecate } from 'core-decorators';
import Client from '../Client';
import Event from '../helpers/reminder/Event';
import JsonApiService from './JsonApiService';
// import Rule from '../helpers/reminder/Rule';

import { validate, hasToken, isRequired } from '../utilities/ValidationUtility';

/**
 * Service handling Rule calls with specific endpoints.
 */
class RuleService extends JsonApiService {
  /**
   * Update type to be rules
   */
  constructor() {
    super();

    /** @type {String} - The type of the default data */
    this.type = 'reminder__rules';
  }

  /**
   * @override
   * Call a PATCH request on the main obj.type expecting JSON API information.
   *
   * @param  {Rule} rule      - Rule object in which to update
   * @param  {String} [cacheMode] - Override the caching method for this call
   * @return {Promise}            - Message
   *
   * @example
   * import { ruleService } from 'clinical6';
   *
   * // You will be able to delete a rule using `delete`.
   * ruleService.delete({ id: 23 });
   * // This will also clear the local storage of this type and id
   */
  async delete(rule, cacheMode = undefined) {
    validate('RuleService.delete',
      hasToken(),
      isRequired({ rule }));
    return super.delete(rule, { cacheMode });
  }

  /**
   * @override
   * Call a GET request expecting JSON API information.
   *
   * @throws {Clinical6Error}     - If missing token or missing required parameters
   * @param  {Object} [params]    - Parameters used to get information from server (such as id)
   * @param  {String} [cacheMode] - Override the caching method for this call
   * @return {Promise<Rule[] | Rule>}
   *                              - Promise object that returns one rule or a key:rule hashtable
   *
   * @example
   * import { ruleService } from 'clinical6';
   *
   * // You will be able to access these rules using the `get` method.
   * ruleService.get().then(rules => console.log(rules));
   *
   * // Additionally, you can retrieve the subcategories for a specific rule with the `get`
   * // method, using the ID of the desired rule as a parameter.
   * ruleService.get(23).then(rule => console.log(rule));
   */
  async get(params = {}, cacheMode = undefined) {
    validate('RuleService.get',
      hasToken());
    return super.get(params, { cacheMode });
  }

  /**
   * @override
   * Call a POST request on the main obj.type expecting JSON API information.
   *
   * @param  {Rule}  rule       - Key from server
   * @param  {String} [cacheMode] - Override the caching method for this call
   * @return {Promise<Rule>}     - Inserted rule
   *
   * @example
   * import { Rule, ruleService } from 'clinical6';
   * const rule = new Rule({...});
   *
   * // you can insert a rule using the `insert` method.
   * ruleService.insert(mobileApplicationKey).then(rule => console.log(rule));
   *
   * // you could also just call `save` on the rule if it doesn't have an id, which will also
   * // invoke the `insert` method
   * rule.save();
   */
  async insert(rule, cacheMode = undefined) {
    validate('RuleService.insert',
      hasToken(),
      isRequired({ rule }));

    return super.insert(rule, { cacheMode });
  }

  /**
   * @override
   * Call a PATCH request on the main obj.type expecting JSON API information.
   *
   * @param  {Rule} rule      - Rule object in which to update
   * @param  {String} [cacheMode] - Override the caching method for this call
   * @return {Promise<Rule>}    - Updated rule
   *
   * @example
   * import { Rule, ruleService } from 'clinical6';
   * const rule = new Rule({...});
   *
   * // you can update a rule using the `update` method.
   * ruleService.update(rule).then(rule => console.log(rule));
   *
   * // you could also just call `save` on the rule if it has an id, which will also
   * // invoke the `update` method
   * rule.save();
   */
  async update(rule, cacheMode = undefined) {
    validate('RuleService.update',
      hasToken(),
      isRequired({ rule }));
    return super.update(rule, { cacheMode });
  }

  // old v2 methods below

  /**
   * @deprecated
   * Returns all reminder events.
   *
   * @param {String} ruleId - The rule ID to check for events. (optional)
   * @return {Promise} Promise object that returns success or failure
   */
  @deprecate
  getEvents(ruleId) {
    validate('RuleService.getEvents',
      hasToken());

    const httpQuery = ruleId !== undefined ? `?rule_id=${ruleId}` : '';

    return new Promise((resolve, reject) => {
      Client.instance.fetch(`/api/reminder/events${httpQuery}`).then(
        response => resolve(response),
        err => reject(err)
      );
    });
  }

  /**
   * @deprecated
   * Returns all reminder events. Requires a rule ID to filter the events to return.
   *
   * @param {String} ruleId - The rule ID to check for events. (required)
   * @return {Promise} Promise object that returns success or failure
   */
  @deprecate
  getEventsByRule(ruleId) {
    validate('RuleService.getEvents',
      hasToken(),
      isRequired({ ruleId }));

    return new Promise((resolve, reject) => {
      Client.instance.fetch(`/api/reminder/rules/${ruleId}/events`).then(
        response => resolve(response[ruleId].map(obj => new Event(obj))),
        err => reject(err)
      );
    });
  }

  /**
   * @deprecated
   * Marks the event depending on the action given. The results can vary depending on the time this
   * method is called. If an invalid action is given, it will be interpreted as 'ignored'.
   * Event action is either 'completed' or 'ignored'. Passes parameters in URL.
   *
   * @param {String} ruleId - Permanent link of the rule of the event to update.
   * @param {String} eventId - ID value of the event to update.
   * @param {String} eventAction - The optional event action indicates the action to mark the event
   * with. Event action must either be 'completed' or 'ignored'. If no value or an invalid value is
   * provided, the event action will be interpreted as 'ignored'.
   * @return {Promise} Promise object that returns success or failure
   */
  @deprecate
  markEvent(ruleId, eventId, eventAction) {
    validate('RuleService.markEvent',
      hasToken(),
      isRequired({ ruleId, eventId }));

    return new Promise((resolve, reject) => {
      Client.instance.fetch(`/api/reminder/rules/${ruleId}/events/${eventId}/mark`, 'post',
        { event_action: eventAction }).then(
        response => resolve(response),
        err => reject(err)
      );
    });
  }

  /**
   * @deprecated
   * Marks the event depending on the action given. The results can vary depending on the time this
   * method is called. If an invalid action is given, it will be interpreted as 'ignored'.
   * Event action is either 'completed' or 'ignored'. Events will be marked based
   * off of the supplied eventChange object. The event ID and event action will be passed
   * through the eventChange object and not by URL parameters.
   *
   * @param {String} ruleId - Permanent link of the rule of the event to update.
   * @param {Object} eventChange - Object with the changes to make for the event
   * @param {Number} eventChange.id - The ID of the event to mark.
   * If no ID value is supplied no change will be made. (optional)
   * @param {String} eventChange.event_action - The optional event action
   * indicates the action to mark the event with. Event action must either be 'completed' or
   * 'ignored'. If no value or an invalid value is
   * provided, the event action will be interpreted as 'ignored'.
   *
   * @return {Promise} Promise object that returns success or failure
   */
  @deprecate
  markEventByObj(ruleId, eventChange) {
    validate('RuleService.markEventByObj',
      hasToken(),
      isRequired({ ruleId }));

    return new Promise((resolve, reject) => {
      Client.instance.fetch(`/api/reminder/rules/${ruleId}/events/mark`, 'post',
        eventChange).then(
        response => resolve(response),
        err => reject(err)
      );
    });
  }

  /**
   * @deprecated
   * Returns the most recent events for all rules. Optionally, the time unit can be specified
   * to filter the events to return.
   *
   * @param {String} timeUnit - The time cap for recent events.
   * Must be either 'week' or 'month' (optional)
   * @return {Promise} Promise object that returns success or failure
   */
  @deprecate
  getRecentEvents(timeUnit) {
    validate('RuleService.getRecentEvents',
      hasToken());

    const httpQuery = timeUnit !== undefined ? `?time_unit=${timeUnit}` : '';

    return new Promise((resolve, reject) => {
      Client.instance.fetch(`/api/reminder/events/recent${httpQuery}`).then(
        response => resolve(response),
        err => reject(err)
      );
    });
  }

  /**
   * @deprecated
   * Returns the most recent events for all rules. This method requires a rule ID in order
   * to filter the recent events by rules. Optionally, the time unit can be specified
   * to filter the events to return.
   *
   * @param {String} ruleId - The rule ID to filter the recent events (required)
   * @param {String} timeUnit - The time cap for recent events.
   * Must be either 'week' or 'month' (optional)
   * @return {Promise} Promise object that returns success or failure
   */
  @deprecate
  getFilteredRecentEvents(ruleId, timeUnit) {
    validate('RuleService.getFilteredRecentEvents',
      hasToken(),
      isRequired({ ruleId }));

    const httpQuery = timeUnit !== undefined ? `?time_unit=${timeUnit}` : '';

    return new Promise((resolve, reject) => {
      Client.instance.fetch(`/api/reminder/rules/${ruleId}/events/recent${httpQuery}`).then(
        response => resolve(response[ruleId].map(obj => new Event(obj))),
        err => reject(err)
      );
    });
  }

  /**
   * @deprecated
   * Returns the next event for a given rule. If there is not a next event
   * a 404 status will be returned.
   *
   * @param {String} ruleId - The rule ID to check for the next event.
   * @return {Promise} Promise object that returns success or failure
   */
  @deprecate
  getNextEvent(ruleId) {
    validate('RuleService.getNextEvent',
      hasToken(),
      isRequired({ ruleId }));

    return new Promise((resolve, reject) => {
      Client.instance.fetch(`/api/reminder/rules/${ruleId}/events/next`).then(
        response => resolve(new Event(response)),
        err => reject(err)
      );
    });
  }

  /**
   * @deprecated
   * Returns the events that will occur soon for the given rule ID.
   * Optionally, the time unit can be specified to filter the events to return.
   *
   * @param {String} ruleId - The rule ID to check for upcoming events.
   * @param {String} [timeUnit] - The time cap for recent events. Must be either 'week' or 'month' (optional)
   * @return {Promise} Promise object that returns success or failure
   */
  @deprecate
  getUpcomingEvents(ruleId, timeUnit) {
    validate('RuleService.getUpcomingEvents',
      hasToken(),
      isRequired({ ruleId }));

    const httpQuery = timeUnit !== undefined ? `?time_unit=${timeUnit}` : '';

    return new Promise((resolve, reject) => {
      Client.instance.fetch(`/api/reminder/rules/${ruleId}/events/upcoming${httpQuery}`).then(
        response => resolve(response[ruleId].map(obj => new Event(obj))),
        err => reject(err)
      );
    });
  }

  /**
   * @deprecated
   * Returns all the vents for a given rule that occur on the supplied date.
   * If the date is in the future, new events may be created depending on the
   * rules and their schedule.
   *
   * @param {String} ruleId - The rule ID to check for events.
   * @param {String} date - The date that will be used to filter the events.
   * Use ISO8601 format YYYY-MM-DD.
   * @return {Promise} Promise object that returns success or failure
   */
  @deprecate
  getEventsByDate(ruleId, date) {
    validate('RuleService.getEventsByDate',
      hasToken(),
      isRequired({ ruleId, date }));

    return new Promise((resolve, reject) => {
      Client.instance.fetch(`/api/reminder/rules/${ruleId}/events/${date}/by_date`).then(
        response => resolve(response[ruleId].map(obj => new Event(obj))),
        err => reject(err)
      );
    });
  }
}

export default RuleService;