gorillabbit / cyclic_todo

0 stars 0 forks source link

APIを作り、ChatGPTや、GASから操作できるようにする #71

Open gorillabbit opened 1 month ago

gorillabbit commented 1 month ago

Firebase Functionsの設定

初期化が完了すると、functionsフォルダが作成されます。このフォルダに移動し、TypeScript関連のパッケージをインストールします。

cd functions
npm install firebase-admin firebase-functions
npm install --save-dev typescript @types/node

TypeScriptの設定 tsconfig.jsonファイルを設定します。

{
  "compilerOptions": {
    "lib": ["es6", "dom"],
    "module": "commonjs",
    "noImplicitReturns": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es6"
  },
  "compileOnSave": true,
  "include": ["src"]
}

APIの作成 src/index.tsを作成し、以下のコードを追加します。

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp();
const db = admin.firestore();

export const addData = functions.https.onRequest(async (req, res) => {
  if (req.method !== 'POST') {
    return res.status(405).send('Method Not Allowed');
  }

  const data = req.body;

  try {
    const docRef = await db.collection('your-collection-name').add(data);
    return res.status(200).send(`Document added with ID: ${docRef.id}`);
  } catch (error) {
    return res.status(500).send(`Error adding document: ${error}`);
  }
});

APIをデプロイします。

npm run deploy

デプロイが完了すると、APIのURLが表示されます。このURLを使用して、外部からデータを追加することができます。

APIのテスト PostmanやcURLなどを使用して、APIをテストします。以下はcURLを使用した例です。

curl -X POST https://<your-region>-<your-project-id>.cloudfunctions.net/addData \
-H "Content-Type: application/json" \
-d '{
  "field1": "value1",
  "field2": "value2"
}'
gorillabbit commented 1 month ago
// データを取得するAPI
export const getData = functions.https.onRequest(async (req, res) => {
  if (req.method !== 'GET') {
    return res.status(405).send('Method Not Allowed');
  }

  try {
    const snapshot = await db.collection('your-collection-name').get();
    const data = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
    return res.status(200).json(data);
  } catch (error) {
    return res.status(500).send(`Error getting documents: ${error}`);
  }
});
gorillabbit commented 1 month ago

留意事項:JSONで取得するので、それをうまく加工する。 JSONで渡ってくるので、それをfirestorenに収納するまでにうまく加工する。

gorillabbit commented 1 month ago

スマホのウィジェットで、chatgptにレシート画像を渡す chatgptが画像を読み込み、JSON形式にする。 変換結果をスマホアプリで表示する。 スマホアプリで承認or破棄or再生成。 承認されたら、chatgptからAPIで家計簿に記入する。