-
Notifications
You must be signed in to change notification settings - Fork 68
/
getLedger.js
129 lines (106 loc) · 2.86 KB
/
getLedger.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
'use strict';
var Logger = require('../../lib/logger');
var log = new Logger({scope : 'get ledger'});
var smoment = require('../../lib/smoment');
var hbase = require('../../lib/hbase')
var getLedger = function (req, res, next) {
var options = prepareOptions();
if (options.error) {
errorResponse(options);
} else {
if (options.ledger_index) {
log.info('LEDGER:', options.ledger_index);
} else if (options.ledger_hash) {
log.info('LEDGER:', options.ledger_hash);
} else if (options.closeTime) {
log.info('LEDGER:', options.closeTime.format());
} else {
log.info('LEDGER: latest');
}
hbase.getLedger(options, function(err, ledger) {
if (err) {
errorResponse(err);
} else if (!ledger) {
errorResponse({error: "ledger not found", code: 404});
} else {
successResponse(ledger);
}
});
}
/**
* prepareOptions
* parse request parameters to determine query options
*/
function prepareOptions() {
var options = {
ledger_index: req.query.ledger_index,
ledger_hash: req.query.ledger_hash,
binary: (/true/i).test(req.query.binary) ? true : false,
expand: (/true/i).test(req.query.expand) ? true : false,
transactions: (/true/i).test(req.query.transactions) ? true : false
};
var ledger_param = req.params.ledger_param;
var intMatch = /^\d+$/;
var hexMatch = new RegExp('^(0x)?[0-9A-Fa-f]+$');
var date = smoment(ledger_param);
if (ledger_param) {
// ledger index test
if (intMatch.test(ledger_param)) {
options.ledger_index = ledger_param;
// date test
} else if (date) {
options.closeTime = date;
// ledger hash test
} else if (hexMatch.test(ledger_param) && ledger_param.length % 2 === 0) {
options.ledger_hash = ledger_param.toUpperCase();
} else {
return {
error: "invalid ledger identifier",
code: 400
};
}
} else if (req.query.date) {
date = smoment(req.query.date);
if (date) {
options.closeTime = date;
} else {
return {
error: 'invalid date format',
code: 400
};
}
}
return options;
}
/**
* errorResponse
* return an error response
* @param {Object} err
*/
function errorResponse(err) {
log.error(err.error || err);
if (err.code && err.code.toString()[0] === '4') {
res.status(err.code).json({
result: 'error',
message: err.error
});
} else {
res.status(500).json({
result: 'error',
message: 'unable to retrieve ledger'
});
}
}
/**
* successResponse
* return a successful response
* @param {Object} ledger
*/
function successResponse(ledger) {
res.json({
result: 'success',
ledger: ledger
});
}
};
module.exports = getLedger