我当前的问题是我想初始化应用程序以将一些用户变量设置为状态,但是无法按预期运行,这是我当前的nuxtServerInit代码:
store / index.js
import { usersCollection } from '~/plugins/firebase.js'
const COOKIE_NAME = '__session'
export const state = () => ({
locales: ['en', 'es', 'it'],
locale: 'en'
})
export const mutations = {
setLanguage(state, locale) {
if (state.locales.indexOf(locale) !== -1) {
state.locale = locale
}
}
}
export const getter = {
getLanguages: state => state.locales,
getLanguage: state => state.locale
}
// TODO
export const actions = {
nuxtServerInit: (process.server && !process.static) ? async function({ commit, dispatch }, { req, store }) {
if (!req.headers.cookie) { return }
// CUSTOM
const admin = await import('firebase-admin');
const key = require('../keys/service-account.json') // You will get it inside your firebase project settings
// eslint-disable-next-line import/no-mutable-exports
let adminApp
if (admin.apps.length > 0) {
adminApp = admin
} else {
adminApp = admin.initializeApp({
credential: admin.credential.cert(key)
})
}
// CUSTOM END
//if (!admin.apps.length) {
// return;
//}
const cookie = await import('cookie');
const parsedCookies = cookie.parse(req.headers.cookie);
if (!parsedCookies) { return; }
const idToken = parsedCookies[COOKIE_NAME];
const JWTDecode = (await import('jwt-decode')).default;
let decodedAuthUserClaims = null;
try {
decodedAuthUserClaims = JWTDecode(idToken);
} catch { }
if (decodedAuthUserClaims == null) { return; }
try {
const decodedToken = await adminApp.auth().verifyIdToken(idToken, true)
const uid = decodedToken.uid
if (uid) {
console.log('UID: ', uid)
commit('user/setUid', uid)
dispatch('user/fetchUserProfile')
}
} catch {
}
} : () => { },
setLanguage({commit, rootState}, locale) {
commit('setLanguage', locale)
// Adding preferred language
usersCollection.doc(rootState.user.uid)
.update({
preferredLanguage: locale
})
}
}
尝试了很多类似的解决方案:
https://github.com/nuxt/nuxt.js/issues/129
感谢阅读本文,希望有解决方案。