All files / src/model StreamResponse.ts

59.26% Statements 16/27
0% Branches 0/2
60% Functions 3/5
57.69% Lines 15/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    2x 2x 2x   2x   17x           17x   17x 17x   72x 14x             3x 3x     17x                   17x                   17x                            
import { Moment } from 'moment';
 
import { Util } from '../internal/Util';
import { StreamPost } from './StreamPost';
import { TwitarrError } from '../api/TwitarrError';
 
export class StreamResponse {
  public static fromRest(data: any) {
    Util.assertHasProperties(data, 'has_next_page');
 
    if (Util.isEmpty(data.stream_posts, data.stream_post, data.post)) {
      throw new TwitarrError('At least one of stream_posts, stream_post, or posts is expected on the response!', undefined, undefined, undefined, data);
    }
 
    const ret = new StreamResponse();
 
    Util.setProperties(ret, data, 'has_next_page');
    Util.setDateProperties(ret, data, 'next_page');
    if (!Util.isEmpty(data.stream_posts)) {
      ret.posts = data.stream_posts.map(post => StreamPost.fromRest(post));
      ret.is_thread = false;
    }
    if (!Util.isEmpty(data.stream_post)) {
      ret.posts = [StreamPost.fromRest(data.stream_post)];
      ret.is_thread = true;
    }
    if (!Util.isEmpty(data.post)) {
      ret.posts = [StreamPost.fromRest(data.post)];
      ret.is_thread = true;
    }
 
    return ret;
  }
 
  /** Whether there are more posts to retrieve. */
  public has_next_page: boolean;
 
  /** The timestamp of the next page. */
  public next_page: Moment;
 
  /** The stream posts. */
  public posts: StreamPost[] = [];
 
  public get post() {
    if (this.posts && this.posts.length >= 2) {
      throw new TwitarrError('StreamResponse has more than one post!');
    }
    return this.posts[0];
  }
 
  /** Whether this is a single thread or multiple posts. */
  public is_thread: boolean = false;
 
  public toJSON() {
    const ret = {} as any;
    ret.has_next_page = this.has_next_page;
    ret.next_page = this.next_page;
    if (ret.is_thread) {
      ret.post = this.posts;
    } else {
      ret.stream_posts = this.posts;
    }
    return ret;
  }
}