LoginSignup
1
2

More than 1 year has passed since last update.

cloud functionsの関数トリガーで非同期処理 async/awaitを使う

Posted at

はじめに

cloud functionsでドキュメントの数をカウントする処理があるのですが、、たまに回数がズレてたり間違ったり、正常に動作していない時があります:sweat_smile:

どこかしらで処理が終わっているのか、何かしらのエラーがたまに発生しているのか、具体的な理由はわかりませんが、とりあえず非同期にしてみることにしました

ドキュメントの数をカウントするFunctionで、async/awaitを使う

ただ、cloud functionsの関数トリガー(onWriteとか)でasync/awaitを使う場合、どうやって書けばいいのか分からず検索しまくりました。。。

👆公式のサンプルを参考に実装しました!

index.ts
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
const db = admin.firestore();

exports.countEvents = functions.region('asia-northeast1').firestore
  .document('users/{userId}/events/{eventId}')
  .onWrite(async (change, context) => {

    try {
      const userId = context.params.userId;
      const FieldValue = admin.firestore.FieldValue;
      const countsRef = db.collection('users').doc(userId);    

      if (!change.before.exists) {
        // 登録時に件数をインクリメント
        await countsRef.update({ eventCount: FieldValue.increment(1) });
        return
      } else if (change.before.exists && !change.after.exists) {
        // 削除時に件数をデクリメント
        await countsRef.update({ eventCount: FieldValue.increment(-1) });
        return
      }
        return null;
    } catch (error) {
        console.error(`Fatal error ${error}`);
        return null;
      }
  });

asynconWriteのカッコに、awaitはその後のドキュメントをカウントする処理のところで使用。

async/awaitの使い方に関する詳細は下記を参考に!

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2