81 lines
2.0 KiB
JavaScript
81 lines
2.0 KiB
JavaScript
|
import { getDocs, collection, getFirestore, deleteDoc, doc, serverTimestamp, Timestamp, addDoc } from 'firebase/firestore'
|
||
|
import { getAuth } from 'firebase/auth'
|
||
|
|
||
|
export const useNewsStore = defineStore('news', () => {
|
||
|
const db = getFirestore()
|
||
|
const auth = getAuth()
|
||
|
|
||
|
const news = ref([])
|
||
|
const loaded = ref(false)
|
||
|
|
||
|
const toast = useToast()
|
||
|
|
||
|
const getNews = async () => {
|
||
|
news.value = []
|
||
|
try {
|
||
|
const querySnapshot = await getDocs(collection(db, "news"));
|
||
|
querySnapshot.forEach((doc) => {
|
||
|
let data = doc.data()
|
||
|
data.id = doc.id
|
||
|
news.value.push(data)
|
||
|
});
|
||
|
|
||
|
news.value.sort((a, b) => b.date.seconds - a.date.seconds)
|
||
|
|
||
|
loaded.value = true
|
||
|
} catch (e) {
|
||
|
console.log(e)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
const deleteNews = async (item, index) => {
|
||
|
if (!item.id) return toast.error('Refresh eerst voordat je dit bericht kan verwijderen')
|
||
|
|
||
|
try {
|
||
|
await deleteDoc(doc(db, "news", item.id));
|
||
|
|
||
|
news.value.splice(index, 1)
|
||
|
toast.success('Bericht verwijderd')
|
||
|
} catch (e) {
|
||
|
console.log(e)
|
||
|
|
||
|
toast.error('Error tijdens bericht verwijderen')
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
const send = async (form) => {
|
||
|
const idToken = await auth.currentUser.getIdToken(true)
|
||
|
console.log(idToken)
|
||
|
|
||
|
const { error } = await useFetch('/api/sendmessage', {
|
||
|
method: 'post',
|
||
|
body: { title: form.title, body: form.description, token: idToken, topic: form.topic }
|
||
|
})
|
||
|
|
||
|
if (error.value) {
|
||
|
console.log(error.value)
|
||
|
return toast.error('Error tijdens het versturen van het bericht')
|
||
|
}
|
||
|
|
||
|
await addDoc(collection(db, "news"), {
|
||
|
title: form.title,
|
||
|
description: form.description,
|
||
|
date: serverTimestamp()
|
||
|
});
|
||
|
|
||
|
if (news.value) {
|
||
|
news.value.unshift({
|
||
|
title: form.title,
|
||
|
description: form.description,
|
||
|
date: Timestamp.now()
|
||
|
})
|
||
|
}
|
||
|
toast.success('Bericht is verstuurd')
|
||
|
|
||
|
navigateTo('/news')
|
||
|
}
|
||
|
|
||
|
return { getNews, news, loaded, deleteNews, send }
|
||
|
});
|