]> git.r.bdr.sh - rbdr/dasein/blob - app/components/posts.js
c41707fc7e71b8e3963bb807b50994af5ca6c8d9
[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 DatetimeFilter from '../filters/datetime';
7 import UsertimeFilter from '../filters/usertime';
8
9 const internals = {};
10
11 internals.kPostsRoute = '/api/posts';
12
13 export default internals.PostsComponent = Vue.component('posts', {
14 template: '<div class="posts-container">' +
15 '<post-form v-on:post-submitted="addPost"></post-form>' +
16 '<h1>Posts.</h1>' +
17 '<p v-show="message" class="posts-error">{{message}}</p>' +
18 '<article class="post" v-for="post in posts">' +
19 '<aside class="post-meta">' +
20 '<img :src="post.userImage" v-bind:alt="\'Avatar for @\' + post.userId">' +
21 '<a v-bind:href="\'https://twitter.com/\' + post.userId">{{post.userName}}</a> said on ' +
22 '<time v-bind:datetime="post.timestamp | datetime">{{post.timestamp | usertime}}</time>' +
23 '</aside>' +
24 '<div class="post-content">{{post.content}}</div>' +
25 '</article>' +
26 '</div>',
27
28 data() {
29
30 return {
31 message: '',
32 authService: new AuthService(),
33 posts: []
34 };
35 },
36
37 methods: {
38 fetchPosts() {
39
40 return Axios({
41 method: 'get',
42 headers: {
43 Authorization: `Bearer ${this.authService.token}`
44 },
45 url: internals.kPostsRoute
46 }).then((response) => {
47
48 this.posts = response.data;
49 }).catch((err) => {
50
51 console.err(err.stack);
52 this.message = 'Error while loading the posts...';
53 });
54 },
55
56 addPost(post) {
57
58 this.posts.unshift(post);
59 }
60 },
61
62 components: {
63 postForm: PostFormComponent,
64 datetime: DatetimeFilter,
65 usertime: UsertimeFilter
66 },
67
68 mounted: function mounted() {
69
70 if (!this.authService.authenticated) {
71 return this.$router.push('/login');
72 }
73
74 return this.fetchPosts();
75 }
76 });
77