2022年7月12日火曜日

Google functions とdatastore

App Engineからfunctionsに乗り換えるためにテスト。 調べてみるといろいろと新しいシステムデータベースはあるのだけど、 結局われわれの用途にはdatastoreが一番適しているという結論。つまらん。

datastoreの認証がどうなっているのか心配だったのだが、GCPのプロジェクト内では 認証が不要っぽい感じ。逆にプロジェクト外部からは触れなさそう。 この辺、AWSのIAM Roleですべての認証を切り分けていくというのとは好対照だな。

このブログを参考に試してみた。 データはdatastoreのWebサイトから直接データをいれていて、それをfunctionsから 取りに行く形。

const functions = require('@google-cloud/functions-framework');
const Datastore = require('@google-cloud/datastore');
const datastore = Datastore();

functions.http('helloHttp', (req, res) => {
   const key = datastore.key([req.body.kind, req.body.key]);
   console.log(req.body.kind, req.body.key);
   return datastore.get(key)
     .then(([entity]) => {
       res.status(200).send(entity);
     });
});
jsonをアップロードすると、自動的にパースしてくれるのね。便利。 package.jsonでdatastoreを参照する。最新版がいくつなのかわからないが、1.0.0だと 動かなかった。
{
  "dependencies": {
    "@google-cloud/functions-framework": "^2.1.0",
    "@google-cloud/datastore": "1.4.1"
  }
}
アクセスはこんなかんじ。謎の文字列は、datastore上のentityのID。
% curl -H "Content-type: application/json" -X POST -d '{"kind":"User", "key": 5634161670881280}' https://xxxx.xxxxx.x.run.app/

{"name":"john"}
返り値もjsonになってるけど、誰がやってくれてるんだろう。。不思議。

0 件のコメント: