48
25

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.

functions.https.onCallを試してみる

Posted at

今までFunctionsのhttps経由の呼び出しといえばhttps.onRequest(通常のWebAPI)でしたが、https.onCallというのも使えるようになりました(だいぶ前ですが)。

この呼出は基本SDKからになるため呼び出し元をある程度制限できます。また認証情報も保持しているためAPI側で認証情報を取得し、処理を分岐させたりできます。

簡単に見てみます。

Functions側

onCallはdataとcontextの2つの引数を取るようで、

  • data: 送られてきたパラメータ
  • context:認証情報等

が入っているみたい。とりあえず内容を確認するため下記のようなコードを書いてみました。

const functions = require('firebase-functions');

//onCall
exports.helloWorld = functions.https.onCall((data, context) => {
    return { data: data, auth: context.auth }
});

呼び出し側

クライアントは何でもいいのですが、こなれたReactで下記のように書いてみました。jsならだいたい同じでしょう。
ボタンをクリックしたらonCallします。

App.js
import React from 'react';
import './App.css';

import firebase from './Firebase';
import { sign } from 'crypto';

class App extends React.Component {

  handlePush = async () => {

    // await firebase.auth().signInAnonymously();
    // await firebase.auth().signOut();
	
	//functionsを使う
    const functions = firebase.functions();
    //参照?を取得
    const func = functions.httpsCallable("helloWorld");
    //引数を付けて呼び出し
    func({ name: 'hoge' }).then(res => {
      console.log(res);
    }).catch(e => {
      console.log(e);
    })
  }

  render() {
    return (
      <div>
        <p>App</p>
        <button onClick={this.handlePush}>push</button>
      </div>
    );
  }
}

export default App;

結果

非ログイン時

dataの中にname:"hoge"が確認できます。authはnullです。

スクリーンショット 2019-12-08 17.02.54.png

ログイン時(匿名)

ログイン時はauthの中にuidを始めとする各種情報が帰ってきます。

スクリーンショット 2019-12-08 17.02.02.png

48
25
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
48
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?