-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbaseService.ts
99 lines (89 loc) · 2.79 KB
/
baseService.ts
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
import invoke from './invoke';
import query from './query';
import getLogger from '../utils/getLogger';
import createFabricClient from './createFabricClient';
interface Options {
channelId?: string;
peers?: Peer[];
orderer?: Orderer;
}
interface QueryOptions {
chaincode: Chaincode;
userId: string;
peer?: Peer;
channelId?: string;
}
interface InvokeOptions {
chaincode: Chaincode;
userId: string;
peers?: Peer[];
channelId?: string;
orderer?: Orderer;
}
type getServicesFunction<Services extends {[key: string]: Function}> = (
query: (options: QueryOptions) => Promise<{} | string>,
invoke: (options: InvokeOptions) => Promise<{} | string>
) => Services | {};
const logger = getLogger('lib/baseService');
export default function baseService<Services extends {[key: string]: Function}>(
keyStorePath: string,
chaincodeId: string,
getServices: getServicesFunction<Services> = () => ({}),
{
channelId: defaultChannelId,
peers: defaultPeers = [],
orderer: defaultOrderer
}: Options = {}
): {
getChaincodeId: () => string;
} & Services {
const setChaincodeOption = (chaincode: Chaincode) => {
const updatedChaincode = {...chaincode};
if (typeof chaincode.id !== 'string') {
updatedChaincode.id = chaincodeId;
}
if (!Array.isArray(chaincode.args)) {
updatedChaincode.args = [];
}
return updatedChaincode;
};
const services = getServices(
async({
chaincode, channelId = defaultChannelId, peer = defaultPeers[0], userId
}: QueryOptions) => {
const fabricClient = await createFabricClient(keyStorePath);
const options = {
chaincode: setChaincodeOption(chaincode),
channelId,
peer,
userId
};
logger.info(`Query options: ${JSON.stringify(options)}`);
return query({
...options,
fabricClient
});
},
async ({
chaincode, channelId = defaultChannelId, peers = defaultPeers, orderer = defaultOrderer, userId
}: InvokeOptions) => {
const fabricClient = await createFabricClient(keyStorePath);
const options = {
chaincode: setChaincodeOption(chaincode),
channelId,
peers,
orderer,
userId
};
logger.info(`Invoke options: ${JSON.stringify(options)}`);
return invoke({
...options,
fabricClient
});
}
);
return {
getChaincodeId: () => chaincodeId,
...(services as object),
} as Services & { getChaincodeId: () => string };
};