This repository has been archived by the owner on Feb 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.service.js
87 lines (71 loc) · 2.03 KB
/
query.service.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
import httpStatus from "http-status";
import { isBuffer } from "lodash";
import logger from "../config/Log";
import network from "./network.service";
let channel = null;
const query = async (fcn, args) => {
try {
channel = await network.getChannel();
const channelPeers = channel.getChannelPeers();
const peers = channelPeers.map(channelpeer => {
if (channelpeer._roles.endorsingPeer) {
return channelpeer.getName();
}
});
// send query
const request = {
targets: peers, // queryByChaincode allows for multiple targets
chaincodeId: network.getChaincodeName(),
fcn,
args
};
const responsePayloads = await channel.queryByChaincode(request);
if (responsePayloads.length === 0 || responsePayloads === undefined) {
throw new Error(
`Error from query: No result `,
httpStatus.BAD_REQUEST,
true
);
}
for (let i = 0; i < responsePayloads.length; i += 1) {
logger.info(
`result received from peer ${i}: ${responsePayloads[i].toString(
"utf8"
)}`
);
}
// TODO multiple peers, multiple responses
if (isBuffer(responsePayloads[0])) {
return JSON.parse(responsePayloads[0].toString("utf8"));
}
return {
result: responsePayloads[0].toString("utf8")
};
} catch (e) {
logger.info(e);
return e;
}
};
const GetAll = async () => query("queryAll", []);
const Validate = async (id, hash) => {
const result = await query("validateResource", [
JSON.stringify({ id, hash })
]);
return {
result: result.result,
blockchainHash: result.hash
};
};
const GetResourceById = async id =>
query("queryById", [JSON.stringify({ id })]);
const GetResourceHistory = async id =>
query("queryHistory", [JSON.stringify({ id })]);
const GetResourceHistoryByVersion = async (id, version) =>
query("queryHistoryByVersion", [JSON.stringify({ id, version })]);
export default {
GetAll,
Validate,
GetResourceById,
GetResourceHistory,
GetResourceHistoryByVersion
};