Skip to content

Commit 3c16f4c

Browse files
Block Details API is ready to use.
1 parent 8caeba6 commit 3c16f4c

3 files changed

Lines changed: 67 additions & 46 deletions

File tree

.gitignore

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -551,4 +551,7 @@ MigrationBackup/
551551
.ionide/
552552

553553
# txt
554-
*.txt
554+
*.txt
555+
556+
# vscode tools
557+
/.vscode

backend/src/controllers/block.controller.js

Lines changed: 58 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@ let redisClient;
33

44
// Initialize the Redis client
55
const initRedis = async () => {
6-
if (!redisClient || !redisClient.isOpen) {
6+
if ( !redisClient || !redisClient.isOpen ) {
77
try {
88
redisClient = await initializeRedisClient();
9-
console.log('✓ Redis is connected successfully');
10-
} catch (error) {
11-
console.error('Error connecting to Redis:', error.message);
12-
throw new Error('Redis connection failed');
9+
console.log( '✓ Redis is connected successfully' );
10+
} catch ( error ) {
11+
console.error( 'Error connecting to Redis:', error.message );
12+
throw new Error( 'Redis connection failed' );
1313
}
1414
}
1515
};
@@ -21,75 +21,90 @@ const getLast10Blocks = async ( req, res ) => {
2121
await initRedis();
2222

2323
// Check if the 'blocks' sorted set exists
24-
const blocksExist = await redisClient.exists('blocks');
25-
if (!blocksExist) {
26-
return res.status(404).json({
24+
const blocksExist = await redisClient.exists( 'blocks' );
25+
if ( !blocksExist ) {
26+
return res.status( 404 ).json( {
2727
message: 'No sorted set "blocks" found in Redis'
28-
});
28+
} );
2929
}
3030

3131
// Retrieve the last 10 block keys from Redis sorted set 'blocks'
32-
const blockKeys = await redisClient.zRange('blocks', 0, 9, { REV: true });
32+
const blockKeys = await redisClient.zRange( 'blocks', 0, 9, { REV: true } );
3333

34-
if (!blockKeys || blockKeys.length === 0) {
35-
return res.status(404).json({
34+
if ( !blockKeys || blockKeys.length === 0 ) {
35+
return res.status( 404 ).json( {
3636
message: 'No blocks found in Redis sorted set'
37-
});
37+
} );
3838
}
3939

40-
console.log('Retrieved block keys:', blockKeys);
40+
console.log( 'Retrieved block keys:', blockKeys );
4141

4242
// Fetch details for each block key from the Redis hash
4343
const blocks = await Promise.all(
44-
blockKeys.map(async (key) => {
45-
const block = await redisClient.hGetAll(`block:${key}`);
44+
blockKeys.map( async ( key ) => {
45+
const block = await redisClient.hGetAll( `block:${key}` );
4646
return block;
47-
})
47+
} )
4848
);
4949

5050
// Return the blocks as a JSON response
51-
return res.status(200).json({
51+
return res.status( 200 ).json( {
5252
blocks,
5353
message: 'Successfully retrieved the latest 10 blocks'
54-
});
55-
} catch (error) {
56-
console.error('Error retrieving blocks from Redis:', error.message);
57-
return res.status(500).json({
54+
} );
55+
} catch ( error ) {
56+
console.error( 'Error retrieving blocks from Redis:', error.message );
57+
return res.status( 500 ).json( {
5858
message: 'Internal server error',
5959
error: error.message
60-
});
60+
} );
6161
}
6262
};
63+
// Function to get details for a specific block by block number
64+
const getBlockDetails = async ( req, res ) => {
65+
// Extract blocknumber from the request body
66+
const { blocknumber } = req.body;
67+
68+
// If blocknumber is not provided, return a 400 error
69+
if ( !blocknumber ) {
70+
return res.status( 400 ).json( {
71+
message: 'Block number is required',
72+
} );
73+
}
6374

64-
// Function to get specific block details from Redis cache or database
65-
const getBlockDetails = async ( req, res, next ) => {
66-
const { blockNumber } = req.params;
6775
try {
68-
// Ensure Redis client is initialized
76+
// Initialize Redis client
6977
await initRedis();
7078

71-
const cacheKey = `block:${blockNumber}`;
72-
let blockData = await redisClient.get( cacheKey );
73-
74-
if ( blockData ) {
75-
return res.json( { success: true, result: JSON.parse( blockData ) } );
79+
// Check if the block exists in Redis
80+
const blockExists = await redisClient.exists( `block:${blocknumber}` );
81+
if ( !blockExists ) {
82+
return res.status( 404 ).json( {
83+
message: `Block with number "${blocknumber}" not found in Redis`,
84+
} );
7685
}
7786

78-
// Fallback to database if block is not found in Redis cache
79-
// @ts-ignore
80-
const result = await db.query( 'SELECT * FROM blocks WHERE block_number = $1', [ blockNumber ] );
87+
// Fetch the block data from Redis
88+
const blockData = await redisClient.hGetAll( `block:${blocknumber}` );
8189

82-
if ( result.rows.length === 0 ) {
83-
return res.status( 404 ).json( { success: false, message: 'Block not found' } );
90+
// If no block data is found, return a 404 error
91+
if ( !blockData || Object.keys( blockData ).length === 0 ) {
92+
return res.status( 404 ).json( {
93+
message: `No data found for block number "${blocknumber}" in Redis`,
94+
} );
8495
}
8596

86-
// Cache the block data in Redis for future requests
87-
blockData = result.rows[ 0 ];
88-
await redisClient.set( cacheKey, JSON.stringify( blockData ) );
89-
90-
return res.json( { success: true, result: blockData } );
97+
// Send the block data as a JSON response
98+
return res.status( 200 ).json( {
99+
block: blockData,
100+
message: `Successfully retrieved block data for block number "${blocknumber}"`,
101+
} );
91102
} catch ( error ) {
92-
next( error );
103+
console.error( `Error retrieving block data for number "${blocknumber}":`, error.message );
104+
return res.status( 500 ).json( {
105+
message: 'Internal server error',
106+
error: error.message,
107+
} );
93108
}
94109
};
95110

backend/src/routes/block.route.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
const express = require('express');
2-
const { getLast10Blocks, getBlockDetails } = require('@controllers/block.controller');
2+
const { getLast10Blocks, getBlockDetails } = require('../controllers/block.controller');
33

44
const router = express.Router();
55

6-
// Define the GET route for last 10 blocks
6+
// Define the POST route for fetching the last 10 blocks
77
router.post('/getLast10Blocks', getLast10Blocks);
8+
9+
// Define the POST route for fetching block details by block number
10+
// Changed from 'blockKey' to 'blocknumber' to match the route parameter name
811
router.post('/blockDetails', getBlockDetails);
912

1013
module.exports = router;

0 commit comments

Comments
 (0)