サンプル2(POSTサンプル)
NCMB (ニフクラ mobile backend) のPOSTメソッドのサンプルを、Firebase FunctionsとFirebase Firestoreを使って実装する方法について解説しています。
概要
目的: NCMBでのPOSTメソッドを用いたデータ保存のサンプルを、Firebase Functionsでの実装に変換。
動作: Firestoreの
Item
コレクションにデータを保存。
Firebase Functionsのコード
機能
認証: 指定された
username
とpassword
で認証を行い、条件を満たす場合のみデータの保存を許可。データの保存:
body
に含まれるデータをFirestoreに保存。
コード例
const post_data = functions.https.onCall(async (data, context) => {
// ユーザー認証
const username = data.header.username;
const password = data.header.password;
if (username != 'admin' || password != 'AA00XX11') {
throw new functions.https.HttpsError('unauthenticated', 'The function must be called while authenticated.');
}
// データの保存
const body = data.body;
return admin.firestore().collection('Item').add(body)
.then(docRef => {
return { message: `Document added with ID: ${docRef.id}` };
})
.catch(error => {
throw new functions.https.HttpsError('internal', `Error adding document: ${error}`);
});
});
exports.post_data = post_data;
解説
認証の取り扱い:
Firebase Functionsの
onCall
ではユーザー固有の情報をヘッダに含めることができません。そのため、data
オブジェクト内にheader
とbody
を設定し、header
に認証情報を、body
に保存するデータを記述しています。
新規ドキュメント生成:
このサンプルでは常に新しいドキュメントが生成されます。既存ドキュメントの更新を行いたい場合は、コードの改修が必要です。
HttpsErrorについて
Firebaseの
HttpsError
の詳細はこちらを参照してください。
アプリ側のコード
機能
post_data
関数を呼び出し、Firestoreにデータを保存。
コード例
const post_data = httpsCallable(functions, 'post_data');
post_data({ 'header' : {
'username': 'admin',
'password': 'AA00XX11'
},
'body' : {
'name': 'ぶどう'
}
}).then((result) => {
log(result.data);
}).catch((error) => {
log(error);
});
解説
引数の構造:
サーバー側の
post_data
関数には、header
(認証情報)とbody
(保存するデータ)を含むオブジェクトを引数として渡します。
認証情報:
ここで使用される
username
とpassword
はFirebase Functions側でハードコードされたものであり、Firebaseのユーザー管理機能とは異なります。
最終更新
役に立ちましたか?