Configure the Advanced I/O Function

Let’s now configure the Advanced I/O function component. The Advanced I/O function is intialized Node.js, its directory (functions/news_app_function) will contain:

You will be adding code in the index.js file.

The Advanced I/O function fetches the news item from its source table in the Data Store and forwards it to the client component as a JSON response.

Install Express Node.js Framework

Since you are coding in the Node.js platform, you will be using the Express Node.js framework. To import the Express package in the code, you must install the Express dependencies in your system.

copy
$
npm install express

This will install the Express module and save the dependencies.

cron_express_news_app_function_install

This information will also be updated in the package.json file.

cron_express_news_app_function_json

Copy the Node.js code and paste it in index.js in functions/news_app_function directory of your project, and save the file. You can use any IDE to work with the application’s files.

Note: Please go through the code in this section to make sure you fully understand it.
    
index.js
copy
'use strict'; var express = require('express'); var app = express(); var catalyst = require('zcatalyst-sdk-node'); app.use(express.json()); //GET API that gets the news from the required table app.get('/fetchData', (req, res) => { var tablename = req.query.tablename; console.log("Table Name "+tablename); //Initializing Catalyst SDK var catalystApp = catalyst.initialize(req); //Queries the Catalyst Data Store table and gets the required news getDataFromCatalystDataStore(catalystApp, tablename).then(newsDetails => { res.send({ "content": newsDetails }) }).catch(err => { console.log(err); sendErrorResponse(res); }) }); /** * Executes the Query and fetches the news from the table * @param {*} catalystApp * @param {*} tablename */ function getDataFromCatalystDataStore(catalystApp, tablename) { return new Promise((resolve, reject) => { //Queries the Catalyst Data Store table catalystApp.zcql().executeZCQLQuery("Select title,url from " + tablename).then(queryResponse => { resolve(queryResponse); }).catch(err => { reject(err); }) }); } /** * Sends an error response * @param {*} res */ function sendErrorResponse(res) { res.status(500); res.send({ "error": "Internal server error occurred. Please try again in some time." }); } module.exports = app;
View more

The Advanced I/O function is now configured. We will discuss the application’s architecture after you configure the client.

Last Updated 2023-12-15 18:54:08 +0530 +0530