]> git.r.bdr.sh - rbdr/dasein/blob - app/components/posts.js
d0e03387d9f207f5885d58f395970d87bd3c4229
[rbdr/dasein] / app / components / posts.js
1 import Axios from 'axios';
2 import Vue from 'vue';
3 import AuthService from '../services/auth';
4
5 import PostFormComponent from './post_form';
6 import PostComponent from './post';
7 import DatetimeFilter from '../filters/datetime';
8 import UsertimeFilter from '../filters/usertime';
9
10 const internals = {};
11
12 internals.kPostsRoute = '/api/posts';
13 internals.kPollFrequency = 5000;
14
15 export default internals.PostsComponent = Vue.component('posts', {
16 template: '<div v-if="authService.authenticated" class="posts-container">' +
17 '<post-form v-on:post-submitted="addPost"></post-form>' +
18 '<h1>Posts.</h1>' +
19 '<p v-show="message" class="posts-error">{{message}}</p>' +
20 '<post v-for="post in posts" v-bind:post="post" :key="post.uuid"></post>' +
21 '</div>',
22
23 data() {
24
25 return {
26 message: '',
27 authService: new AuthService(),
28 posts: []
29 };
30 },
31
32 methods: {
33 fetchPosts() {
34
35 return Axios({
36 method: 'get',
37 headers: {
38 Authorization: `Bearer ${this.authService.token}`
39 },
40 url: internals.kPostsRoute
41 }).then((response) => {
42
43 this.posts = response.data;
44 if (!this._isBeingDestroyed) {
45 setTimeout(this.fetchPosts.bind(this), internals.kPollFrequency);
46 }
47 }).catch((err) => {
48
49 console.error(err.stack);
50 this.message = 'Error while loading the posts...';
51 });
52 },
53
54 addPost(post) {
55
56 this.posts.unshift(post);
57 }
58 },
59
60 components: {
61 postForm: PostFormComponent,
62 post: PostComponent,
63 datetime: DatetimeFilter,
64 usertime: UsertimeFilter
65 },
66
67 mounted() {
68
69 if (!this.authService.authenticated) {
70 return this.$router.push('/login');
71 }
72
73 this.fetchPosts();
74
75 }
76 });
77