store/modules/fcm.js
// src/store/modules/fcm.js
import { messaging } from '@/firebase';
import { getToken } from "firebase/messaging";
import { db, collection, doc, setDoc, getDoc, updateDoc, deleteDoc, arrayUnion } from "@/firebase";
const state = {
isGranted: false,
isLoading: false,
error: null
};
const mutations = {
setGranted(state, isGranted) {
state.isGranted = isGranted;
},
setError(state, error) {
state.error = error;
},
setLoading(state, isLoading) {
state.isLoading = isLoading;
}
};
const actions = {
async getAndSaveFCMToken({ commit, dispatch }, userId) {
commit('setLoading', true);
try {
// Request permission from the user to send notifications
const permission = await Notification.requestPermission();
if (permission === "granted") {
//console.log("Notification permission granted.");
// Get the FCM token
const token = await getToken(messaging, { vapidKey: process.env.VUE_APP_VAPID_KEY });
if (token) {
// Save the FCM token to Firestore
dispatch('saveFCMToken', { userId, token });
commit("setGranted", true);
} else {
commit('setError', "No registration token available.");
}
} else {
commit('setError', "Notification permission denied.");
}
} catch (error) {
commit('setError', "An error occurred while getting the FCM token: " + error.message);
}
},
// Save the FCM token to Firestore
async saveFCMToken({ commit }, {userId, token}) {
try {
const tokenRef = doc(db, 'fcmTokens', userId);
const tokenDoc = await getDoc(tokenRef);
if (tokenDoc.exists()) {
// 이미 등록된 토근이 있는 경우
const tokens = tokenDoc.data().tokens || [];
// Check if the token already exists
const tokenExists = tokens.some(t => t.token === token);
if (!tokenExists) {
// Add the token with creation date using arrayUnion
await updateDoc(tokenRef, {
tokens: arrayUnion({
token: token,
createdAt: new Date()
})
});
commit('setLoading', false);
alert('New FCM token added with creation date.');
} else {
commit('setLoading', false);
alert('FCM token already exists, no action taken.');
}
} else {
// Create a new document if the user does not exist, with the token and creation date
await setDoc(tokenRef, {
tokens: [{
token: token,
createdAt: new Date()
}]
});
//commit('setError', 'User document created and token saved.');
commit('setLoading', false);
alert('User document created and token saved.');
}
} catch (error) {
//commit('setError','Error saving FCM token: ${error}');
commit('setLoading', false);
alert('Error saving FCM token : ' + error);
}
},
async deleteFCMToken({ commit }, userId) {
commit('setLoading', true);
try {
const tokenRef = doc(db, 'fcmTokens', userId);
const tokenDoc = await getDoc(tokenRef);
if (tokenDoc.exists()) {
// 이미 등록된 토근이 있는 경우
await deleteDoc(tokenRef);
commit("setGranted", false);
commit('setLoading', false);
alert('User token deleted.');
}
} catch (error) {
//commit('setError',"Error delete FCM token: " + error.message);
commit('setLoading', false);
alert('Error delete FCM token : ' + error);
}
},
// 푸시 알림 허용/차단을 위하여 토큰이 저장되어 있는지 확인
async checkFCMToken({ commit }, userId) {
const tokenRef = doc(db, 'fcmTokens', userId);
try {
const tokenDoc = await getDoc(tokenRef);
if (tokenDoc.exists()) {
commit("setGranted", true);
} else {
commit("setGranted", false);
}
} catch (error) {
commit('setError','Error check FCM token : ' + error.message);
console.error('Error check FCM token:', error);
}
},
resetError({ commit }) {
commit('setError', null);
},
};
const getters = {
isGranted: state => state.isGranted,
isLoading: state => state.isLoading,
error: state => state.error
};
export default {
namespaced: true,
state,
mutations,
actions,
getters
};