Source: src/request.js

/**
 * IdealNet REST Request.
 *
 * Implements functions and logic to parse the REST request
 * coming into IdealNet REST and translate that to a pubsub
 * request.
 *
 * @author michael whobrey <mwhobrey@idealss.com>
 */

const axios = require('axios');
const { extractApiFromQuery, getPrivateKey} = require('./utils');
const {constants} = require('./constants');
const INRClient = require('./inrClient');

/**
 * IdealNet REST Request (INRRequest) class.
 *
 * Provides a way to process an incoming REST request
 * in a PubSub manner and return the results to the
 * caller.
 */
class INRRequest {
  #path;
  #restReq;
  #token;
  #signature;
  #payload;

  /**
   * Create a request.
   *
   * @param path {string} the pubsub message path for the request
   * @param restReq {Object} the REST request body to parse
   * @param restReq.token {string}  - the token of the client being used to make the request
   * @param restReq.signature {string}  - the signature of req.payload + private key
   * @param restReq.group {Number} - the group number for the location
   * @param restReq.siteId {Number} - the location id
   * @param restReq.payload {Object}  - the actual api body to be used to make the pubsub request (structure varies)
   */
  constructor(path, restReq) {
    this.#path = path;
    this.#restReq = restReq;
    this.#token = restReq.token;
    this.#signature = restReq.signature;
    this.#payload = restReq.payload;

    this.publish = this.publish.bind(this);
    this.pubSubIt = this.pubSubIt.bind(this);
  }

  /**
   * Getter for path
   */
  get path() {
    return this.#path;
  }

  /**
   * Getter for client.
   */
  get restReq() {
    return this.#restReq;
  }

  /**
   * Getter for token.
   */
  get token() {
    return this.#token;
  }

  /**
   * Getter for signature.
   */
  get signature() {
    return this.#signature;
  }

  /**
   * Getter for payload.
   */
  get payload() {
    return this.#payload;
  }

  /**
   * Publish to pubsub the data.
   * 
   * Check the payload size, if the size is over 50k bytes then call the lmsRedirect function
   * to get the redirect hash_id. Send the request as normal if the payload is under 50k bytes.
   *
   * @param client {INRClient} The client that has established the connection with pubsub.
   */
  publish(client) {
    if (Buffer.byteLength(JSON.stringify(this.#payload)) > 50000) {
      this.lmsRedirect(this.#payload)
        .then( (payload) => {
          client.publish(this.#path, payload);
        })
        .catch( (err) => {
          throw err;
        });
    }
    else {
      client.publish(this.#path, this.#payload);
    }
  }

  /**
   * Send message payload that is over the 50k limit to the redirect service and return
   * the updated payload.
   * 
   * Take the payload and send it via HTTP Post to the redirect service. The redirect service
   * will return an object that has a boolean "success" property and a string "hash_id" property. 
   * The returned hash_id will be set on a new property called "redirect"
   * and the payload's "data" property will be cleared. Return a promise that resolves with the
   * updated payload.
   * 
   * @param payload {Object} The payload to send to the redirect service.
   * 
   * @return {Promise} Returns a promise that resolves with the updated payload.
   */
  lmsRedirect = async (payload) => {
    return new Promise( (resolve, reject) => {
      try {
        axios.post(constants.lmsEndpoint(), payload)
          .then( (res) => {
            if (res.data.success) {
              payload.redirect = res.data.hash_id;
              payload.data = {};
              resolve(payload);
            }
            else {
              reject(res.data);
            }
          })
          .catch( (err) => {
            reject(err);
          });
      }
      catch (err) {
        reject(err);
      }
    });
  };

  /**
   * Send message via IdealNet PubSub and return the response.
   *
   * Connect to IdealNet PubSub as a proxy for the REST request,
   * send the request and wait on the results to return as the
   * results for the REST request.
   *
   * @param dbClient {MongoClient} Database connection client.
   *
   * @return {Promise} Returns a response from pubsub once received or fails
   * with an error.
   */
  pubSubIt = async (dbClient) => {
    const key = await getPrivateKey(this.#token, dbClient);
    const client = new INRClient(extractApiFromQuery(this.#path), this.#restReq.group, this.#restReq.siteId, this.#token, key);
    return new Promise( (resolve, reject) => {
      try {
        client.onSubscribed = () => {
          this.publish(client);
        };

        client.onError = (err) => {
          resolve(err);
        };

        client.connect((res) => {
          resolve(res);
        });
      }
      catch (err) {
        reject(err);
      }
    });
  };
}

module.exports = INRRequest;