9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Cloud Functions の Slack 通知に Cloud Firestore データへの直リンクを貼る

Last updated at Posted at 2018-02-17

Cloud Functions でエラーが起きた時に Slack に通知を飛ばしたいですね。
その時、エラーが発生したデータに Cloud Firestore 管理画面の直リンクがあると便利です。

というわけで実装してみましょう。

Firestore の URL をみる

このような URL があったとして、これは 4 つに分解できます。

  • https://console.firebase.google.com/u/0/project/
    • どの Project も同じ、 firebase の base_url
  • sandbox-hoge/
    • project_id
    • functions.config().firebase.projectId で取得できる
  • /database/firestore/data~2F
    • Database の firestore を表す部分
  • user~2F08UQUZSbDw7VdlVTRwpU
    • データの path を表す部分
    • DocumentReference.path で取得できる、 /~2F に置換する

コードで作り出す

こんな感じになります。

let baseURL = 'https://console.firebase.google.com/u/0/project/'
baseURL += (functions.config().firebase.projectId || '/projectId') + '/database/firestore/data~2F'
const ref = admin.firestore().doc('user/08UQUZSbDw7VdlVTRwpU').path
const path = ref.replace(/\//g, '~2F')
const firestoreURL =  baseURL + path

console.log(firestoreURL)
// => https://console.firebase.google.com/u/0/project/sandbox-329fc/database/firestore/data~2Fuser~2F08UQUZSbDw7VdlVTRwpU

この URL を slack に投げるとエラーが起きた時に直リンクでデータへ飛ぶことができます。

ライブラリ

というわけで、 Firestore へのリンクを自動で貼ってくれる Slack クライアントライブラリを作りました。

starhoshi/fire-slack

使い方

index.[js|ts] で初期設定をします。 TypeScript の実装例ですが、 JS で使う場合は脳内変換してください。

import * as Slack from 'fire-slack'

Slack.initialize(
    <admin.AppOptions>functions.config().firebase,
    'https://your-incoming-webhook-url',
    { channel: 'default_channel', iconEmoji: ':default:', username: 'default_usern' } // optional
)

送信はこれだけ。

// エラーはあれば指定する
Slack.send({webhook: {text: 'message'}, ref: reference, error: error}

こんな感じでデータへのリンクと project_id を自動で表示してくれます。

screenshot.png (413×199)

webhook のパラメータは TypeScript で型安全に Slack の Incoming Webhook を扱う - Qiita で書いた、 IncomingWebhookOptions 型がそのまま使えます。

実際の Cloud Functions のサンプル

現実世界ではこのように使うことを想定しています、エラーが起きた時のサンプルです。

export const orderPaymentRequested = functions.firestore
    .document(`sampleorder/{orderID}`).onCreate(async event => {

  try {
    return event.data.ref.update({ name: 'new name' })
  } catch (error) {
    // ref and error are optional.
    await Slack.send({
      webhook: { text: 'An error occurred!' },
      ref: event.data.ref,
      error: error
    })
    return Promise.reject(error)
  }
})

おわり

Cloud Functions で Firestore やっている人は使ってみてください :pray:
starhoshi/fire-slack

9
4
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
9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?