Moves undefined fallback from client to server side for cursor parameter Ensures consistent pagination behavior when fetching links from KV storage This prevents potential edge cases where undefined cursor values could be handled differently between client and server.
29 lines
802 B
TypeScript
29 lines
802 B
TypeScript
import { z } from 'zod'
|
|
|
|
export default eventHandler(async (event) => {
|
|
const { cloudflare } = event.context
|
|
const { KV } = cloudflare.env
|
|
const { limit, cursor } = await getValidatedQuery(event, z.object({
|
|
limit: z.coerce.number().max(1024).default(20),
|
|
cursor: z.string().trim().max(1024).optional(),
|
|
}).parse)
|
|
const list = await KV.list({
|
|
prefix: `link:`,
|
|
limit,
|
|
cursor: cursor || undefined,
|
|
})
|
|
if (Array.isArray(list.keys)) {
|
|
list.links = await Promise.all(list.keys.map(async (key: { name: string }) => {
|
|
const { metadata, value: link } = await KV.getWithMetadata(key.name, { type: 'json' })
|
|
if (link) {
|
|
return {
|
|
...metadata,
|
|
...link,
|
|
}
|
|
}
|
|
return link
|
|
}))
|
|
}
|
|
delete list.keys
|
|
return list
|
|
})
|