Help us understand the problem. What is going on with this article?

cloud functionsでfirestoreを使う

alt
結論から言うと、firebaseのcloud functionsでfirestoreを使うには、
firebase-admin
というサードパーティライブラリが必要。
cloud functions自身には、httpリクエストからfireStoreのデータを読む術はない。
(ただしcloud function単体でfireStoreトリガーで、fireStoreクエリを発行することは出来る。)

firebase initでcloud functionを作成した後

npm i firebase-admin --save

以下のように使う

const functions = require('firebase-functions')
// cloud functionでfirestoreを使うのに必要な設定は以下の2行
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase)

// データベースの参照を作成
var fireStore = admin.firestore()

exports.helloWorld = functions.https.onRequest((request, response) => {
  // 動作確認のため適当なデータをデータベースに保存
  var citiesRef = fireStore.collection('cities');
  citiesRef.doc('SF').set({
    name: 'San Francisco', state: 'CA', country: 'USA',
    capital: false, population: 860000 })

  var cityRef = fireStore.collection('cities').doc('SF')
  cityRef.get()
  .then(doc => {
    if (!doc.exists) {
      response.send('No such document!')
    } else {
      response.send(doc.data())
      }
    })
    .catch(err => {
      response.send('not found')
    })
})

今回作成したAPIにgetすると、firestoreにcityが書き込まれ、書き込まれた結果が帰ってくる。
cloud function単体ではfirestoreと連携出来ず、firebase-adminと連携して使う必要がある。

firebase serveと打つと、ローカルでcloud functionsを動作確認できるが、ローカル環境でも、firestoreは問題なく使えた。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away