1
0

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.

Deno KVですべてのデータをエスクポート【Deno Deploy】

Last updated at Posted at 2023-05-06

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': '*' } })
})
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?