I’m working on a Cloudflare Hono api site, where I want to fetch ZLIB items from a Cloudflare KV.
Items are stored as, eg. <key_name>_chunk_0, <key_name>_chunk_1, etc.
Ideally I want to return the items as a list of compressed objects, but will be satisfied with a single zipped object (I’ll be decompressing on the client).
So far, I get empty stuff returned to the client. I’ve checked namespace and access to the KV store and all that works fine.
Here’s a simplified version of my code:
import { Hono } from 'hono';
const app = new Hono();
async function fetchFromKV(env, baseKey) {
const chunks = [];
let chunkIndex = 0;
while (true) {
const chunkKey = `${baseKey}_chunk_${chunkIndex}`;
const chunkData = await env.KEYNAMESPACE.get(chunkKey, "arrayBuffer");
if (chunkData === null) {
// No more chunks found, break the loop
break;
}
chunks.push(chunkData);
chunkIndex++;
}
return chunks;
}
app.get('/api/getHello', async (c) => {
try {
const data = await fetchFromKV(c.env, 'key-for-zipped-item'); // Use await to fetch data
return c.json({
message: 'Here is your data!',
data: data
});
} catch (e) {
return c.json({ error: e.message }, 500);
}
});
export default app;
Can someone tell me what I’m doing wrong?
Many thanks in advance!
EDIT: Also tried this with no success with GZIP item:
app.get('/api/getGzipItem', async (c) => {
// Basic auth check (you may want to adjust this based on your actual auth setup)
const key = '<key_name>_chunk_0';
const gzipData = await c.env.RESSADA.get(key, "arrayBuffer");
if (gzipData === null) {
return c.json({ message: 'Item not found' }, 404);
}
c.header('Content-Type', 'application/gzip');
c.header('Content-Encoding', 'gzip');
// Return the compressed data as a raw response
return c.body(gzipData);
});
1