IBM Cloudant – NodeJS sample
In previous IBM Mobile Foundation tutorial we demoed the backend connections capability of MFP and the use of MFP Adapters to communicate with Cloundant databases . In this tutorial we will demo IBM Cloudant connections through NodeJS services .
The content in this tutorial is very basic and simple to get you started with IBM Cloudant .
We will start with setting up a new IBM Cloudant service and creating few databases , then writing a server.js to acccess the NoSQL cloudant service and query or inserts data to its databases .
Cloudant setup
-
create a cloudant NoSQl DB service through the IBM Cloud dashboard :
from your Cloudant service dashboard , click on Launch Cloudant Dashboard:
- populate new service credentials from your new Cloudant instance’s dashboard / Service credentials :
these credentials will be used as config data in the NodeJS server to access your Cloudant . - create a new database with the name cities , and a database with the name countries as per our sample code requirements :
we will leave the two databases with no documents for the moment, and pass to perform the insertion through JS code .
NodeJS service to query/insert data
You can clone this repo for the NodeJS service code ! I am sharing the repo’s link first because the code is basic and simple . Still, I recommend you follow these steps before running the sample app .
-
-
-
- Create service credentials config file (vcap-local.json)
we will store the service credentials generated in previous steps in vcap-local.json file on this format :{ "services": { "cloudantNoSQLDB": { "credentials": SERVICE CREDENTIALS HERE , "label": "cloudantNoSQLDB" } } }
so your final vcap-local.json will be the following :
{ "services": { "cloudantNoSQLDB": { "credentials":{
"apikey": "XYZ",
"host": "XYZ",
"iam_apikey_description": "XYZ",
"iam_apikey_name": "XYZ",
"iam_role_crn": "XYZ",
"iam_serviceid_crn": "XYZ",
"password": "XYZ",
"port": "XYZ",
"url":"XYZ",
"username": "XYZ"
} , "label": "cloudantNoSQLDB" } } } - Initialize the Cloudant library
in order to connect to Cloudant service through NodeJS we will use Cloudant’s official node driver (Cloudant Node.js Client ) . Which we can add to our app using:$ npm install --save @cloudant/cloudant
add the following to your server.js file to load the Cloudant library and initialise it with the credentials being parsed from vcap-local.json :let vcapLocal; try { vcapLocal = require('./vcap-local.json'); console.log("Loaded local VCAP", vcapLocal); } catch (e) {
console.log("Error loading cloudant credentials file", vcapLocal);
} const appEnvOpts = vcapLocal ? { vcap: vcapLocal } : {} const appEnv = cfenv.getAppEnv(appEnvOpts); var Cloudant = require('@cloudant/cloudant'); if (process.env.VCAP_SERVICES) { var env = JSON.parse(process.env.VCAP_SERVICES); var credentials = env['cloudantNoSQLDB'][0]['credentials']; cloudant = new Cloudant({ url: credentials.url, maxAttempt: 25, plugins: { retry: { retryErrors: false, retryStatusCodes: [429] } } }); } else if (appEnv.services['cloudantNoSQLDB'] || appEnv.getService(/cloudant/)) { if (appEnv.services['cloudantNoSQLDB']) { cloudant = new Cloudant({ url: appEnv.services['cloudantNoSQLDB'][0].credentials.url, maxAttempt: 25, plugins: { retry: { retryErrors: false, retryStatusCodes: [429] } } }); } else { cloudant = new Cloudant({ url: appEnv.getService(/cloudant/).credentials.url, maxAttempt: 25, plugins: { retry: { retryErrors: false, retryStatusCodes: [429] } } }); } } else if (process.env.CLOUDANT_URL) { cloudant = new Cloudant({ url: process.env.CLOUDANT_URL, maxAttempt: 25, plugins: { retry: { retryErrors: false, retryStatusCodes: [429] } } }); - Insert / delete or update data to Cloudant
– add a city database entry to your Cities database with a reference to a Countries database document , where country name is given :app.post("/api/addCity", cors(), function (request, response) { let countryID; countries_db = cloudant.db.use("countries"); cities_db = cloudant.db.use("cities"); if (!countries_db || !cities_db) { responseError("An error has occured", 400, response); return; } countries_db.find({ selector: { "name": request.body.toCountry } }, function (err, result) { if (err) { throw err; } countryID = eval(JSON.stringify(result["docs"]))[0]._id; cities_db.insert({ name: request.body.name, country_id: countryID }, function (err, result) { if (err) { throw err; } console.log("Current cities list: " + JSON.stringify(result)); }); var responseJson = { "success": true, "added city": request.body.name, "toCountry": request.body.toCountry }; response.status(200); response.json(responseJson); }); });
read all documents in Countries database :app.post("/api/getAllCountries", cors(), function (request, response) { countries_db = cloudant.db.use("countries"); if (!countries_db) { responseError("An error has occured", 400, response); return; } countries_db.find({ selector: { "continent": request.body.continent } }, function (err, result) { if (err) { throw err; } response.status(200); response.json(result); console.log("List of countries in " + request.body.continent + " " + JSON.stringify(result)); }); });
You can check out more operations and details in the sample code in the repo I mentioned above . And you can drop any comment or question below regarding NodeJS with Cloudant .
Next tutorials will be on more NodeJS REST APIs – with IBM services topics . So please drop any suggestions as well, if any !
- Create service credentials config file (vcap-local.json)
-
-
Recent Comments