🍵

Cloudflare Workers KV , お試し

2023/06/17に公開

概要

Cloudflare Workers KVのお試しメモとなります。

  • 無料枠は、書込み 1000件と少ない目のようでした。

環境

  • Cloudflare Workers
  • Cloudflare Workers KV

参考のコード

https://github.com/kuc-arc-f/kv-project2


関連


workers作成、準備

wrangler init sample -y

wrangler login

  • KV create

  • 通常、preview を作成、idが出力されます

wrangler kv:namespace create "MY_KV"
wrangler kv:namespace create --preview  "MY_KV"

  • wrangler.toml

  • binding, id, preview_id を設定

kv_namespaces = [
    { binding = "MY_KV", id="3da6a6a5c5314524b48840f50c779d7d", preview_id = "de0fa7eafbba4bc38accdbde3d67fa16" }
]

  • put
  • namespace-id: id指定
  • key=hoge1, value= 1
wrangler kv:key put --namespace-id=3da6a6a5c5314524b48840f50c779d7d "hoge1" "1"

  • get
  • binding指定、key=hoge1
wrangler kv:key get --binding=MY_KV "hoge1"

TS実装

  • src/index.ts
  • env.MY_KV.XXX が、KVの関数です
index.ts
import Common from './lib/Common';
/**
 * Welcome to Cloudflare Workers! This is your first worker.
 *
 * - Run `wrangler dev src/index.ts` in your terminal to start a development server
 * - Open a browser tab at http://localhost:8787/ to see your worker in action
 * - Run `wrangler publish src/index.ts --name my-worker` to publish your worker
 *
 * Learn more at https://developers.cloudflare.com/workers/
 */

export interface Env {
}

export default {
	async fetch(
		request: Request,
		env: Env,
		ctx: ExecutionContext
	): Promise<Response> {
		const { pathname } = new URL(request.url);
//		const envKey = env.API_KEY;
//console.log("envKey=", envKey);
		const errorObj = {ret: "NG", messase: "Error"};
		const retObj = {ret: "OK", data:{} , messase: "Error"};
		//
//console.log("#env");
//console.log(env);
		if (request.method === "GET") {
		}
		if (request.method === "POST") {
			const json: any = JSON.stringify(await request.json());
			const reqObj: any = JSON.parse(json);
			const validApiKey = await Common.validApiKey(env, reqObj);
   		    console.log(validApiKey);
			if(!validApiKey) {
				errorObj.messase = "Error, Common.validApiKey=false";
				console.log("Error, Common.validApiKey=false");
				return Response.json(errorObj);
			}
//console.log("pathname=", pathname);
console.log(reqObj);
			const contentType = request.headers.get("content-type");
			if(contentType !== "application/json") {
				console.log("contentType=", contentType);
				return Response.json({ret: "NG", messase: "Error, contentType <> application/json"});
			}	
			//Router
			if (pathname === "/put") {
				await env.MY_KV.put(reqObj.key, reqObj.value);
				return Response.json(retObj);
			}
			if (pathname === "/get") {
				let value = await env.MY_KV.get(reqObj.key);
				if(!value) {
					return Response.json(errorObj);
				}
				retObj.data = value;
				return Response.json(retObj);
			}
			if (pathname === "/delete") {
				await env.MY_KV.delete(reqObj.key);
				return Response.json(retObj);
			}
		}
		//
		return new Response("Hello World!");
	},
};


server Start

npm run start

deploy

npm run deploy

HTTP Test

  • Rest Clientの例になります
  • Get
POST http://localhost:8787/get
Content-Type: application/json

{
    "api_key": "hoge",
    "key": "k1"
}
  • result
{
  "ret": "OK",
  "data": "v1",
  "messase": "Error"
}

  • Put
POST http://localhost:8787/put
Content-Type: application/json

{
    "api_key": "hoge",
    "key": "k1",
    "value": "v22"
}

Discussion