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-09

TypeError: value too large (max 65536 bytes)

圧縮することでデータが10分の1ほどになります。保存できないときにお試しください

import { serve } from "https://deno.land/std@0.177.0/http/server.ts";
import { deflate, inflate } from "https://deno.land/x/compress@v0.4.4/mod.ts";

const kv = await Deno.openKv();
kv.getText = (...args) => kv.get(...args).then(e => ({...e, value: new TextDecoder().decode(inflate(e.value))}))
kv.setText = (key, value) => kv.set(key, deflate(new TextEncoder().encode(value)))
kv.listText = async (...args) => {
    const entries = []
    for await (const e of kv.list(...args)) entries.push({...e, value: new TextDecoder().decode(inflate(e.value))})
    return entries
}

serve(async (req: Request) => {
    const html = await fetch("https://example.com/").then(r => r.text())
    await kv.setText(["mykey"], html)
    console.log(await kv.getText(["mykey"]))
    console.log(await kv.listText({prefix: []}))
    return new Response("Hello World")
});

deflateではなく、gzipを使う場合

gzipは、deflateより12バイト多くなります

import { serve } from "https://deno.land/std@0.177.0/http/server.ts";
import { gzip, gunzip } from "https://deno.land/x/compress@v0.4.4/mod.ts";

const kv = await Deno.openKv();
kv.getText = (...args) => kv.get(...args).then(e => ({...e, value: new TextDecoder().decode(gunzip(e.value))}))
kv.setText = (key, value) => kv.set(key, gzip(new TextEncoder().encode(value)))
kv.listText = async (...args) => {
    const entries = []
    for await (const e of kv.list(...args)) entries.push({...e, value: new TextDecoder().decode(gunzip(e.value))})
    return entries
}

serve(async (req: Request) => {
    const html = await fetch("https://example.com/").then(r => r.text())
    await kv.setText(["mykey"], html)
    console.log(await kv.getText(["mykey"]))
    console.log(await kv.listText({prefix: []}))
    return new Response("Hello World")
});
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?