From 7da6568a12349767b819733abfa78d70b673f557 Mon Sep 17 00:00:00 2001 From: yosaphatprs Date: Fri, 7 Nov 2025 11:30:03 +0700 Subject: [PATCH] feat: update chaincode to get with pagination for reducing storage load on blockchain --- .../logVerification/lib/logVerification.js | 54 ++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/backend/blockchain/chaincode/logVerification/lib/logVerification.js b/backend/blockchain/chaincode/logVerification/lib/logVerification.js index 7cd7a5d..cbc90f2 100644 --- a/backend/blockchain/chaincode/logVerification/lib/logVerification.js +++ b/backend/blockchain/chaincode/logVerification/lib/logVerification.js @@ -1,5 +1,5 @@ "use strict"; - +// CC_VERSION=1.3 CC_SEQUENCE=4 ./deployChaincode.sh const stringify = require("json-stringify-deterministic"); const sortKeysRecursive = require("sort-keys-recursive"); const { Contract } = require("fabric-contract-api"); @@ -142,6 +142,58 @@ class LogVerification extends Contract { return allResults; } + async getLogsWithPagination(ctx, pageSize, bookmark) { + if (!pageSize || isNaN(pageSize) || pageSize <= 0) { + throw new Error("Page size must be a positive integer"); + } + + if (!bookmark) { + bookmark = ""; + } + + if (pageSize > 100) { + throw new Error("Page size must not exceed 100"); + } + + const { iterator, metadata } = await ctx.stub.getStateByRangeWithPagination( + "", + "", + pageSize, + bookmark + ); + + const logs = []; + + try { + while (true) { + const res = await iterator.next(); + if (res.value && res.value.value.length > 0) { + const payload = res.value.value.toString("utf8"); + try { + logs.push({ + txId: res.value.txId, + value: JSON.parse(payload), + }); + } catch (err) { + throw new Error(`Failed to parse log data: ${err}`); + } + } + if (res.done) { + break; + } + } + } finally { + await iterator.close(); + } + + return { + logs: logs, + fetchedRecordsCount: metadata.fetchedRecordsCount, + bookmark: metadata.bookmark, + metadata: metadata, + }; + } + async logExists(ctx, id) { const logJSON = await ctx.stub.getState(id); return logJSON && logJSON.length > 0;