Chaincode in Node.js

Let's look at the procedure for developing chaincode in Node.js:

  • Create a Node.js file using the fabric-shim package
  • Create a package.json file with the details of the Node.js file and dependencies, if any
  • Package all the files in a ZIP file including package.json, the main Node.js file, and other JavaScript or config files or dependencies, if any
  • Deploy the package under the Chaincode tab in OBP (refer to the Chaincode deployment section)
Note: You are only required to create a package.json file; there's no need to run npm commands to install node_modules, as the OBP does this for you internally.

Sample Node.js file named education.js.

Create a Node.js file using the fabric-shim package:

const shim = require('fabric-shim');
const Chaincode = class {
async Init(stub) {
return shim.success();
}
async Invoke(stub) {
let ret = stub.getFunctionAndParameters();
let method = this[ret.fcn];
console.log("Inside invoke. Calling method: " + ret.fcn);
if (!method) {
shim.error(Buffer.from('Received unknown function ' + ret.fcn + ' invocation'));
}
try {
let payload = await method(stub, ret.params);
return shim.success(payload);
} catch (err) {
console.log(err);
return shim.error(err);
}
}

//Method to save or update a user review to a product

async insertReceiver(stub, args) {
console.log("inside insertReceiver: " + JSON.stringify(args));
if (args.length != 3) {
throw 'Incorrect number of arguments. Expecting ID,Name and Org.';
}
var receiver = {};
receiver.ObjectType = "receiver";
receiver.Receiver_id = args[0];
receiver.Receiver_name = args[1];
receiver.Upload_org = args[2];
await stub.putState(receiver.Receiver_id, Buffer.from(JSON.stringify(receiver)));
}//End of method
}

shim.start(new Chaincode());

Sample JSON file named package.json.

Create a package.json file with the details of the Node.js file and dependencies, if any:

{
"name": "education",
"version": "1.0.0",
"description": "Chaincode implemented in node.js",
"engines": {
"node": ">=8.9.0",
"npm": ">=5.5.0"
},
"scripts": {
"start" : "node education.js"
},
"engine-strict": true,
"license": "Apache-2.0",
"dependencies": {
"fabric-shim": "~1.3.0"
}
}

This sample Node.js code with the package.json file can be downloaded from the GitHub repository referenced in this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset