Skip to content

Commit 4168184

Browse files
author
Long Nguyen
authored
Merge pull request #38 from Akachain/change_output_format_for_query_service
Change output format for query service
2 parents 48b8554 + 4158858 commit 4168184

File tree

4 files changed

+99
-49
lines changed

4 files changed

+99
-49
lines changed

lib/helper/InvokeService.js

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ class InvokeService {
154154
}, 30000);
155155
eh.registerTxEvent(tx_id_string, (tx, code, block_num) => {
156156
logger.debug('The chaincode invoke chaincode transaction has been committed on peer %s', eh.getPeerAddr());
157-
logger.debug('Transaction %s has status of %s in block %s', tx, code, block_num);
157+
logger.debug('Transaction %s has status of %s in blocl %s', tx, code, block_num);
158158
clearTimeout(event_timeout);
159159

160160
if (code !== 'VALID') {
@@ -168,8 +168,7 @@ class InvokeService {
168168
}
169169
}, (err) => {
170170
clearTimeout(event_timeout);
171-
// logger.error(err);
172-
logger.warn(err.message, ': ', eh._peer._url);
171+
logger.error(err);
173172
reject(err);
174173
},
175174
// the default for 'unregister' is true for transaction listeners
@@ -249,23 +248,25 @@ class InvokeService {
249248
success = false;
250249
logger.error(message);
251250
if (errResponses.length > 0) {
252-
return {
253-
Result: {
254-
Status: errResponses[0].status,
255-
Payload: ""
256-
},
257-
Message: errResponses[0].msg,
258-
MessageDetail: errResponses,
259-
};
251+
// return {
252+
// Result: {
253+
// Status: errResponses[0].status,
254+
// Payload: ""
255+
// },
256+
// Message: errResponses[0].msg,
257+
// MessageDetail: errResponses,
258+
// };
259+
return common.createReturn(errResponses[0].status, "", errResponses[0].msg, errResponses);
260260
} else {
261-
return {
262-
Result: {
263-
Status: 202,
264-
Payload: ""
265-
},
266-
Message: error_message,
267-
MessageDetail: error_message,
268-
};
261+
// return {
262+
// Result: {
263+
// Status: 202,
264+
// Payload: ""
265+
// },
266+
// Message: error_message,
267+
// MessageDetail: error_message,
268+
// };
269+
return common.createReturn(202, "", error_message, error_message);
269270
}
270271
} else {
271272
logger.debug(message);
@@ -279,14 +280,15 @@ class InvokeService {
279280
} catch (e) {
280281
obj.payload = obj.payload.toString('utf8');
281282
}
282-
let result = {
283-
Result: {
284-
Status: obj.status,
285-
Payload: obj.payload
286-
},
287-
Message: "Success",
288-
MessageDetail: "Success"
289-
};
283+
// let result = {
284+
// Result: {
285+
// Status: obj.status,
286+
// Payload: obj.payload
287+
// },
288+
// Message: "Success",
289+
// MessageDetail: "Success"
290+
// };
291+
let result = common.createReturn(obj.status, obj.payload, "Success", "Success");
290292

291293
// send transaction total timer
292294
sendTransactionTotalHistogramTimer({

lib/helper/QueryService.js

Lines changed: 46 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ const common = require('../utils/common')
1515
* It also integrates with 'prom-client' to measure duration when requesting.
1616
*/
1717
class QueryService {
18-
constructor() {}
18+
constructor() { }
1919

2020
/**
2121
* queryChaincode sends a proposal to one or more endorsing peers that will be handled by the chaincode
@@ -29,35 +29,67 @@ class QueryService {
2929
*/
3030
async queryChaincode(peerNames, channelName, chaincodeName, fcn, args, orgName, userName) {
3131
try {
32+
const client = await common.getClientForOrg(orgName, userName)
3233
// first setup the client for this or
3334
const channel = await common.getChannel(orgName, userName, channelName);
3435
if (!channel) {
3536
let message = util.format('Channel %s was not defined in the connection profile', channelName);
3637
logger.error(message);
37-
throw new Error(message);
38+
return common.createReturn(202, "", message, message);
3839
}
40+
const tx_id = client.newTransactionID();
3941

4042
let request = {
4143
targets: peerNames, //queryByChaincode allows for multiple targets
4244
chaincodeId: chaincodeName,
4345
fcn: fcn,
44-
args: args
46+
args: args,
47+
chainId: channelName,
48+
txId: tx_id
4549
};
4650

47-
let response_payloads = await channel.queryByChaincode(request);
48-
if (response_payloads) {
49-
for (let i = 0; i < response_payloads.length; i++) {
50-
logger.debug('------->>> R E S P O N S E : ' + response_payloads[i].toString('utf8'));
51-
return response_payloads[i].toString('utf8');
51+
const proposalResults = await channel.sendTransactionProposal(request);
52+
const responses = proposalResults[0];
53+
logger.debug('queryByChaincode - results received');
54+
55+
if (!responses || !Array.isArray(responses)) {
56+
return common.createReturn(202, "", `Payload results are missing from the chaincode query`, "");
57+
}
5258

59+
if (responses[0]) {
60+
if (responses[0] instanceof Error) {
61+
let err = responses[0];
62+
let jsonErr = JSON.stringify(err, Object.getOwnPropertyNames(err));
63+
let objErr = JSON.parse(jsonErr);
64+
try {
65+
let convertObj = JSON.parse(objErr.message);
66+
// logger.debug('convertObj: ', convertObj);
67+
return common.createReturn(convertObj.status, "", convertObj.msg, convertObj.msg);
68+
} catch (err) {
69+
logger.error('error: ', err);
70+
return common.createReturn(convertObj.status, "", err, err);
71+
}
72+
} else if (responses[0].response && responses[0].response.payload) {
73+
logger.debug("RESPONSE DATA: ", responses[0].response)
74+
var obj = responses[0].response
75+
try {
76+
obj.payload = JSON.parse(obj.payload.toString('utf8'));
77+
} catch (e) {
78+
obj.payload = obj.payload.toString('utf8');
79+
}
80+
return common.createReturn(obj.status, obj.payload, "Success", "Success");
81+
} else {
82+
logger.error('queryByChaincode - unknown or missing results in query ::' + responses);
83+
return common.createReturn(202, "", `queryByChaincode - unknown or missing results in query`, "");
5384
}
85+
5486
} else {
5587
logger.error('response_payloads is null');
56-
return 'response_payloads is null';
88+
return common.createReturn(202, "", `response_payloads is null`, "");
5789
}
5890
} catch (error) {
5991
logger.error('Failed to query due to error: ' + error.stack ? error.stack : error);
60-
return error.toString();
92+
return common.createReturn(202, "", error.toString(), error.toString());
6193
}
6294
}
6395

@@ -278,10 +310,10 @@ class QueryService {
278310
);
279311
});
280312
const output = headerAsn.encode({
281-
Number: parseInt(header.number),
282-
PreviousHash: Buffer.from(header.previous_hash, 'hex'),
283-
DataHash: Buffer.from(header.data_hash, 'hex')
284-
},
313+
Number: parseInt(header.number),
314+
PreviousHash: Buffer.from(header.previous_hash, 'hex'),
315+
DataHash: Buffer.from(header.data_hash, 'hex')
316+
},
285317
'der'
286318
);
287319
return sha.sha256(output);

lib/utils/common.js

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -130,9 +130,9 @@ const getChannel = async (orgName, userName, channelName, isRefresh) => {
130130
* Declare prometheus' Histograms and Counters to measure duration metrics when sending the request.
131131
*/
132132
const requestCounter = new promClient.Counter({
133-
name: 'akc_request_count',
134-
help: 'Counter of requests'
135-
}),
133+
name: 'akc_request_count',
134+
help: 'Counter of requests'
135+
}),
136136
sendTransactionTotalHistogram = new promClient.Histogram({
137137
name: 'akc_send_transaction_total_duration',
138138
help: 'Histogram of send transaction total duration',
@@ -153,11 +153,24 @@ const requestCounter = new promClient.Counter({
153153
help: 'Counter of error requests'
154154
});
155155

156+
157+
const createReturn = (Status, Payload, Message, MessageDetail) => {
158+
return {
159+
Result: {
160+
Status,
161+
Payload,
162+
},
163+
Message,
164+
MessageDetail,
165+
};
166+
}
167+
156168
exports.getDefaultEndorsermentPolicy = getDefaultEndorsermentPolicy;
157169
exports.getClientForOrg = getClientForOrg;
158170
exports.getChannel = getChannel;
159171
exports.requestCounter = requestCounter;
160172
exports.sendTransactionTotalHistogram = sendTransactionTotalHistogram;
161173
exports.sendProposalHistogram = sendProposalHistogram;
162174
exports.sendTransactionHistogram = sendTransactionHistogram;
163-
exports.errorRequestCounter = errorRequestCounter;
175+
exports.errorRequestCounter = errorRequestCounter;
176+
exports.createReturn = createReturn;

package.json

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,23 @@
11
{
22
"name": "@akachain/akc-node-sdk",
3-
"author": "hoangnh, hongsongp97, longnh, hainq, huanlv",
4-
"version": "v2.2.1",
3+
"author": "hoangnh, hongsongp97, longnh, hainq, huanlv, thienlk",
4+
"version": "v2.2.3",
55
"description": "AKC node.js SDK for Decentralized Application to connect to Fabric Peers",
66
"main": "index.js",
77
"scripts": {},
88
"keywords": [],
99
"license": "GPL-2.0-or-later",
1010
"dependencies": {
1111
"asn1.js": "^5.2.0",
12+
"fabric-ca-client": "^2.2.3",
1213
"fabric-client": "~1.4.0",
1314
"js-sha256": "^0.9.0",
14-
"log4js": "^4.4.0",
1515
"lodash": "^4.17.19",
16+
"log4js": "^4.4.0",
1617
"prom-client": "^11.5.0"
1718
},
18-
"publishConfig": { "registry": "https://npm.pkg.github.com/" },
19+
"publishConfig": {
20+
"registry": "https://npm.pkg.github.com/"
21+
},
1922
"repository": "git://github.com/Akachain/akc-node-sdk.git"
2023
}

0 commit comments

Comments
 (0)