> For the complete documentation index, see [llms.txt](https://ja.docs.monaca.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ja.docs.monaca.io/migration-guide/nifcloud/sukuriputo/sanpuru2postsanpuru.md).

# サンプル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のユーザー管理機能とは異なります。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ja.docs.monaca.io/migration-guide/nifcloud/sukuriputo/sanpuru2postsanpuru.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
