Firebase Web CodelabのFriendly Chatチュートリアルで手順や躓いたところなどのメモ
Firebase Web CodelabのFriendly Chatチュートリアル
下準備
nodebrewとnode.jsとnpmを準備
$node -v
v10.11.0
$npm -v
6.4.1
$firebase --version
4.2.1
$ firebase serve --only hosting
=== Serving from '/Users/marina/dev/friendlychat/web-start'...
i hosting[chat-web-623f5]: Serving hosting files from: ./
✔ hosting[chat-web-623f5]: Local server: http://localhost:5000
127.0.0.1 - - [06/Oct/2018:08:46:24 +0000] "GET / HTTP/1.1" 200 5623 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"
こんなかんじになった
6. Import and Configure Firebase
FirebaseのSDKを入れる
web-start/index.html
に変更を加える
下の方にココにいれてねという印があるのでそこにコピペ
<!-- Import and configure the Firebase SDK -->
<!-- These scripts are made available when the app is served or deployed on Firebase Hosting -->
<!-- If you do not want to serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup -->
<script src="/__/firebase/5.5.1/firebase-app.js"></script>
<script src="/__/firebase/5.5.1/firebase-auth.js"></script>
<script src="/__/firebase/5.5.1/firebase-database.js"></script>
<script src="/__/firebase/5.5.1/firebase-storage.js"></script>
<script src="/__/firebase/5.5.1/firebase-messaging.js"></script>
Configure Firebase Firebaseの設定
追加で下記のようにweb-start/index.html
を変更する
<!-- Import and configure the Firebase SDK -->
<!-- These scripts are made available when the app is served or deployed on Firebase Hosting -->
<!-- If you do not want to serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup -->
<script src="/__/firebase/5.5.1/firebase-app.js"></script>
<script src="/__/firebase/5.5.1/firebase-auth.js"></script>
<script src="/__/firebase/5.5.1/firebase-database.js"></script>
<script src="/__/firebase/5.5.1/firebase-storage.js"></script>
<script src="/__/firebase/5.5.1/firebase-messaging.js"></script>
<script src="/__/firebase/init.js"></script>
次に
http://localhost:5000/__/firebase/init.js
をブラウザ上で確認すると下記のような表示がでてくる
if (typeof firebase === 'undefined') throw new Error('hosting/init-error: Firebase SDK not detected. You must include it before /__/firebase/init.js');
firebase.initializeApp({
"apiKey": "qwertyuiop_asdfghjklzxcvbnm1234568_90",
"databaseURL": "https://●●●(自分で入れたプロジェクト名).firebaseio.com",
"storageBucket": "●●●(自分で入れたプロジェクト名).appspot.com",
"authDomain": "●●●(自分で入れたプロジェクト名).firebaseapp.com",
"messagingSenderId": "●●●(プロジェクトのid)",
"projectId": "●●●(プロジェクトのid)"
});
7. User Sign-in
Firebase SDKは、index.htmlファイルにインポートされて初期化されているため、使用できるようになりました。まず、Firebase Authを使用してユーザサインインを実装します。
web-start/scripts/main.js
の中で下記を書き込む
Authenticate your users with Google Sign-In
ログインについて
// Signs-in Friendly Chat.
function signIn() {
// TODO 1: Sign in Firebase with credential from the Google user.
// Signs-in Friendly Chat.
FriendlyChat.prototype.signIn = function() {
// Sign in Firebase using popup auth and Google as the identity provider.
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider);
};
};
サインアウトはこのように書く
function signOut() {
// TODO 2: Sign out of Firebase.
firebase.auth().signOut();
}
Track the auth state
UIを更新するには、ユーザーがサインインまたはサインアウトしているかどうかを確認する方法が必要です。
function initFirebaseAuth() {
// TODO 3: Initialize Firebase.
// Listen to auth state changes.
firebase.auth().onAuthStateChanged(authStateObserver);
}
Display the signed-in user information
ログインしたユーザーのプロフィール写真と名前をトップバーに表示します。
// Returns the signed-in user's profile Pic URL.
function getProfilePicUrl() {
// TODO 4: Return the user's profile pic URL.
return firebase.auth().currentUser.photoURL || '/images/profile_placeholder.png';
}
// Returns the signed-in user's display name.
function getUserName() {
// TODO 5: Return the user's display name.
return firebase.auth().currentUser.displayName;
}
// Returns true if a user is signed-in.
function isUserSignedIn() {
return !!firebase.auth().currentUser;
}
ここまできてチュートリアルではログイン・ログアウトボタンが右上にでてくると表示があったがでてこない
気になるエラー内容は下記
Warning: You're using Node.js v10.11.0 but Google Cloud Functions only supports v6.11.5.
なので下記の記事を参考に
Firebaseでfunctionが動作しないときはNode.jsのバージョンを確認すると良いかもしれない
node.js
のバージョンをv6.11.5.
に変更した
$ nodebrew ls
v6.11.5
v10.11.0
current: v10.11.0
$ nodebrew use v6.11.5
use v6.11.5
$ nodebrew ls
v6.11.5
v10.11.0
current: v6.11.5
バージョンの変更を行った
上記の記事によるとfirebase-toolsの再インストールが必要とのことだったので
$ npm -g install firebase-tools
をした
導入したバージョンは5.0.1
で無事にサインインボタンがでてくることを確認
$ firebase --version
5.0.1
8. Read messages
このjsonデータをfirebaseにアップロードする
https://github.com/firebase/friendlychat-web/blob/master/initial_messages.json
コマンドでもできるらしい
firebase database:set / ../initial_messages.json
Synchronize Messages
main.js
を書き換える
// Loads chat messages history and listens for upcoming ones.
function loadMessages() {
// Loads the last 12 messages and listen for new ones.
var callback = function(snap) {
var data = snap.val();
displayMessage(snap.key, data.name, data.text, data.profilePicUrl, data.imageUrl);
};
firebase.database().ref('/messages/').limitToLast(12).on('child_added', callback);
firebase.database().ref('/messages/').limitToLast(12).on('child_changed', callback);
}
9. Send Messages
main.js
を書き換える
// Saves a new message on the Firebase DB.
function saveMessage(messageText) {
// TODO 8: Push a new message to Firebase.
// Add a new message entry to the Firebase Database.
return firebase.database().ref('/messages/').push({
name: getUserName(),
text: messageText,
profilePicUrl: getProfilePicUrl()
}).catch(function(error) {
console.error('Error writing new message to Firebase Database', error);
});
}
ちなみにFirebase RealtimeDatabaseを確認するとこんなかんじになっていた
チュートリアル途中ですが、とりあえずここまでめも
参考にしたもの
https://qiita.com/saekis/items/d580d1c2ae4f32a6ae99
Firebaseでfunctionが動作しないときはNode.jsのバージョンを確認すると良いかもしれない
先人の知恵に感謝してます