MC Press Online

Monday, Jun 26th

Last updateFri, 23 Jun 2017 1pm

You are here: Home ARTICLES Programming Programming - Other TechTip: Node.js JoinJS

Programming - Other

TechTip: Node.js JoinJS

 

Support MC Press - Visit Our Sponsors
FORUMS
Element Break 290x14

Visit the MC Press Bookstore for New and Best Selling Titles Today! Print and e-Books available for most!

Element Break 290x14

Best-Selling

Evolve Your RPG Coding: Move from OPM to ILE ... and Beyond


ORDER YOUR COPY

*******************

Click for this Month's

Bookstore Special Deals

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..

Aaron Bartell

Aaron Bartell is Director of IBM i Innovation for Krengel Technology, Inc. Aaron facilitates adoption of open-source technologies on IBM i through professional services, staff training, speaking engagements, and the authoring of best practices within industry publications and www.litmis.comWith a strong background in RPG application development, Aaron covers topics that enable IBM i shops to embrace today's leading technologies, including Ruby on Rails, Node.js, Git for RPG source change management, and RSpec for unit testing RPG. Aaron is a passionate advocate of vibrant technology communities and the corresponding benefits available for today's modern application developers. Connect with Aaron via email at abartell@krengeltech.com.

Aaron lives with his wife and five children in southern Minnesota. He enjoys the vast amounts of laughter that having a young family brings, along with camping and music. He believes there's no greater purpose than to give of our life and time to help others.

More Articles By This Author
Related Articles
BLOG COMMENTS POWERED BY DISQUS