今まで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です。
ログイン時(匿名)
ログイン時はauthの中にuidを始めとする各種情報が帰ってきます。