# サンプル2（POSTサンプル）

NCMB (ニフクラ mobile backend) のPOSTメソッドのサンプルを、Firebase FunctionsとFirebase Firestoreを使って実装する方法について解説しています。

{% embed url="<https://mbaas.nifcloud.com/doc/current/script/sample_javascript.html#POST%20%E3%82%B5%E3%83%B3%E3%83%97%E3%83%AB>" %}

## 概要

* **目的**: NCMBでのPOSTメソッドを用いたデータ保存のサンプルを、Firebase Functionsでの実装に変換。
* **動作**: Firestoreの `Item` コレクションにデータを保存。

## Firebase Functionsのコード

### **機能**

* **認証**: 指定された `username` と `password` で認証を行い、条件を満たす場合のみデータの保存を許可。
* **データの保存**: `body` に含まれるデータをFirestoreに保存。

### **コード例**

```javascript
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;
```

### **解説**

* **認証の取り扱い**:&#x20;
  * Firebase Functionsの `onCall` ではユーザー固有の情報をヘッダに含めることができません。そのため、`data` オブジェクト内に `header` と `body` を設定し、`header` に認証情報を、`body` に保存するデータを記述しています。
* **新規ドキュメント生成**:&#x20;
  * このサンプルでは常に新しいドキュメントが生成されます。既存ドキュメントの更新を行いたい場合は、コードの改修が必要です。
* **HttpsErrorについて**
  * Firebaseの `HttpsError` の詳細は[こちら](https://firebase.google.com/docs/reference/node/firebase.functions.HttpsError)を参照してください。

***

## アプリ側のコード

### **機能**

* `post_data` 関数を呼び出し、Firestoreにデータを保存。

### **コード例**

```javascript

    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);
    });

```

### **解説**

* **引数の構造**:&#x20;
  * サーバー側の `post_data` 関数には、`header`（認証情報）と `body`（保存するデータ）を含むオブジェクトを引数として渡します。
* **認証情報**:&#x20;
  * ここで使用される `username` と `password` はFirebase Functions側でハードコードされたものであり、Firebaseのユーザー管理機能とは異なります。
