All files / src/tumblr stream.js

100% Statements 19/19
100% Branches 11/11
100% Functions 8/8
100% Lines 16/16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67                                                      13x 13x 13x 13x 13x 6x                     8x   7x 7x   11x 7x   7x 6x 4x 6x           1x            
import Stream from '../core/stream';
 
/**
 * @private
 * @class TumblrStream
 * @description TumblrStream class
 * @example
 *
 * const stream = tumblr.stream('blog/:blog-identifier/posts');
 *
 * stream.on('message', (message) => {
 *  console.log(message);
 * });
 *
 * // handle stream error
 * stream.on('error', (err) => {
 *  // An error occur
 *  console.log(err);
 * });
 */
class TumblrStream extends Stream {
  /**
   * @private
   * @memberof TumblrStream
   * @description Create a new instance of TumblrStream class
   */
  constructor(tumblr, endpoint, options = {}) {
    super(options);
    this.tumblr = tumblr;
    this.endpoint = endpoint;
    this.interval = options.interval || 20000;
    if (options.runOnCreation !== false) {
      this.start();
    }
  }
 
  /**
   * @memberof TumblrStream
   * @private
   * @description Make a request on tumblr API.<br />
   * Cache the result and emit only new messages.
   */
  makeRequest() {
    this.tumblr.get(this.endpoint)
      .then((data) => {
        const posts = data.response.posts;
        if (posts.length > 0) {
          // Only return messages not in cache
          let newPosts = posts.filter(post => this.cache.indexOf(post.id) === -1);
          this.cache.push(...newPosts.map(post => post.id));
          // Only return messages created after the stream
          newPosts = newPosts.filter(post => this.startDate < new Date(post.date));
          if (newPosts.length > 0) {
            newPosts.forEach((newPost) => {
              this.emit('message', newPost);
            });
          }
        }
      })
      .catch((err) => {
        this.emit('error', err.error || err);
      });
  }
}
 
export default TumblrStream;