Engineer's Way

主にソフトウェア関連について色々書くブログです。

最新のMBaaS、Firebaseのチュートリアルをやってみた

 

Firebaseとは

FirebaseはGoogleが提供しているmBaaS。最近機能が強化され、かなり使えるようになった。
mBaasではあるものの、普通にPCのWebアプリケーションでも有効活用できる。

Firebaseの特徴

Firebaseは以下のような特徴がある。

  1. リアルタイムDBや認証、ストレージ、ホスティングなどの仕組みを提供してくれる。
  2. リアルタイムDBはオフライン → オンライン時に自動でデータ同期してくれる。しかも滅茶苦茶速い。
  3. スマホアプリのA/Bテストや色んな端末でのテストを支援してくれる。
  4. アプリのSEO対策やGAみたいな分析も可能。

チュートリアルの補足

今回、Firebaseのサンプルの一番下にあるFriendlyChatのWeb版をやってみた。 https://firebase.google.com/docs/samples/

英語で書かれているが、割と平易なのとコード例が多いので、英語が読めなくてもとりあえずなんとかなる。
以下に補足メモを書いておきます。


1. Overview

これから作ろうとしているFriendlyChatについての概要。 以下が必要だと書かれているので、もし無ければ準備する。

  1. WebStorm、AtomSublimeなどのIDE、もしくはテキストエディタ (私はVisual Studio Codeを使用)
  2. コンソール
  3. サンプルコード (次の章で取得)
  4. Chromeのようなブラウザ

2. Get the sample code

書かれている通りにgit cloneソースコードを持ってくる。
持ってきたリポジトリは以下のようなディレクトリ構成になっているはず。
以降の作業ではinitial_messages.jsonweb-startだけが必要になる。

friendlychat
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── android
├── android-start
├── initial_messages.json
├── ios
├── ios-starter
├── web
└── web-start

3. Import the starter app

friendlychat/web-startを予め用意していたIDEやエディタにインポートする。
別にvimなどを使っていても、以降の作業に支障はないので、その場合はこの章は読み飛ばす。

4. Create a Firebase project and Setup your app

  • Firebaseのセットアップ
    1. FIrebase Consoleにアクセスして「新規プロジェクトを作成」をクリックする。「国や地域」はもちろん日本で。
    2. プロジェクトを作ったら、それをクリックする。すると以下の画面になる。 f:id:matsnow:20161128011717p:plain
    3. 「ウェブアプリにFirebaseを追加」をクリック。スニペットが表示されるので、コピーボタンでコピーする。 f:id:matsnow:20161128011804p:plain
    4. コピーした内容を、「web-start/index.html」の最下部に貼り付ける。(以下の場所)
<script src="https://www.gstatic.com/firebasejs/3.5.1/firebase.js"></script>
<!-- ***********************************************************************************************************************
* TODO(DEVELOPER): Paste the initialization snippet from: Firebase Console > Overview > Add Firebase to your web app. *
*********************************************************************************************************************** -->
<script src="scripts/main.js"></script>


  • アプリ認証の設定
    1. 次はGoogleアカウントの認証を有効にするため、左のメニューから「Authentication」-「ログイン方法」を選択する。 f:id:matsnow:20161128012006p:plain
    2. プロバイダの「Google」をクリックすると以下の表示になるので、「有効にする」とした上で「保存」 f:id:matsnow:20161128012019p:plain

ここまでで4章は完了。

5. Install the Firebase Command Line Interface

書かれている通りのコマンドを実行する。 以下のような出力が得られるはず。

% firebase login
? Allow Firebase to collect anonymous CLI usage information? Yes  // <=== ここはYesで答える。

Visit this URL on any device to log in:
https://accounts.google.com/o/oauth2/auth?client_id=563584335869-fgrhgmd47bqnekij5i8b5pr03ho849e6.apps.googleusercontent.com&scope=email%20openid%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloudplatformprojects.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Ffirebase&response_type=code&state=363409070&redirect_uri=http%3A%2F%2Flocalhost%3A9005

Waiting for authentication...

✔  Success! Logged in as matsnow@outlook.jp

% firebase use --add
? Which project do you want to add? friendlychat-108fb
? What alias do you want to use for this project? (e.g. staging) staging

Created alias staging for friendlychat-108fb.
Now using alias staging (friendlychat-108fb)

6. Run the starter app

firebase serveコマンドを実行すると、http://localhost:5000で、とりあえずアプリの画面が見えるようになる。 (まだ何もできない状態)

% firebase serve
Starting Firebase development server...

Project Directory: /Users/XXXX/develop/projects/firebase_sample/friendlychat/web-start
Public Directory: ./

Server listening at: http://localhost:5000

7. User Sign-in

もともとこうなっているので、

// Sets up shortcuts to Firebase features and initiate firebase auth.
FriendlyChat.prototype.initFirebase = function() {
  // TODO(DEVELOPER): Initialize Firebase.
};

↓ こんな感じで書き換える。

// Sets up shortcuts to Firebase features and initiate firebase auth.
FriendlyChat.prototype.initFirebase = function() {
    // TODO(DEVELOPER): Initialize Firebase.
    this.auth = firebase.auth();
    this.database = firebase.database();
    this.storage = firebase.storage();
    this.auth.onAuthStateChanged(this.onAuthStateChanged.bind(this));
};

onAuthStateChanged関数はnullの部分を書き換える。

FriendlyChat.prototype.onAuthStateChanged = function(user) {
    if (user) { // User is signed in!
        // Get profile pic and user's name from the Firebase user object.
        var profilePicUrl = null; // TODO(DEVELOPER): Get profile pic.
        var userName = null; // TODO(DEVELOPER): Get user's name.

FriendlyChat.prototype.onAuthStateChanged = function(user) {
    if (user) { // User is signed in!
        // Get profile pic and user's name from the Firebase user object.
        var profilePicUrl = user.photoURL; // TODO(DEVELOPER): Get profile pic.
        var userName = user.displayName; // TODO(DEVELOPER): Get user's name

この時点でlocalhost:5000にアクセスすると、ログインだけはできる状態。

8. Read messages

web-startディレクトリと同じ階層に置かれているinitial_messages.jsonをインポートする。

  1. 左メニューから「Database」を選択する。 f:id:matsnow:20161128013309p:plain
  2. 右の「:」をクリックして「JSONをインポート」を選ぶ。 f:id:matsnow:20161128013317p:plain
  3. インポートファイルの選択ダイアログが開くので、initial_messages.jsonを選ぶ。
    f:id:matsnow:20161128013432p:plain:w400 f:id:matsnow:20161128013441p:plain:w300
    4.「データは正常にインポートされました」と出て以下の状態になる。 f:id:matsnow:20161128013537p:plain:h400

そのあと、main.jsを指示にしたがって書き換えると、localhost:5000でインポートしたJSONの内容が表示される。
この時点では読めるだけで、書き込みなどはできない。

9. Database Security Rules [Optional]

リアルタイムデータベースの読み書き権限を変えたければdatabase-rules.jsonを変更する必要があることが書かれているが、特に読み飛ばしても問題なし。

10. Send Messages

11. Send Images

main.jsを指示通りに書き換えるだけ。
それでチャットメッセージの送信と画像のアップロードができるようになる。

12. Storage Security Rules [Optional]

オンラインストレージの権限の読み書き権限を変えたければstorage.rulesを作成する必要があることが書かれているが、読み飛ばしても問題なし。

13. Deploy your app using Firebase static hosting

書かれている通り、firebase deployを実行すると、数秒でアップロードが完了する。 「Hosting URL」に書かれているURLで、インターネット上のどこからでもアクセスできる状態になっている。

% firebase deploy

=== Deploying to 'friendlychat-108fb'...

i  deploying database, hosting
✔  database: rules ready to deploy.
i  hosting: preparing ./ directory for upload...
Uploading: [                                        ] 0%✔  hosting: ./ folder uploaded successfully
✔  hosting: 11 files uploaded successfully
i  starting release process (may take several minutes)...

✔  Deploy complete!

Project Console: https://console.firebase.google.com/project/friendlychat-108fb/overview
Hosting URL: https://friendlychat-108fb.firebaseapp.com

以上まででチュートリアルが完了。 このように、ちゃんとネット上へのデプロイまで出来てしまっている。
https://friendlychat-108fb.firebaseapp.com/


もうサーバ側のありきたりな機能はFirebaseを使えば簡単にできるかな、という印象。
今後プロダクションでも使っていきたい。