26
Thu, Dec
0 New Articles

TechTip: Node.js JoinJS

Programming - Other
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

 

SQL result sets are flat for joins. That makes it more complex to process both in business logic and UI. JoinJS to the rescue!

I am currently coding a Node.js project for a customer that uses the HapiJS web framework. We had the need to create a JSON result object from DB2 that conveyed a list of employees and their department associations and send it to the browser. In short, the SQL result set looked like the below.

[

{"FIRST_NAME":"Georgi","LAST_NAME":"Facello","NAME":"Marketing"},

{"FIRST_NAME":"Georgi","LAST_NAME":"Facello","NAME":"Sales"},

{"FIRST_NAME":"Bezalel","LAST_NAME":"Simmel","NAME":"Sales"},

{"FIRST_NAME":"Parto","LAST_NAME":"Bamford","NAME":"Production"}

]

It's a pretty simple result set, though there is one inefficiency; specifically, Georgi Facello is in two departments, so his name is duplicated on the first two lines. The goal is to instead produce a result set that looks like the following. Note I've formatted the results to make it easier to see how I created a new "departments" section.

[

  {

    "FIRST_NAME": "Georgi",

    "LAST_NAME": "Facello",

    "departments": [

      {"NAME": "Marketing"},

      {"NAME": "Sales"}

    ]

  },

  {

    "FIRST_NAME": "Bezalel",

    "LAST_NAME": "Simmel",

    "departments": [

      {"NAME": "Sales"}

    ]

  },

  {

    "FIRST_NAME": "Parto",

    "LAST_NAME": "Bamford",

    "departments": [

      {"NAME": "Production"}

    ]

  }

]

The above JSON is much simpler to iterate in the UI, but I didn't want to have a bunch of JavaScript in the UI that iterated over a result set and kept track of when the first and last name changed for breaking purposes. I instead set out to implement it in the model layer of the application and was successful. Well, I was only partially successful. The code took 30 minutes to write. Knowing there would be potentially hundreds of other similar chunks of conversion code, I set out to see if there was a tool available to do the mapping for me. After some searching I found the join-js npm.

The join-js npm has the following description:

JoinJS is a JavaScript library to map complex database joins to nested objects. It's a simpler alternative to a full-blown Object-Relation Mapper (ORM), and gives you direct control over your database interactions.

Bingo! That will fit the need perfectly.

Before I go further, I want to show what the current Node.js program looks like before making the join-js changes. The following code should be placed into a file named app.js within the directory of your choice. The process.env.LITMIS_SCHEMA_DEVELOPMENT is a convention used on spaces.litmis.com to gain access to the development DB2 library. Note you can use Litmis Spaces for free to test articles like this. Note also this code requires Node v6.9.1 because of string templates and the new-ish variable declaration syntax (i.e., const and let).

const db = require('/QOpenSys/QIBM/ProdData/OPS/Node6/os400/db2i/lib/db2a')

const dbconn = new db.dbconn()

dbconn.conn("*LOCAL")

const stmt = new db.dbstmt(dbconn)

const schema = process.env.LITMIS_SCHEMA_DEVELOPMENT

let sql = `

SELECT e.first_name,e.last_name,d.name

FROM ${schema}.employees as e

LEFT JOIN ${schema}.dept_emp as de on de.emp_id = e.id

LEFT JOIN ${schema}.departments as d on d.id = de.dept_id

`

stmt.exec(sql, function(result,err) {

  console.log('result:' + JSON.stringify(result,null,2))

})

And below are the SQL DDL and DML statements to populate your DB2 database. I used SQLWorkbenchJ to invoke them all at once.

CREATE TABLE departments (

  id INT NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1),

  name        VARCHAR(40) NOT NULL,

  PRIMARY KEY (id)

);

INSERT INTO departments VALUES

(1,'Marketing'),

(2,'Finance'),

(3,'Human Resources'),

(4,'Production'),

(5,'Development'),

(6,'Quality Management'),

(7,'Sales'),

(8,'Research'),

(9,'Customer Service');

CREATE TABLE employees (

  id          INT             NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1),

  birth_date  DATE            NOT NULL,

  first_name  VARCHAR(14)     NOT NULL,

  last_name   VARCHAR(16)     NOT NULL,

  hire_date   DATE            NOT NULL,

  PRIMARY KEY (id)

);

INSERT INTO employees VALUES

(10001,'1953-09-02','Georgi','Facello','1986-06-26'),

(10002,'1964-06-02','Bezalel','Simmel','1985-11-21'),

(10003,'1959-12-03','Parto','Bamford','1986-08-28');

CREATE TABLE dept_emp (

  id          INT       NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1),

  emp_id      INT       NOT NULL,

  dept_id     INT       NOT NULL,

  from_date   DATE      NOT NULL,

  to_date     DATE      NOT NULL,

  FOREIGN KEY (emp_id)  REFERENCES employees   (id),

  FOREIGN KEY (dept_id) REFERENCES departments (id),

  PRIMARY KEY (id)

);

INSERT INTO dept_emp VALUES

(1,10001,1,'1986-06-26','9999-01-01'),

(2,10001,7,'1986-06-26','9999-01-01'),

(3,10002,7,'1996-08-03','9999-01-01'),

(4,10003,4,'1995-12-03','9999-01-01'),

(5,10004,4,'1986-12-01','9999-01-01'),

(6,10005,3,'1989-09-12','9999-01-01'),

(7,10006,5,'1990-08-05','9999-01-01'),

(8,10007,8,'1989-02-10','9999-01-01'),

(9,10008,5,'1998-03-11','2000-07-31');

Next, install the join-js npm using the below command.

% npm install join-js

`-- join-js@0.4.1                                                              

  `-- This email address is being protected from spambots. You need JavaScript enabled to view it..4

Now you're ready to make modifications to the app.js file to make use of the join-js module, as shown below. I've added line numbers to make this code easier to discuss.

01  const jjs = require('join-js').default;

02  const db = require('/QOpenSys/QIBM/ProdData/OPS/Node6/os400/db2i/lib/db2a')

03  const dbconn = new db.dbconn()

04  dbconn.conn("*LOCAL")

05  const stmt = new db.dbstmt(dbconn)

06  const schema = process.env.LITMIS_SCHEMA_DEVELOPMENT

07 

08 

09  let maps =

10  [

11    {

12      mapId: 'emp_dept_map',

13      idProperty: 'ID',

14      properties: ['FIRST_NAME','LAST_NAME'],

15      collections: [

16        {name: 'departments', mapId: 'dept_map', columnPrefix: 'DEPT_'}

17      ]

18    },

19    {

20      mapId: 'dept_map',

21      idProperty: 'ID',

22      properties: ['NAME']

23    }

24  ]

25 

26  let sql = `

27  SELECT

28  e.id AS ID,

29  e.first_name AS FIRST_NAME,

30  e.last_name AS LAST_NAME,

31  d.id  AS DEPT_ID,

32  d.name  AS DEPT_NAME

33  FROM ${schema}.employees as e

34  LEFT JOIN ${schema}.dept_emp as de on de.emp_id = e.id

35  LEFT JOIN ${schema}.departments as d on d.id = de.dept_id

36  `

37 

38  stmt.exec(sql, function(result,err) {

39    let result2 = jjs.map(result, maps, 'emp_dept_map')

40    console.log('result2:' + JSON.stringify(result2,null,2))

41  })

Line 01 brings in the new join-js npm and assigns it to variable jjs. Nothing too earth-shattering there.

Where things start to change is on lines 09 through 24. This is where we define mappings that will be used to convert the DB2 results to the JSON object we require. The mapId property allows us to modularize the composition of various entities in this configuration. Specifically, you can see there is a mapId property for emp_dept_map and dept_map; and you can also see that map emp_dept_map references map dept_map in the collections declaration. This is essentially a configuration syntax that maps the DB2 result set properties to a new structure. You can learn the full syntax of join-js on its Github README.md page.

The contents of the maps variable will make more sense once you look at lines 28 through 32. Here we can see the SQL statement has been changed to include the employees and departments id columns. I added these because that's what join-js requires. I also gave the result columns specific names so they were unique within the result set (i.e., e.id AS ID).

Running the program again, we get the below results.

[                                                                      

  {                                                                            

    "ID": "10001",

    "FIRST_NAME": "Georgi",

    "LAST_NAME": "Facello",

    "departments": [

      {

        "ID": "1",

        "NAME": "Marketing"

      },

      {

        "ID": "7",

        "NAME": "Sales"

      }

    ]

  },

  {

    "ID": "10002",

    "FIRST_NAME": "Bezalel",

    "LAST_NAME": "Simmel",

    "departments": [

      {

        "ID": "7",

        "NAME": "Sales"

      }

    ]

  },

  {

    "ID": "10003",

    "FIRST_NAME": "Parto",

    "LAST_NAME": "Bamford",

    "departments": [

      {

        "ID": "4",

        "NAME": "Production"

      }

    ]

  }

]

Success! This has a few more JSON properties than what I originally wanted (i.e., ID), but that's OK because what I really wanted was the relational structure of employee to departments, and that definitely came through.

It's worth noting that issues like this are already addressed in frameworks like Ruby on Rails through the ActiveRecord ORM gem, which means the IBM i Node.js community is still playing catchup in this area. Note I included "IBM i" as a qualifier in the previous sentence. That's because there are already a number of ORM solutions that exist for Node.js, though none for IBM i…yet. On that note, the IBM i community has started the sails-db2fori project that aims to be the first Node.js ORM implementation for IBM i. Please feel free to help out with the project.

If you have any questions or comments, then please comment below or email me at This email address is being protected from spambots. You need JavaScript enabled to view it..

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: