Nuxtとデータベースと認証にfirebase(Cloud FirestoreとFirebase Authentication)を使用する場合に実装方法を紹介します。
アプリケーションからの呼び出しを簡単にするために、pluginとしてFirebaseのラッパーを登録します。
AuthとDatabaseで別々のファイルを作成しても良いのですが、記述量がそんなにないので1つのfirebase.jsファイルでまとめてしまいます。
~/plugins/firebase.js
import firebase from 'firebase'
if (!firebase.apps.length) {
firebase.initializeApp({
apiKey: process.env.APIKEY,
authDomain: process.env.AUTHDOMAIN,
databaseURL: process.env.DATABASEURL,
projectId: process.env.PROJECTID,
storageBucket: process.env.STORAGEBUCKET,
messagingSenderId: process.env.MESSAGINGSENDERID
})
}
// Authentication
function auth() {
return new Promise((resolve, reject) => {
firebase.auth().onAuthStateChanged((user) => {
resolve(user || false)
})
})
}
// Database
const db = firebase.firestore()
export { auth, db }
以下の部分は、画像のプロジェクトを設定を押し、下に行くとデータが乗っているのでそれを参考にしてください。
if (!firebase.apps.length) {
firebase.initializeApp({
apiKey: process.env.APIKEY,
authDomain: process.env.AUTHDOMAIN,
databaseURL: process.env.DATABASEURL,
projectId: process.env.PROJECTID,
storageBucket: process.env.STORAGEBUCKET,
messagingSenderId: process.env.MESSAGINGSENDERID
})
}
次に、nuxt.config.jsに以下を追記し、プラグインとして登録してください
plugins: [
'~/plugins/firebase'
],
使い方
Google認証
import { auth } from 'firebase'
const provider = new auth.GoogleAuthProvider()
auth.signInWithRedirect(provider)
使いたいところで必要なものだけをimportします
Cloud Firestore
<script>
import { db } from '~/plugins/firebase'
...
</script>
export default {
components: {
ApiSection
},
async asyncData({ params }) {
return {
projects: await getData()
}
}
}
// get data from firestore
async function getData() {
const querySnapshot = await db
.collection('projects')
.where('name', '==', 'sample')
.get()
.catch(function(error) {
console.log('Error getting documents: ', error)
})
const data = []
querySnapshot.forEach(function(doc) {
data.push(doc.data())
})
return data
}
firebaseの使い方
いつも忘れてしまうのでついでにfirebaseの使い方も少しだけ書いておきます。
データベース検索
Insert
db.collection('hoge')
.add(data)
.then(function(docRef) {
console.log('Document written with ID: ', docRef.id)
})
.catch(function(error) {
console.error('Error adding document: ', error)
})
async/awaitの場合
const docRef = await db
.collection('hoge')
.add(data)
.catch(function(error) {
console.error('Error adding document: ', error)
})
console.log('Document written with ID: ', docRef.id)
Get
Cloud Firestore で単純なクエリと複合クエリを実行する
var docRef = db.collection("hoge").doc("hogehoge");
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
Delete
db.collection("hoge").doc("hogehoge").delete().then(function() {
console.log("Document successfully deleted!");
}).catch(function(error) {
console.error("Error removing document: ", error);
});
Update
var washingtonRef = db.collection("hoge").doc("hogehoge");
const data = {
sample: true
}
return washingtonRef.update(data)
.then(function() {
console.log("Document successfully updated!");
})
.catch(function(error) {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});