-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
includes list-event route with pages
- Loading branch information
1 parent
f72b224
commit b79c82c
Showing
2 changed files
with
57 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,61 @@ | ||
import { Env } from "../../worker-configuration"; | ||
|
||
export async function handleEvents(request: Request, env: Env) { | ||
const prefix = 'event/app-stake-a'; | ||
const PREFIX = "event/app-stake-a" | ||
|
||
const listResult = await env.EVENTS.list({ prefix }); | ||
const HEADERS = { 'Content-Type': 'application/json' } | ||
const BATCH_SIZE = 5 | ||
const LIMIT = 200 | ||
|
||
export async function handleListEvents(request: Request, env: Env) { | ||
const url = new URL(request.url) | ||
|
||
const fullParam = url.searchParams.get('full') | ||
const page = url.searchParams.get('page') || '0' | ||
const returnFullResult = fullParam === 'true' | ||
|
||
const listResult = await env.EVENTS.list({ prefix: PREFIX }); | ||
|
||
if (returnFullResult) { | ||
const fullResult = await getFullResult(listResult, page, env) | ||
|
||
return new Response(JSON.stringify(fullResult, null, 2), { | ||
headers: HEADERS, | ||
}); | ||
} | ||
|
||
return new Response(JSON.stringify(listResult.keys, null, 2), { | ||
headers: { 'Content-Type': 'application/json' }, | ||
headers: HEADERS | ||
}); | ||
} | ||
|
||
async function getFullResult(listResult: KVNamespaceListResult<unknown, string>, page: string, env: Env) { | ||
const keys = listResult.keys.map(key => key.name); | ||
const fullResults: Record<string, any>[] = []; | ||
|
||
|
||
async function processBatch(batch: string[]) { | ||
const results = await Promise.all( | ||
batch.map(async (key) => { | ||
const value = await env.EVENTS.get(key); | ||
return { key, value: JSON.parse(value!) }; | ||
}) | ||
); | ||
|
||
fullResults.push(...results); | ||
}; | ||
|
||
const pageIndex = parseInt(page) || 0 | ||
const startIndex = pageIndex * LIMIT | ||
const endIndex = startIndex + LIMIT - 1 | ||
|
||
for (let i = startIndex; i < keys.length; i += BATCH_SIZE) { | ||
if (i > endIndex) { | ||
break | ||
} | ||
|
||
const batch = keys.slice(i, i + BATCH_SIZE); | ||
await processBatch(batch); | ||
} | ||
|
||
return fullResults | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters