From e0d4046f9a3f4ebadcd66327e70277420d31a3f9 Mon Sep 17 00:00:00 2001 From: Samuel Papineau Date: Tue, 5 Dec 2023 10:00:46 -0500 Subject: [PATCH] Updated latest cursor --- src/fetch/GET.ts | 6 +++--- src/fetch/cursor.ts | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 src/fetch/cursor.ts diff --git a/src/fetch/GET.ts b/src/fetch/GET.ts index 66ff433..9ecaa9a 100644 --- a/src/fetch/GET.ts +++ b/src/fetch/GET.ts @@ -9,6 +9,7 @@ import swaggerFavicon from "../../swagger/favicon.png" import { toFile, toJSON, toText } from "./cors.js"; import { handleMessages, selectMessages } from "./messages.js"; import { checkHealth } from "./health.js"; +import { latestCursor } from "./cursor.js"; export default async function (req: Request, server: Server) { const { pathname, searchParams} = new URL(req.url); @@ -16,9 +17,8 @@ export default async function (req: Request, server: Server) { // Bun automatically returns a 101 Switching Protocols // if the upgrade succeeds const key = req.headers.get("sec-websocket-key") - const chain = searchParams.get("chain") + const chain = searchParams.get("chain"); const moduleHash = searchParams.get("moduleHash"); - const payload = JSON.parse(selectMessages(db, 1, "desc", searchParams.get("chain"), searchParams.get("moduleHash"))[0].payload) const success = server.upgrade(req, {data: {key, chain, moduleHash}}); if (success) { logger.info('upgrade', {key, chain, moduleHash}); @@ -35,7 +35,7 @@ export default async function (req: Request, server: Server) { if ( pathname === "/chain") return toJSON(sqlite.selectAll(db, "chain")); if ( pathname === "/openapi") return toJSON(openapi); if ( pathname === "/messages") return handleMessages(req); - if ( pathname === "/cursor/latest") return toText(payload.cursor); + if ( pathname === "/cursor/latest") return latestCursor(req); return toText("Not found", 400 ); } \ No newline at end of file diff --git a/src/fetch/cursor.ts b/src/fetch/cursor.ts new file mode 100644 index 0000000..f352400 --- /dev/null +++ b/src/fetch/cursor.ts @@ -0,0 +1,17 @@ +import { handleMessages, selectMessages } from "./messages.js"; +import * as sqlite from "../sqlite.js"; +import { db } from "../../index.js"; +import { toText } from "./cors.js"; + + +export function latestCursor(req: Request) { + const { searchParams} = new URL(req.url); + const chain = searchParams.get("chain"); + const moduleHash = searchParams.get("moduleHash"); + + if ( !sqlite.exists(db, "chain", chain) && chain != null) throw new Error(`Chain [${chain}] not found.`); + if ( !sqlite.exists(db, "moduleHash", moduleHash) && moduleHash != null) throw new Error(`ModuleHash [${moduleHash}] not found.`); + + const payload = selectMessages(db, 1, "desc", searchParams.get("chain"), searchParams.get("moduleHash"))[0]?.payload; + return toText(JSON.parse(payload)?.cursor) +} \ No newline at end of file