よしたく blog

ほぼ週刊で記事を書いています

Cloud Firestoreを触ってみた

f:id:yoshitaku_jp:20181128144942p:plain

この記事は、yoshitaku_jpの1人 Advent Calendar 2018 - Adventar20日目の記事です。

目次

tl;dr

  • Cloud Firestoreを触ってみた
  • データの挿入と削除をやってみた

先日RealtimeDatabaseを触りましたが、今回はCloud Firestoreを触ってみます。

201812/20日現在、ベータ版となっていますが今後RealtimeDatabaseから置き換わっていくのかなと思っています。

yoshitaku-jp.hatenablog.com

準備

alligator.io

自分で試行錯誤していたのですが全然うまくいかなかったので、上記サイトで公開されていたチュートリアルを実施してみました。

  • ディレクトリの構成
  • Todo.vueのソース
  • router/index.jsのソース

Vue-firestoreのインストール

今回はこちらを使います。

github.com

自分は前回からの続きでしたのでnpm install vue-firestore --saveを実行しました。

今回がはじめての方はnpm install @firebase/app @firebase/firestore vue-firestore --saveを実行しましょう。

ディレクトリ構成

今回のディレクトリ構成は下記の通りです。Reptile.vueを適切に読み込めれば、どのような構成でも大丈夫だと思います。

tree -I "node_modules|test|assets|config|static|README.md|build" -L 3
.
├── index.html
├── package-lock.json
├── package.json
└── src
    ├── App.vue
    ├── components
    │   ├── HelloWorld.vue
    │   ├── Reptile.vue
    │   ├── Signin.vue
    │   ├── Signup.vue
    │   └── Todo.vue
    ├── main.js
    └── router
        └── index.js

main.js

全体

import Vue from 'vue'
import App from './App'
import router from './router'
import firebase from 'firebase'
import VueFirestore from 'vue-firestore'

Vue.config.productionTip = false

// Initialize Firebase
//Firebaseの値は置き換えましょう
var config = {
  apiKey: process.env.NODE_API_KEY,
  authDomain: process.env.NODE_AUTH_DOMAIN,
  databaseURL: process.env.NODE_DATABASE_URL,
  projectId: process.env.NODE_PROJECT_ID,
  storageBucket: process.env.NODE_STORAGE_BUCKET,
  messagingSenderId: process.env.NODE_MESSAGING_SENDER_ID
}
const firebaseApp = firebase.initializeApp(config)

const db = firebaseApp.firestore()
db.settings({timestampsInSnapshots: true})
Vue.use(VueFirestore)

export default db

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

Firestoreの読み込み

Firestoreを読み込みます。db.settings({timestampsInSnapshots: true}) この設定はないといけないようです。

const db = firebaseApp.firestore()
db.settings({timestampsInSnapshots: true})
Vue.use(VueFirestore)

Reptile.vueのソースコード

<template>
  <div id="app">
    <div>
      <input type="text"
        v-model="newReptile"
        @keyup.enter="addReptile">
      <button  @click="addReptile">
        Add Reptile
      </button>
    </div>
    <ul class="reptileList">
      <li v-for="reptile in reptiles"  :key="reptile.id">
        {{ reptile.name }} -
        <button @click="deleteReptile(reptile)">
          Remove
        </button>
      </li>
    </ul>
  </div>
</template>

<script>
import db from '../main'

export default {
  name: 'app',
  data () {
    return {
      reptiles: [],
      newReptile: ''
    }
  },
  firestore () {
    return {
      reptiles: db.collection('reptiles')
    }
  },
  methods: {
    addReptile: function () {
      this.$firestore.reptiles.add(
        {
          name: this.newReptile,
          timestamp: new Date()
        }
      )
      this.newReptile = ''
    },
    deleteReptile: function (reptile) {
      this.$firestore.reptiles.doc(reptile['.key']).delete()
    }
  }
}
</script>

<style>
.reptileList {
  list-style: none;
}
</style>

firestore ()

Cloud Firestore上の、reptilesコレクションから値を持ってきています。Vue側のreptiles変数にいれて、表示しています。

  firestore () {
    return {
      reptiles: db.collection('reptiles')
    }
  },

methods/createTodo、methods/deleteTodo

この辺はあまり難しいことをしていないです。

  methods: {
    createTodo: function (newTodoName) {
      if (newTodoName === '') { return }
      this.todoRef.push({
        name: this.newTodoName
      })
      this.newTodoName = ''
    },
    deleteTodo: function (todo) {
      this.todoRef.child(todo).remove()
    }
  }

デモ

f:id:yoshitaku_jp:20181221085118g:plain

まとめ

  • RealtimeDatabaseとは違う実装なので、違いをまとめていきたい
  • 個人的にはコンソール画面での編集はCloud Firestoreが使いやすいと感じている

yoshitaku-jp.hatenablog.com