|
|
|
|
class JokeService {
|
|
|
|
|
|
|
|
|
|
constructor(categories = ['programming', 'coding', 'development'], lang = 'en') {
|
|
|
|
|
this.categories = Array.isArray(categories) ? categories : [categories];
|
|
|
|
|
this.lang = lang;
|
|
|
|
|
this.apiBaseUrl = 'https://v2.jokeapi.dev/joke/';
|
|
|
|
|
this.toldJokes = localStorage.getItem('toldJokes') !== null ? JSON.parse(localStorage.getItem('toldJokes')) : [];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
setCategory(category) {
|
|
|
|
|
this.categories = Array.isArray(category) ? category : [category];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
tell() {
|
|
|
|
|
let service = this;
|
|
|
|
|
|
|
|
|
|
axios.get(
|
|
|
|
|
service.apiBaseUrl + service.categories.join(',') + '?lang=' + service.lang
|
|
|
|
|
).then((response) => {
|
|
|
|
|
if (response.data.error === false) {
|
|
|
|
|
if (service.toldJokes.includes(response.data.id)) {
|
|
|
|
|
service.tell();
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
service.show(response.data);
|
|
|
|
|
}
|
|
|
|
|
}).catch((error) => {
|
|
|
|
|
console.error(error);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
show(joke) {
|
|
|
|
|
let service = this;
|
|
|
|
|
if (joke.type === 'twopart') {
|
|
|
|
|
setTimeout(() => {
|
|
|
|
|
showNotification(joke.delivery)
|
|
|
|
|
}, 4000);
|
|
|
|
|
|
|
|
|
|
showNotification(joke.setup);
|
|
|
|
|
service.jokeTold(joke);
|
|
|
|
|
} else {
|
|
|
|
|
showNotification(joke.joke);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
jokeTold(joke) {
|
|
|
|
|
this.toldJokes.push(joke.id);
|
|
|
|
|
localStorage.setItem('toldJokes', JSON.stringify(this.toldJokes));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
getToldJokes() {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function showNotification(text) {
|
|
|
|
|
if (Notification.permission === 'granted') {
|
|
|
|
|
new Notification('', {
|
|
|
|
|
body: text
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
console.warn('Notifications sind nicht erlaubt.')
|
|
|
|
|
}
|
|
|
|
|
}
|