]> git.immae.eu Git - github/bastienwirtz/homer.git/blame - src/components/Message.vue
Merge pull request #175 from luixal/message-remote-fields-mapping
[github/bastienwirtz/homer.git] / src / components / Message.vue
CommitLineData
b9c5fcf0 1<template>
7ef65940 2 <article v-if="show" class="message" :class="message.style">
0e045b4c
GC
3 <div v-if="message.title || message.icon" class="message-header">
4 <p>
5 <i v-if="message.icon" :class="`fa-fw ${message.icon}`"></i>
6 {{ message.title }}
7 </p>
b9c5fcf0 8 </div>
8ae1fe8a
BW
9 <div
10 v-if="message.content"
11 class="message-body"
12 v-html="message.content"
13 ></div>
b9c5fcf0
BW
14 </article>
15</template>
16
17<script>
18export default {
19 name: "Message",
20 props: {
21 item: Object,
22 },
7ef65940
BW
23 data: function () {
24 return {
25 show: false,
26 message: {},
27 };
28 },
29 created: async function () {
b9c5fcf0 30 // Look for a new message if an endpoint is provided.
7ef65940 31 this.message = Object.assign({}, this.item);
1ddf3941 32 await this.getMessage();
7ef65940 33 this.show = this.message.title || this.message.content;
b9c5fcf0 34 },
1ddf3941 35
b9c5fcf0 36 methods: {
1ddf3941 37 getMessage: async function() {
38 if (this.item && this.item.url) {
39 let fetchedMessage = await this.downloadMessage(this.item.url);
40 if (this.item.mapping) fetchedMessage = this.mapRemoteMessage(fetchedMessage);
41 // keep the original config value if no value is provided by the endpoint
42 for (const prop of ["title", "style", "content"]) {
43 if (prop in fetchedMessage && fetchedMessage[prop] !== null) {
44 this.message[prop] = fetchedMessage[prop];
45 }
46 }
47 }
1ddf3941 48 if (this.item.refreshInterval) setTimeout(this.getMessage, this.item.refreshInterval);
49 },
50
51 downloadMessage: function (url) {
b9c5fcf0
BW
52 return fetch(url).then(function (response) {
53 if (response.status != 200) {
54 return;
55 }
56 return response.json();
57 });
58 },
6d29bc27 59
60 mapRemoteMessage: function (message) {
61 let mapped = {};
62 // map property from message into mapped according to mapping config (only if field has a value):
63 for (const prop in this.item.mapping) if (message[this.item.mapping[prop]]) mapped[prop] = message[this.item.mapping[prop]];
64 return mapped;
65 },
b9c5fcf0
BW
66 },
67};
68</script>