wget https://k-v.deno.dev
prefixを空配列にすることですべてのデータを取得できます。
const entries = []
for await (const entry of db.list({ prefix: [] })) entries.push(entry)
例
# すべてのデータを取得
curl https://k-v.deno.dev
# ユーザーの一覧のみ取得
curl https://k-v.deno.dev/users
# 特定のユーザーを取得
curl https://k-v.deno.dev/users/1
# ユーザーを追加
curl https://k-v.deno.dev/users/1 -d '{"name":"John Doe","age":13}'
# ユーザーの属性を修正
curl https://k-v.deno.dev/users/1/books/1 -d '{"name":"アンパンマン","price":980}'
# ユーザーを削除
curl -X DELETE https://k-v.deno.dev/users/1
# ユーザーの属性を削除
curl -X DELETE https://k-v.deno.dev/users/1/books/1
ソースコード
import { serve } from "https://deno.land/std@0.155.0/http/server.ts";
const db = await Deno.openKv();
serve(async (req: Request) => {
const path = new URL(req.url).pathname.slice(1)
const key = path ? path.split('/') : []
if (req.method === 'GET') {
const { value } = await db.get(key)
if (value) return new Response(value, { headers: { 'Access-Control-Allow-Origin': '*' } })
const entries = []
for await (const e of db.list({ prefix: key })) entries.push(e)
return new Response(JSON.stringify(entries, null, 2), { headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json; charset=UTF-8' } })
} else if (['POST', 'PUT'].includes(req.method)) {
db.set(key, await req.text())
} else if (req.method === 'DELETE') {
db.delete(key)
}
return new Response('', { headers: { 'Access-Control-Allow-Origin': '*' } })
})