Slack client helper to recursively request a resource using pagination
https://slack.dev/node-slack-sdk/web_api#pagination

@param {*} client
@param {*} method
@param {*} property
@param {*} options
17771
function RecursivePaginatedWebCall(client, method, property, options = {}) {
    /**
     * store all entries
     */
    var data = [];

    /**
     * count of recursive calls required
     */
    var rcount = 0;

    return new Promise((resolve, reject) => {
      function recurse() {
        rcount++;
        client
          .apiCall(method, options)
          .then(res => {
            data = data.concat(res[property]);

            /**
             * if more pages, keep going otherwise resolve the promise
             */
            if (
              res.response_metadata &&
              res.response_metadata.next_cursor &&
              res.response_metadata.next_cursor !== ""
            ) {
              options.cursor = res.response_metadata.next_cursor;

              // keep recursing
              recurse();
            } else {
              resolve(data);
            }
          })
          .catch(e => {
            reject(e);
          });
      }

      // start recursion
      recurse();
    });
  }
243554
def query_property_filter(query, options)
      if options[:where]
        opts = options[:where]
        if opts[0].is_a?(Array)
          opts.each do |opt|
            query.where(opt[0], opt[1], opt[2]) unless opt.nil?
          end
        else
          query.where(opts[0], opts[1], opts[2])
        end
      end
      query
    end
934773
def callback!(event, options, method, property_options) # TODO: remove args.
      context = options[:context] || self # TODO: test me.

      # TODO: Use Option::Value here. this could be created straight in the DSL with the twin being passed in.
      if context.methods.include?(method) && context.method(method).arity == 1 # TODO: remove in 0.3.
        warn "[Disposable] Callback handlers now receive two options: #{method}(twin, options)."
        return Dispatch.new(@twin).(event, method, property_options) { |twin| context.send(method, twin) }
      end

      Dispatch.new(@twin).(event, method, property_options) { |twin| context.send(method, twin, options) }
    end
1115884
function SlackState(n) {
    RED.nodes.createNode(this, n);

    var node = this;
    this.client = n.client;
    this.clientNode = RED.nodes.getNode(this.client);

    node.status(statuses.disconnected);

    if (node.client) {
      SetConfigNodeConnectionListeners(node);

      node.on("input", function(msg) {
        SlackDebug("slack-state incomiming message", msg);

        node.status(statuses.sending);

        /**
         * support for forcing a refresh of data
         */
        if (msg.payload === true) {
          node.clientNode
            .refreshState()
            .then(() => {
              msg.slackState = node.clientNode.state;
              node.send(msg);
              node.status(statuses.connected);
            })
            .catch(e => {
              SlackDebug("slack-state error response", e.data);
              msg.payload = e.data;
              node.send(msg);
              node.status(statuses.connected);
            });
        } else {
          msg.slackState = node.clientNode.state;
          node.send(msg);
          node.status(statuses.connected);
        }
      });

      ["state_initialized"].forEach(eventName => {
        node.clientNode.on(eventName, e => {
          node.status(statuses.sending);
          var msg = {};

          switch (eventName) {
            case "state_initialized":
              eventName = "ready";
              break;
          }

          msg.slackState = node.clientNode.state;
          msg.payload = {
            type: eventName
          };
          node.send([null, msg]);
          node.status(statuses.connected);
        });
      });
    } else {
      node.status(statuses.misconfigured);
    }
  }
281354
function _sendRequest(method, uri, options, callback) {

        method(uri, options)
            .on('success', function(data, response) {
                if (data.result) {
                    callback(null, data.result);
                } else {
                    callback(null, data);
                }
            })
            .on('fail', function(err, response) {
                if (err) {
                    callback(err);
                } else {
                    callback(new Error('Request failed'));
                }
            })
            .on('error', function(err, response) {
                if (err) {
                    callback(err);
                } else {
                    callback(new Error('Request error'));
                }
            })
            .on('timeout', function(ms) {
                callback(new Error('Request timed out (' + ms + ')'));
            });
    }
1180863
function paginate(q, options, callback) {
  /*jshint validthis:true */
  var query, skipFrom, sort, columns, populate, lean, model = this;
  columns = options.columns || null;
  sort = options.sort || options.sortBy || null; // TODO: get rid of sortBy in major version
  populate = options.populate || null;
  var lean = options.lean || false;
  var pageNumber = options.page || 1;
  var resultsPerPage = options.limit || 10;
  skipFrom = (pageNumber * resultsPerPage) - resultsPerPage;
  query = model.find(q);
  if (columns !== null) {
    query = query.select(options.columns);
  }
  query = query.skip(skipFrom).limit(resultsPerPage);
  if (sort !== null) {
    query.sort(sort);
  }
  if (populate) {
    if (Array.isArray(populate)) {
      populate.forEach(function(field) {
        query = query.populate(field);
      });
    } else {
      query = query.populate(populate);
    }
  }
  if (lean) {
    query.lean();
  }

  if (typeof callback === 'function') {
    return handleCallback(query, q, model, resultsPerPage, callback);
  } else {
    return handlePromise(query, q, model, resultsPerPage);
  }
}
663142
public void addPayloadProperty(Object msg, Map<String,Object> properties, String key)
    {
        String name = "get" + key;
        try {
            Method method = msg.getClass().getMethod(name, EMPTY_PARAMS);
            if (method != null)
            {
                Object value = method.invoke(msg, EMPTY_DATA);
                if (value != null)
                {
                    if (value.getClass().getName().contains("ErrorsType"))
                        this.addErrorsProperties(properties, value);
                    else
                        properties.put(key, value);
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // Ignore this error
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
431215
function (methodName, params, execOptions) {
                var defer = vow.defer();
                var url = this._basePath + methodName;
                var data = JSON.stringify(params);

                sendAjaxRequest(url, data, execOptions).then(
                    this._resolvePromise.bind(this, defer),
                    this._rejectPromise.bind(this, defer)
                );

                return defer.promise();
            }
1011719
function requestAsync(resource, opts = {}) {
  const settings = {
    followRedirect: true,
    encoding: null,
    rejectUnauthorized: false
  };

  if (opts.user && opts.pass) {
    settings.headers = {Authorization: 'Basic ' + token(opts.user, opts.pass)};
  }

  return new Bluebird((resolve, reject) => {
    // Handle protocol-relative urls
    resource = url.resolve('http://te.st', resource);
    request(resource, settings, (err, resp, body) => {
      let msg;
      if (err) {
        debug('Url failed:', err.message || err);
        return reject(err);
      }
      if (resp.statusCode !== 200) {
        msg = 'Wrong status code ' + resp.statusCode + ' for ' + resource;
        debug(msg);
        return reject(new Error(msg));
      }

      const mimeType =
        result(resp, 'headers.content-type') || mime.getType(resource);

      resolve({
        contents: body,
        path: resource,
        mime: mimeType
      });
    });
  });
}
806633
def method_missing(method, *args)
      request = RequestBuilder.new(@client)
      request.send(method, *args)
      request
    end
849139
function Stream(options) {

  /**
   * Whether or not the Stream was initialized as
   * a single- or multi-key stream.
   *
   * @property multi
   * @type Boolean
   */
  reader(this, 'multi', !(options && options.apiKey));

  if (!this.multi) {
    options.headers = options.headers || {};
    options.headers['Zotero-API-Key'] = options.apiKey;

    delete options.apiKey;
  }

  Client.call(this, options);

  /**
   * @property retry
   * @type Object
   */
  reader(this, 'retry', {
    delay: Stream.DEFAULT_RETRY
  });

  /**
   * @property idle
   * @type Object
   */
  reader(this, 'idle', {
    ping: Stream.IDLE_TIMEOUT,
    pong: Stream.IDLE_TIMEOUT / 2
  });

  /**
   * @property subscriptions
   * @type Subscriptions
   */
  this.subscriptions = new Subscriptions();

  this.open = this.open.bind(this);
  this.opened = this.opened.bind(this);
  this.closed = this.closed.bind(this);
  this.ping = this.ping.bind(this);
  this.pong = this.pong.bind(this);
  this.receive = this.receive.bind(this);
  this.error = this.error.bind(this);

  this.open();
}
1154439
function request(method, address, body, options) {
  let timeout = null;
  return new Promise((resolve, reject) => {
    try {
      const opts = _.merge({}, this.options, options, url.parse(address), {
        method,
      });

      // handle optional timeout
      if (typeof opts.timeout === 'number') {
        setTimeout(() => {
          reject(new Error(`${method} "${address}" timed out`));
          timeout = null;
        }, Math.floor(opts.timeout));
      }

      // create some request middleware to potentially
      // add headers ahead of time for auth or set cors, etc.
      const before =
        typeof opts.before === 'function'
          ? opts.before.call(this.context, method, address, opts)
          : () => null;

      const proto = opts.protocol === 'https:' ? https : http;

      return Promise.resolve(before)
        .then(() => {
          clearTimeout(timeout);

          const req = proto.request(opts, res => {
            let data = '';
            res
              .on('data', d => {
                data += d;
              })
              .on('error', error => {
                clearTimeout(timeout);
                reject(error);
              })
              .on('end', () => {
                clearTimeout(timeout);
                const parsedData = processData(res, data, opts);
                return parsedData instanceof Error
                  ? reject(parsedData)
                  : resolve(parsedData);
              });
          });

          req.on('error', error => {
            clearTimeout(timeout);
            reject(error);
          });

          if (method === Method.PUT || method === Method.POST) {
            req.write(processBody(opts, body));
          }
          req.end();
        })
        .catch(error => {
          clearTimeout(timeout);
          return reject(error);
        });
    } catch (error) {
      clearTimeout(timeout);
      return reject(error);
    }
  });
}
43936
function(options) {
            options = (options) ? options : {};
            var data = (options.data || {});
            var p = this.paginationConfiguration;
            var d = {};
            d[p.currentPageParam] = this.currentPage;
            d[p.pageSizeParam] = this.pageSize;

            options.data = d;

            var xhr = Augmented.Collection.prototype.fetch.call(this, options);

            // TODO: parse header links to sync up vars

            return xhr;
          }
973979
protected void configureOAuth20Client(final Collection<BaseClient> properties) {
        val index = new AtomicInteger();
        pac4jProperties.getOauth2()
            .stream()
            .filter(oauth -> StringUtils.isNotBlank(oauth.getId()) && StringUtils.isNotBlank(oauth.getSecret()))
            .forEach(oauth -> {
                val client = new GenericOAuth20Client();
                client.setKey(oauth.getId());
                client.setSecret(oauth.getSecret());
                client.setProfileAttrs(oauth.getProfileAttrs());
                client.setProfileNodePath(oauth.getProfilePath());
                client.setProfileUrl(oauth.getProfileUrl());
                client.setProfileVerb(Verb.valueOf(oauth.getProfileVerb().toUpperCase()));
                client.setTokenUrl(oauth.getTokenUrl());
                client.setAuthUrl(oauth.getAuthUrl());
                client.setCustomParams(oauth.getCustomParams());
                val count = index.intValue();
                if (StringUtils.isBlank(oauth.getClientName())) {
                    client.setName(client.getClass().getSimpleName() + count);
                }
                client.setCallbackUrlResolver(new PathParameterCallbackUrlResolver());
                configureClient(client, oauth);

                index.incrementAndGet();
                LOGGER.debug("Created client [{}]", client);
                properties.add(client);
            });
    }
912747
function nodeClient (request) {

    var client = require('got');

    return new PromiseObj(function (resolve) {

        var url = request.getUrl();
        var body = request.getBody();
        var method = request.method;
        var headers = {}, handler;

        request.headers.forEach(function (value, name) {
            headers[name] = value;
        });

        client(url, {body: body, method: method, headers: headers}).then(handler = function (resp) {

            var response = request.respondWith(resp.body, {
                status: resp.statusCode,
                statusText: trim(resp.statusMessage)
            });

            each(resp.headers, function (value, name) {
                response.headers.set(name, value);
            });

            resolve(response);

        }, function (error$$1) { return handler(error$$1.response); });
    });
}
385929
function doQuery(options) {
            // only User Agent (type = `ua`) clients are available at the moment.
            options.data = extend(options.data, {type: 'ua'});

            return models.Client.findOne(options.data, omit(options, ['data']))
                .then((model) => {
                    if (!model) {
                        return Promise.reject(new common.errors.NotFoundError({
                            message: common.i18n.t('common.api.clients.clientNotFound')
                        }));
                    }

                    return {
                        clients: [model.toJSON(options)]
                    };
                });
        }
132425
public function request($method, $uri, array $parameters = [], array $options = [])
    {
        $parameters['key'] = $this->apiKey;
        $options['query'] = $parameters;

        $uri = $this->apiUrl.$uri.'/json';

        $this->log($method, $uri, $options);
        $response = $this->httpClient->request($method, $uri, $options);

        $result = $this->decoder->decode($response);

        if (!isset($result['status'])) {
            throw new ClientErrorException('Missing return status');
        }

        if (!in_array($result['status'], [
                'OK',
                'ZERO_RESULTS',
            ], true)) {
            throw new ClientErrorException(sprintf('Invalid return status "%s"', $result['status']));
        }

        return $result;
    }