aboutsummaryrefslogtreecommitdiff
path: root/app/components/comments.js
blob: e29cedc3c4affdc2b9910ff5ac8dd307438663ff (plain)
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
68
69
70
71
72
73
74
75
76
import Axios from 'axios';
import Vue from 'vue';
import AuthService from '../services/auth';

import CommentFormComponent from './comment_form';
import CommentComponent from './comment';
import DatetimeFilter from '../filters/datetime';
import UsertimeFilter from '../filters/usertime';

const internals = {};

internals.kPostsRoute = '/api/posts';
internals.kCommentsRoute = '/comments';
internals.kPollFrequency = 2000;

export default internals.CommentsComponent = Vue.component('comments', {
  template: '<div class="comments-container">' +
      '<p v-show="message" class="comments-error">{{message}}</p>' +
      '<comment v-for="comment in comments" v-bind:comment="comment" :key="comment.uuid"></comment>' +
      '<comment-form v-bind:postUuid="postUuid" v-on:comment-submitted="addComment"></comment-form>' +
      '</div>',

  props: ['postUuid'],

  data() {

    return {
      message: '',
      poller: null,
      authService: new AuthService(),
      comments: []
    };
  },

  methods: {
    fetchComments() {

      const route = `${internals.kPostsRoute}/${this.postUuid}${internals.kCommentsRoute}`;

      return Axios({
        method: 'get',
        headers: {
          Authorization: `Bearer ${this.authService.token}`
        },
        url: route
      }).then((response) => {

        this.comments = response.data;
        if (!this._isBeingDestroyed) {
          setTimeout(this.fetchComments.bind(this), internals.kPollFrequency);
        }
      }).catch((err) => {

        console.error(err.stack);
        this.message = 'Error while loading the comments...';
      });
    },

    addComment(comment) {

      this.comments.push(comment);
    }
  },

  components: {
    commentForm: CommentFormComponent,
    comment: CommentComponent,
    datetime: DatetimeFilter,
    usertime: UsertimeFilter
  },

  mounted() {

    this.fetchComments();
  }
});