FirestoreをRubyのgoogle-api-clientから叩く

そもそもRubyからFirestoreを叩きたい理由

  • FirestoreはフロントエンドからWriteできるけど、実装の複雑さを避けるためにフロントエンドからはWriteしないで、 チャットのAPI経由でFirestoreに対してWriteを行う機構が必要だったため。*1 *2

方法

  1. とにかくgoogle-api-clientをインストールする
  2. サービスアカウントの認証JSONKeyを取得する
  3. サービスアカウントの権限に追加すればOK

ここまでの方法は調べればいくらでもあるので、他の記事等を参考にして進めて欲しい。 ちょっと画面がややこしいので、この部分を含めても解説しても良かった気がするが時間がないので、また追記します。 以降は実際にコードとしてどう書けばいいか、というのを雑に並べておきます。

require 'google/apis/firestore_v1beta1'
SCOPE = ['https://www.googleapis.com/auth/datastore', 'https://www.googleapis.com/auth/cloud-platform']
PROJECT_ROOT_PATH = "projects/hoge-project/databases/(default)"
client = Google::Apis::FirestoreV1beta1::FirestoreService.new
client.authorization = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open("#{Rails.root}/config/hogehoge.json"),
  scope: SCOPE
)

message = Message.first

# firestoreにドキュメントを追加
def push_firestore(message)
  client.create_project_database_document_document("#{PROJECT_ROOT_PATH}/documents", 'messages', message_doc(message))
end

# firestoreの指定したドキュメントを削除
def destroy_firestore(firestore_message_id)
  client.delete_project_database_document("#{PROJECT_ROOT_PATH}/documents/#{firestore_message_id}")
end

# firestoreのフィールド設定
def message_doc(message)
  doc = Google::Apis::FirestoreV1beta1::Document.new()
  doc.fields = {
     "id": {
        integer_value: message.id
     },
     "content": {
        string_value: message.content
     },
     "created_at": {
        timestamp_value: message.created_at.rfc3339
     },
     "updated_at": {
       timestamp_value: message.updated_at.rfc3339
     }
  }
  doc
end

これでとりあえずgoogle-api-client経由でドキュメントの作成と削除ができる状態になった。 ほかにもたくさんFirestoreのAPIがあるみたいなので、それはまた今後眺めてみることにする。

感想

  • 特にexampleのコードとかなかったし、とにかくわかりづらい印象だった。Gemの中身をちゃんと読みまないと絶対にわからん。
  • 各項目に対して型を設定するのがいちいち面倒、ちゃんと使う分には何某かのうっすいラッパーくらいあっていいかも。

参考リンク

*1:あとは私がサーバサイドエンジニアだったのでというのも理由ひとつ

*2:参考: https://speakerdeck.com/sota1235/realtime-messaging-with-firebase-number-phpcon2017