4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

CloudFlareというサービスを試す(3) Workers KV

Last updated at Posted at 2022-05-18

はじめに

↑の続き。

アプリケーションを作るにあたって、情報の保存が必要になるのでWorkers KVを試す。
KVは名前の通りkey-valueで情報を保存できる機能。

結論

Workers KV の読み込みと書き込みができることを確認できた。
コーディングは非常に簡単。
Cacheとか有効期限も付けれるようだけど、その辺は今後の課題とする。

詳細

Workersのプロジェクトを作成

C:\donraku\cloudflare>wrangler init third-app
 ⛅️ wrangler 2.0.5
-------------------
Using npm as package manager.
✨ Created third-app\wrangler.toml
Would you like to use git to manage this Worker? (y/n) <--y
✨ Initialized git repository at third-app
Would you like to use TypeScript? (y/n) <--n
Would you like to create a Worker at third-app\src\index.js? (y/n) <--y
✨ Created third-app\src\index.js

To start developing your Worker, run `npx wrangler dev`
To publish your Worker to the Internet, run `npx wrangler publish`

initで初期設定。

image.png
初期状態はこんな感じ。
tomlに「main = "src/index.js"」も入ってる。前回は入ってなかったのはやり直したせいかな。。。

KVの名前空間を作成

C:\donraku\cloudflare\third-app>wrangler kv:namespace create MY_KV
 ⛅️ wrangler 2.0.5
-------------------
🌀 Creating namespace with title "third-app-MY_KV"
✨ Success!
Add the following to your configuration file in your kv_namespaces array:
{ binding = "MY_KV", id = "89de2f7402ab49c8a3dd712bcf86****" }

C:\donraku\cloudflare\third-app>wrangler kv:namespace create MY_KV --preview
 ⛅️ wrangler 2.0.5
-------------------
🌀 Creating namespace with title "third-app-MY_KV_preview"
✨ Success!
Add the following to your configuration file in your kv_namespaces array:
{ binding = "MY_KV", preview_id = "9fa02ed329a945e4bd11797cbcbc****" }

C:\donraku\cloudflare\third-app>wrangler kv:namespace list
[
  {
    "id": "89de2f7402ab49c8a3dd712bcf86****",
    "title": "third-app-MY_KV",
    "supports_url_encoding": true
  },
  {
    "id": "9fa02ed329a945e4bd11797cbcbc****",
    "title": "third-app-MY_KV_preview",
    "supports_url_encoding": true
  }
]
※念のためIDをマスキング

①商用の名前空間を作成。
②開発用の名前空間を作成。
リストで確認。
①と②を作っておくのが良いらしい。

image.png
ダッシュボードでもできているのを確認。

wrangler.toml
name = "third-app"
main = "src/index.js"
compatibility_date = "2022-05-18"

kv_namespaces = [
    { binding = "MY_KV", id = "89de2f7402ab49c8a3dd712bcf86****", preview_id = "9fa02ed329a945e4bd11797cbcbc****" }
]

tomlファイルに kv_namespaces の設定を追加。
これでjsの中で"MY_KV"で使えるようになる。
長いからと思って適当に改行するとエラーになるので注意。

Workers KV の読み書きを実装

index.js
addEventListener("fetch", (event) => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const { pathname } = new URL(request.url);

  //読み込み(/get)
  if (pathname.startsWith("/get")) {
    const value = await MY_KV.get("first-key");
    if (value === null) {
      return new Response("Value not found", { status: 404 });
    }
    return new Response(value);
  }

  //書き込み(/put/xxx)
  if (pathname.startsWith("/put")) {
    const value = pathname.split("/")[2];
    await MY_KV.put("first-key", value);
    return new Response(`put success! ${value}`);
  }

  //その他
  return new Response("Hello Third-app!!");
}

↑などを参考にしてソースを作成。

初期状態だと「export default」で始まるモジュールの形式だけど、ほとんどのサンプルの書き方が対応してないので「addEventListener」の書き方にする。
※いろいろ調べてモジュールの形式でも書けることは確認した。

  • /get でKVから値を取得
  • /put/xxx でKVに「xxx」を書き込み

という仕様。

C:\donraku\cloudflare\third-app>wrangler dev

↑で正常に動くまで確認。
ダッシュボードで「third-app-MY_KV_preview」に値が入ることも確認。

デプロイ

C:\donraku\cloudflare\third-app>wrangler publish
 ⛅️ wrangler 2.0.5
-------------------
Uploaded third-app (0.64 sec)
Published third-app (3.48 sec)
  third-app.donraku.workers.dev

一瞬でデプロイ完了。

動作確認

$ curl -X GET "https://third-app.donraku.workers.dev/"
Hello Third-app!!

$ curl -X GET "https://third-app.donraku.workers.dev/get"
Value not found

$ curl -X GET "https://third-app.donraku.workers.dev/put/123456"
put success! 123456

$ curl -X GET "https://third-app.donraku.workers.dev/get"
123456

$ curl -X GET "https://third-app.donraku.workers.dev/put/ABCD"
put success! ABCD

$ curl -X GET "https://third-app.donraku.workers.dev/get"
ABCD

適当なサーバからcurlでアクセスしてみた結果が↑。
KVの読み込みと書き込みの確認OK。

以上です。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?