LoginSignup
1
1

More than 5 years have passed since last update.

Firebase でアプリケーション作ったら functionsで結構ハマったのでメモ

Last updated at Posted at 2019-05-08

概要

Firebaseの勉強をしていたのでまとめ
hosting + authenticationはいろいろやっている人が多かったけどfunctionsも使っている人が少ない印象だったので。
ただ、ローカル起動はわからん。。。教えてくれる人募集。。。

対象

  • nuxtとfirebase hosting + authentication を完全に理解した人
  • functions とかわからんし、という人

hosting + authentications + nuxt

このあたり画像つきで書いてくれている人が多いので割愛
例えば: https://qiita.com/potato4d/items/cfddeb8732fec63cb29c

functions

https://firebase.google.com/docs/functions/get-started?hl=ja
のとおりやればいいらしいが、ちょっとハマったのでとりあえずやったことを書いてます。

functionsをinstallする

firebase init functions

デフォルトのリージョンがusになっていたので東京に修正する

index.ts
export const helloworld = functions
    .region('asia-northeast1')
    .https.onRequest

onRequestだとcrosでエラーと言われるので、 https://qiita.com/qrusadorz/items/40234ac0b5c5c2315cad
を読んで納得した後onCallに変更する(ドキュメントを見ててもよくわからなかった人

index.ts
import * as functions from 'firebase-functions';
import { CallableContext } from 'firebase-functions/lib/providers/https';

export const helloworld = functions
    .region('asia-northeast1')
    .https.onCall((data, context: CallableContext) => {
      if (!context.auth) {
        // permission-deniedで403を返したり
        throw new functions.https.HttpsError('permission-denied', '認証してないから使えません!');
      }
      if (!data.name) {
        // invalid-argumentで400を返したりする
        throw new functions.https.HttpsError('invalid-argument', 'nameは必須です!');
      }
      // なんかいろいろやって200でオブジェクトを返却する
      // nameはclientから送られてくるデータ
      const greet = `hello ${data.name}`;
      return {
        greet
      }
    })

で持って使用するnodeのバージョンを10(まだGAじゃない)に変更しようとしたが、実際に使おうとしたら何故か401が返ってくる
Issue: https://github.com/firebase/firebase-functions/issues/432
そのためバージョンは8にする

package.json
{
  "name": "functions",
  "engines": {
    "node": "8"
  }
}

nuxt側で対象のfunctionを呼ぶようにする.ただリージョンは指定する. これしないとcorsでナンタラカンタラ言われる.
デフォルトのusを見ているので、おそらく存在しないから怒られているんだと推測

認証後のページ
<template>
  <section class="container">
    <div>
      <div>
        <p><input type="text" v-model="name" placeholder="名前">{{name}}</p>
        <p><button @click="call">call</button></p>
        <p>{{greet}}</p>
      </div>
    </div>
  </section>
</template>

<script>
import firebase from '~/plugins/firebase';
export default {
  data() {
    return {
      name: '',
      greet: '',
      client: firebase.app().functions("asia-northeast1").httpsCallable("helloworld")
    }
  },
  methods: {
    call() {
      this.client({
        name: this.name
      }).then(result => {
        this.greet = result.data.greet;
      })
    }
  }
}
</script>

まとめ

いろいろまとめたらfunctionsって簡単につかえますねー。って感覚がある。この記事の意義、、、なんやねん。

1
1
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
1