Category Archives: All About Software Technology

React Components – From OOP To FP

In recent years, there has been an increasingly noticeable trend in software development that prompted developers to transition from object oriented programming (OOP) to functional programming (FP), whenever applicable. React appears to have joined the “movement” and its object oriented class-based React components have been transitioned to the functional components with React Hooks. A similar trend in the Scala world is the ad-hoc polymorphism with type classes as opposed to classic subtype polymorphism.

Given React‘s massive adoption rate and its API being evolved at a breakneck pace, we’re seeing a lot of React applications using a mix of both styles. Inevitably, some old method calls gradually get deprecated in order to align with the design principles of the new Hooks APIs. To maintain backward compatibility while evolving with the new functional approach, wrappers are being used to bundle the React Hooks with the class-based React components.

React Hooks in class-based components

For instance, for a User component to be able to reference the user-id from a HTTP GET query parameter via a React service, the useParams hook can be employed by being wrapped with the User component as a WrappedComponent.

import { connect } from "react-redux";
import { useParams } from "react-router-dom";
import UserDataService from "../services/user.service";

export const withParams = (WrappedComponent) => (props) => {
  const params = useParams();
  return <WrappedComponent {...props} params={params} />;
};
...

class User extends Component {
  ...
  componentDidMount() {
    this.getUser(this.props.params.id);
  }
  ...
  getUser(id) {
    UserDataService.find(id)
      .then(...)
      .catch(...);
  }
  ...
  render() {
    ...
    return {
      // Display UI
      ...
    }
  }
}

export default connect()(withParams(User));

A couple of notes:

  1. While a React hook looks like an ordinary function, it can only be used at the top level (or inside a custom React hook) and cannot be used within the React component class.
  2. If additional React Hooks are needed, they’d have to be successively wrapped. Say, if hooks useNavigate and useLocation are included, one would need to compose the withNavigate and withLocation top-level functions followed by wrapping them as WrappedComponent like below:
export default connect()(withLocation(withNavigate(withParams(User))));

React Hooks in functional components

Even though React Hooks are by design for functional components, the limitation of being at the top level (or from within custom hooks) still holds. That’s because the state of the hooks are internally “intertwined” with the React renderer throughout the rendering cycle of the React DOM.

Here’s what a functional equivalence of the above class-based component might look like:

import React, { useEffect } from "react";
import { useParams } from "react-router-dom";
import UserDataService from "../services/user.service";
...

const User = () => {
  const params = useParams();
  ...
  useEffect(() => {
    getUser(params.id);
  }, [params.id]);
  const getUser = (id) => {
    UserDataService.find(id)
      .then(...)
      .catch(...);
  }
  ...
  return (
    // Display UI
    ...
  )
}

export default User;

Comparing a class-based component with a functional component

As almost always the case, the easiest way to see the key differences between class-based and functional React components is to skim through the class-based and functional versions of a typical component with equivalent functionality.

First, a sample snippet of a class-based React component:

import React, { Component } from "react";
import { connect } from "react-redux";
import { Link, useParams } from "react-router-dom";
import { updateUser } from "../actions/user";
import UserDataService from "../services/user.service";

export const withParams = (WrappedComponent) => (props) => {
  const params = useParams();
  return <WrappedComponent {...props} params={params} />;
};

class User extends Component {  // User is a class

  constructor(props) {
    super(props);
    this.onChangeUsername = this.onChangeUsername.bind(this);
    this.onChangeEmail = this.onChangeEmail.bind(this);
    this.onChangeFirstName = this.onChangeFirstName.bind(this);
    this.onChangeLastName = this.onChangeLastName.bind(this);
    this.getUser = this.getUser.bind(this);
    this.updateContent = this.updateContent.bind(this);
    this.state = {
      currentUser: {
        id: null,
        username: "",
        email: "",
        firstName: "",
        lastName: ""
      },
      message: ""
    };
  }

  componentDidMount() {  // Component lifecycle function called after render() is called
    this.getUser(this.props.params.id);
  }

  // onChange functions for each input fields as class methods

  onChangeUsername(e) {
    const username = e.target.value;
    this.setState(function (prevState) {
      return {
        currentUser: {
          ...prevState.currentUser,
          setState: setState,
        },
      };
    });
  }

  onChangeEmail(e) {
    const email = e.target.value;
    this.setState(function (prevState) {
      return {
        currentUser: {
          ...prevState.currentUser,
          email: email,
        },
      };
    });
  }

  onChangeFirstName(e) {
    const firstName = e.target.value;
    this.setState((prevState) => ({
      currentUser: {
        ...prevState.currentUser,
        firstName: firstName,
      },
    }));
  }

  onChangeLastName(e) {
    const lastName = e.target.value;
    this.setState((prevState) => ({
      currentUser: {
        ...prevState.currentUser,
        lastName: lastName,
      },
    }));
  }

  getUser(id) {
    UserDataService.find(id)
      .then(...)    // Logic for handling return from
      .catch(...);  // service call skipped.
  }

  updateContent() {
    this.props
      .updateUser(this.state.currentUser.id, this.state.currentUser)
      .then(...)    // Logic for handling return from
      .catch(...);  // service call skipped.
  }

  render() {  // Rendering after constructor() is called
    const { currentUser, message } = this.state;
    const { loginUser } = this.props;
    return (
      <div className="list row">
        <div className="col-md-9">
          {currentUser && (currentUser.id === loginUser.id || loginUser.roles.includes('ROLE_ADMIN')) ? (
            <div className="edit-form">
              <h4>User</h4>
              <form>
                <div className="row mt-2">
                  <label className="col-md-3" htmlFor="id">ID</label>
                  <input
                    type="number"
                    className="col-md-9"
                    id="id"
                    value={currentUser.id}
                    disabled readOnly
                  />
                </div>
                <div className="row mt-2">
                  <label className="col-md-3" htmlFor="username">Username</label>
                  <input
                    type="text"
                    className="col-md-9"
                    id="username"
                    value={currentUser.username}
                    disabled readOnly
                  />
                </div>
                <div className="row mt-2">
                  <label className="col-md-3" htmlFor="email">Email</label>
                  <input
                    type="text"
                    className="col-md-9"
                    id="email"
                    value={currentUser.email}
                    onChange={this.onChangeEmail}
                  />
                </div>
                <div className="row mt-2">
                  <label className="col-md-3" htmlFor="firstName">First Name</label>
                  <input
                    type="text"
                    className="col-md-9"
                    id="firstName"
                    value={currentUser.firstName}
                    onChange={this.onChangeFirstName}
                  />
                </div>
                <div className="row mt-2">
                  <label className="col-md-3" htmlFor="lastName">Last Name</label>
                  <input
                    type="text"
                    className="col-md-9"
                    id="lastName"
                    value={currentUser.lastName}
                    onChange={this.onChangeLastName}
                  />
                </div>
              </form>
              <p className="text-warning">{message}</p>
              <button
                type="submit"
                className="btn btn-warning mt-2 mb-2"
                onClick={this.updateContent}
              >
                Update
              </button>
            </div>
          ) : (
            <div>
              <br />
              <p>User access not permitted!</p>
            </div>
          )}
        </div>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    loginUser: state.auth.user
  };
};

export default connect(mapStateToProps, { updateUser })(withParams(User));
// Using connect() for state info in Redux store

Next, an example of a functional style React component with equivalent functionality:

import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Link, useParams } from "react-router-dom";
import { updateUser } from "../actions/user";
import UserDataService from "../services/user.service";

const User = () => {
  const params = useParams();
  const dispatch = useDispatch();
  const loginUser = useSelector(state => state.auth.user);

  const initUserState = {
    id: params.id,
    username: "",
    email: "",
    firstName: "",
    lastName: ""
  };

  const [currentUser, setCurrentUser] = useState(initUserState);
  const [message, setMessage] = useState("");

  const handleUserChange = event => {
    const { id, value } = event.target;
    setCurrentUser({ ...currentUser, [id]: value });
  };

  useEffect(() => {
    getUser(params.id);
  }, [params.id]);

  const getUser = (id) => {
    UserDataService.find(id)
      .then(...)    // Logic for handling return from
      .catch(...);  // service call skipped.
  };

  const updateContent = () => {
    dispatch(updateUser(currentUser.id, currentUser))
      .then(...)    // Logic for handling return from
      .catch(...);  // service call skipped.
  };

  return (
    <div className="list row">
      <div className="col-md-9">
        {currentUser && (currentUser.id === loginUser.id || loginUser.roles.includes('ROLE_ADMIN')) ? (
          <div className="edit-form">
            <h4>User</h4>
            <form>
              <div className="row mt-2">
                <label className="col-md-3" htmlFor="id">ID</label>
                <input
                  type="number"
                  className="col-md-9"
                  id="id"
                  value={currentUser.id}
                  disabled readOnly
                />
              </div>
              <div className="row mt-2">
                <label className="col-md-3" htmlFor="username">Username</label>
                <input
                  type="text"
                  className="col-md-9"
                  id="username"
                  value={currentUser.username}
                  disabled readOnly
                />
              </div>
              <div className="row mt-2">
                <label className="col-md-3" htmlFor="email">Email</label>
                <input
                  type="text"
                  className="col-md-9"
                  id="email"
                  value={currentUser.email}
                  onChange={handleUserChange}
                />
              </div>
              <div className="row mt-2">
                <label className="col-md-3" htmlFor="firstName">First Name</label>
                <input
                  type="text"
                  className="col-md-9"
                  id="firstName"
                  value={currentUser.firstName}
                  onChange={handleUserChange}
                />
              </div>
              <div className="row mt-2">
                <label className="col-md-3" htmlFor="lastName">Last Name</label>
                <input
                  type="text"
                  className="col-md-9"
                  id="lastName"
                  value={currentUser.lastName}
                  onChange={handleUserChange}
                />
              </div>
            </form>
            <p className="text-warning">{message}</p>
            <button
              type="submit"
              className="btn btn-warning mt-2 mb-2"
              onClick={updateContent}
            >
              Update
            </button>
          </div>
        ) : (
          <div>
            <br />
            <p>User access not permitted!</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default User;

Differences between class-based and functional React components

Summarizing the key differences:

  1. Using of React Hooks – As highlighted earlier in this post, for the class-based component, the React hook needs to be wrapped as a WrappedComponent class, whereas it’s being used as a top-level function in a functional component.
  2. Class methods with binding vs regular functions – In the class-based component, each class method requires binding (i.e. .bind(this)) within the constructor so as to make keyword this refer to the component context, allowing the method to access component attributes such as this.props, this.state. On the other hand, functions for UI events in the functional component are no different from regular functions.
  3. State changes – State changes within a class-based component are typically initialized and maintained as class fields each with its corresponding event handler as a class method. In a functional component, state changes are managed via the useState React hook.
  4. Event handling – For the class-based component, in addition to binding, each input field needs to have its own onChange event handler (e.g. class method onChangeUsername), whereas for the functional component, it could be much less verbose by generalizing individual event handers into a single handleUserChange function as long as the onChange event handling logics for the input fields are similar.
  5. Rendering lifecycle – A class-based component has a lifecycle of constructor → render() → componentDidMount(), in that order. For a functional component, various kinds of React hooks have their specific “hooks” associated with the component’s lifecycle, whereas ordinary function calls within the main component are handled in programmatic order
  6. Managing state in React Redux store – Class-based components rely on the connect API along with specialty functions such as mapStateToProps to be called upon state changes in the Redux store to extract state info into the component. As for functional components, certain React Hooks including useSelector can be used for fetching state data from Redux store, as shown in the previous blog post.

Final thoughts

Based on what we’ve gone over, the functional approach to creating a React component obviously offers some advantages over the class-based approach. Code readability due to the minimizing of boilerplate code and consistency of treating event handlers as functions is perhaps the biggest plus.

Looking at the sample source code, the difference between class-based and functional components might seem drastic. But once we’ve had some fundamental understanding of how a React component handles UI events and maintains states throughout its lifecycle, the difference would become self-explanatory.

Nonetheless, migrating a large amount of class-based React components would still require significant investment in coding as well as testing. Since there is no sign support of class-based components will end any time soon, I’d say leaving the already proven working code as a mid-to-low priority tech debt is reasonable.

React Redux – Actions & Reducers

Having immersed in coding JavaScript exclusively using Node.js and React over the past couple of months, I’ve come to appreciate the versatility and robustness the “combo” has to offer. I’ve always liked the minimalist design of Node.js, and would always consider it a top candidate whenever building an app/API server is needed. Besides ordinary app servers, Node has also been picked on a few occasions to serve as servers for decentralized applications (dApps) that involve smart contract deployments to public blockchains. In fact, Node and React are also a popular tech stack for dApp frameworks such as Scaffold-ETH.

React & React Redux

React is relatively new to me, though it’s rather easy to pick up the basics from React‘s official site. And many tutorials out there showcase how to build applications using React along with the feature-rich toolset within the React ecosystem. For instance, this tutorial code repo offers helpful insight for developing a React application with basic CRUD.

React can be complemented with Redux that allows a central store for state update in the UI components. Contrary to the local state maintained within an React component (oftentimes used for handling interactive state changes to input form elements), the central store can be shared across multiple components for state update. That’s a key feature useful for the R&D project at hand.

Rather than just providing a plain global state repository for direct access, the React store is by design “decoupled” from the components. React Redux allows custom programmatic actions to be structured by user-defined action types. To dispatch an action, a component would invoke a dispatch() function which is the only mechanism that triggers a state change.

React actions & reducers

In general, a React action which is oftentimes dispatched in response to an UI event (e.g. a click on a button) mainly does two things:

  1. It carries out the defined action which is oftentimes an asynchronous function that invokes a user-defined React service which, for instance, might be a client HTTP call to a Node.js server.
  2. It connects with the Redux store and gets funneled into a reduction process. The reduction is performed thru a user-defined reducer which is typically a state aggregation of the corresponding action type.

An action might look something like below:

const myAction = () => async (dispatch) => {
  try {
    const res = await myService.someFunction();
    dispatch({
      type: someActionType,
      payload: res.data,
    });
  } catch (err) {
    ...
  }
};

whereas a reducer generally has the following function signature:

const myReducer = (currState = prevState, action) => {
  const { type, payload } = action;
  switch (type) {
    case someActionType:
      return someFormOfPayload;
    case anotherActionType:
      return anotherFormOfPayload;
    ...
    default:
      return currState;
  }
};

Example of a React action

${react-project-root}/src/actions/user.js

import {
  CREATE_USER,
  RETRIEVE_USERS,
  UPDATE_USER,
  DELETE_USER
} from "./types";
import UserDataService from "../services/user.service";
export const createUser = (username, password, email, firstName, lastName) => async (dispatch) => {
  try {
    const res = await UserDataService.create({ username, password, email, firstName, lastName });
    dispatch({
      type: CREATE_USER,
      payload: res.data,
    });
    return Promise.resolve(res.data);
  } catch (err) {
    return Promise.reject(err);
  }
};
export const findUsersByEmail = (email) => async (dispatch) => {
  try {
    const res = await UserDataService.findByEmail(email);
    dispatch({
      type: RETRIEVE_USERS,
      payload: res.data,
    });
  } catch (err) {
    console.error(err);
  }
};
export const updateUser = (id, data) => async (dispatch) => {
  try {
    const res = await UserDataService.update(id, data);
    dispatch({
      type: UPDATE_USER,
      payload: data,
    });
    return Promise.resolve(res.data);
  } catch (err) {
    return Promise.reject(err);
  }
};
export const deleteUser = (id) => async (dispatch) => {
  try {
    await UserDataService.delete(id);
    dispatch({
      type: DELETE_USER,
      payload: { id },
    });
  } catch (err) {
    console.error(err);
  }
};

Example of a React reducer

${react-project-root}/src/reducers/users.js

import {
  CREATE_USER,
  RETRIEVE_USERS,
  UPDATE_USER
  DELETE_USER,
} from "../actions/types";
const initState = [];
function userReducer(users = initState, action) {
  const { type, payload } = action;
  switch (type) {
    case CREATE_USER:
      return [...users, payload];
    case RETRIEVE_USERS:
      return payload;
    case UPDATE_USER:
      return users.map((user) => {
        if (user.id === payload.id) {
          return {
            ...user,
            ...payload,
          };
        } else {
          return user;
        }
      });
    case DELETE_USER:
      return users.filter(({ id }) => id !== payload.id);
    default:
      return users;
  }
};
export default userReducer;

React components

Using React Hooks which are built-in functions, the UI-centric React components harness powerful features related to handling states, programmatic properties, parametric attributes, and more.

To dispatch an action, the useDispatch hook for React Redux can be used that might look like below:

import { useDispatch, useSelector } from "react-redux";
...
  const dispatch = useDispatch();
  ...
    dispatch(myAction(someRecord.id, someRecord))  // Corresponding service returns a promise
      .then((response) => {
        setMessage("myAction successful!");
        ...
      })
      .catch(err => {
        ...
      });
  ...

And to retrieve the state of a certain item from the Redux store, the userSelector hook allow one to use a selector function to extract the target item as follows:

  const myRecords = useSelector(state => state.myRecords);  // Reducer myRecords.js

Example of a React component

${react-project-root}/src/components/UserList.js

import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Link } from "react-router-dom";
import { retrieveUsers, findUsersByEmail } from "../actions/user";
const UserList = () => {
  const dispatch = useDispatch();
  const users = useSelector(state => state.users);
  const [currentUser, setCurrentUser] = useState(null);
  const [currentIndex, setCurrentIndex] = useState(-1);
  const [searchEmail, setSearchEmail] = useState("");
  useEffect(() => {
    dispatch(retrieveUsers());
  }, [dispatch]);
  const onChangeSearchEmail = e => {
    const searchEmail = e.target.value;
    setSearchEmail(searchEmail);
  };
  const refreshData = () => {
    setCurrentUser(null);
    setCurrentIndex(-1);
  };
  const setActiveUser = (user, index) => {
    setCurrentUser(user);
    setCurrentIndex(index);
  };
  const findByEmail = () => {
    refreshData();
    dispatch(findUsersByEmail(searchEmail));
  };
  return (
    <div className="list row">
      <div className="col-md-9">
        <div className="input-group mb-3">
          <input
            type="text"
            className="form-control"
            id="searchByEmail"
            placeholder="Search by email"
            value={searchEmail}
            onChange={onChangeSearchEmail}
          />
          <div className="input-group-append">
            <button
              className="btn btn-warning m-2"
              type="button"
              onClick={findByEmail}
            >
              Search
            </button>
          </div>
        </div>
      </div>
      <div className="col-md-5">
        <h4>User List</h4>
        <ul className="list-group">
          {users &&
            users.map((user, index) => (
              <li
                className={
                  "list-group-item " + (index === currentIndex ? "active" : "")
                }
                onClick={() => setActiveUser(user, index)}
                key={index}
              >
                <div className="row">
                  <div className="col-md-2">{user.id}</div>
                  <div className="col-md-10">{user.email}</div>
                </div>
              </li>
            ))}
        </ul>
        <Link to="/add-user"
          className="btn btn-warning mt-2 mb-2"
        >
          Create a user
        </Link>
      </div>
      <div className="col-md-7">
        {currentUser ? (
          <div>
            <h4>User</h4>
            <div className="row">
              <div className="col-md-3 fw-bold">ID:</div>
              <div className="col-md-9">{currentUser.id}</div>
            </div>
            <div className="row">
              <div className="col-md-3 fw-bold">Username:</div>
              <div className="col-md-9">{currentUser.username}</div>
            </div>
            <div className="row">
              <div className="col-md-3 fw-bold">Email:</div>
              <div className="col-md-9">{currentUser.email}</div>
            </div>
            <div className="row">
              <div className="col-md-3 fw-bold">First Name:</div>
              <div className="col-md-9">{currentUser.firstName}</div>
            </div>
            <div className="row">
              <div className="col-md-3 fw-bold">Last Name:</div>
              <div className="col-md-9">{currentUser.lastName}</div>
            </div>
            <Link
              to={"/user/" + currentUser.id}
              className="btn btn-warning mt-2 mb-2"
            >
              Edit
            </Link>
          </div>
        ) : (
          <div>
            <br />
            <p>Please click on a user for details ...</p>
          </div>
        )}
      </div>
    </div>
  );
};
export default UserList;

It should be noted that, despite having been stripped down for simplicity, the above sample code might still have included a little bit too much details for React beginners. For now, the primary goal is to highlight how an action is powered by function dispatch() in accordance with a certain UI event to interactively update state in the Redux central store thru a corresponding reducer function.

In the next blog post, we’ll dive a little deeper into React components and how they have evolved from the class-based OOP (object oriented programming) to the FP (functional programming) style with React Hooks.

Node.js, PostgreSQL With Sequelize

A recent project has prompted me to adopt Node.js, a popular by-design lean and mean server, as the server-side tech stack. With the requirement for a rather UI feature-rich web application, I include React (a.k.a. ReactJS) as part of the tech stack. A backend database is needed, so I pick PostgreSQL. Thus, this is a deviation from the Scala / Akka Actor / Akka Stream tech stack I’ve been using in recent years.

PostgreSQL has always been one of my favorite database choices whenever a robust RDBMS with decent scalability is required for a given R&D project. With Node.js being the chosen app/API server and React the UI library for the project at hands, I decided to use Sequelize, a popular ORM tool in the Node ecosystem, as the ORM tool.

First and foremost, I must acknowledge the effective documentation on Sequelize’s official website, allowing developers new to it to quickly pick up the essential know-how’s from:

to the more advanced topics like:

Getting started

Assuming the Node.js module is already in place, to install PostgreSQL driver and Sequelize, simply do the following under the Node project root subdirectory:

$ npm install --save pg pg-hstore
$ npm install --save sequelize

Next, create a configuration script ${node-project-root}/app/config/db.config.js for PostgreSQL like below:

module.exports = {
  HOST: "localhost",
  USER: "leo",
  PASSWORD: "changeme!",
  DB: "leo",
  dialect: "postgres",
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
};

For the data model, let’s create script files for a few sample tables under ${node-project-root}/app/models/:

# user.model.js 

module.exports = (sequelize, Sequelize) => {
  const User = sequelize.define("users", {
    username: {
      type: Sequelize.STRING
    },
    email: {
      type: Sequelize.STRING
    },
    password: {
      type: Sequelize.STRING
    },
    firstName: {
      type: Sequelize.STRING
    },
    lastName: {
      type: Sequelize.STRING
    }
  });
  return User;
};
# role.model.js

module.exports = (sequelize, Sequelize) => {
  const Role = sequelize.define("roles", {
    id: {
      type: Sequelize.INTEGER,
      primaryKey: true
    },
    name: {
      type: Sequelize.STRING
    }
  });
  return Role;
};
# order.model.js

module.exports = (sequelize, Sequelize) => {
  const Order = sequelize.define("orders", {
    orderDate: {
      type: Sequelize.DATE
    },
    userId: {
      type: Sequelize.INTEGER
    },
    // add other attributes here ...
  });
  return Order;
};
# item.model.js

module.exports = (sequelize, Sequelize) => {
  const Item = sequelize.define("items", {
    serialNum: {
      type: Sequelize.STRING
    },
    orderId: {
      type: Sequelize.INTEGER
    },
    // add other attributes here ...
  });
  return Item;
};

Sequelize instance

Note that within the above data model scripts, each of the table entities is represented by a function with two arguments — Sequelize refers to the Sequelize library, whereas sequelize is an instance of it. The instance is what’s required to connect to a given database. It has a method define() responsible for specifying the table definition including the table attributes and the by-default pluralized table name.

Also note that it looks as though the typical primary key column id is missing in most of the above table definitions. That’s because Sequelize would automatically create an auto-increment integer column id if none is specified. For a table intended to be set up with specific primary key values, define it with explicitly (similar to how table roles is set up in our sample models).

The Sequelize instance is created and initialized within ${node-project-root}/app/models/index.js as shown below.

# ${node-project-root}/app/models/index.js

const config = require("../config/db.config.js");
const Sequelize = require("sequelize");
const sequelize = new Sequelize(
  config.DB,
  config.USER,
  config.PASSWORD,
  {
    host: config.HOST,
    dialect: config.dialect,
    pool: {
      max: config.pool.max,
      min: config.pool.min,
      acquire: config.pool.acquire,
      idle: config.pool.idle
    }
  }
);
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.user = require("../models/user.model.js")(sequelize, Sequelize);
db.role = require("../models/role.model.js")(sequelize, Sequelize);
db.order = require("../models/order.model.js")(sequelize, Sequelize);
db.item = require("../models/item.model.js")(sequelize, Sequelize);
db.role.belongsToMany(db.user, {
  through: "user_role"
});
db.user.belongsToMany(db.role, {
  through: "user_role"
});
db.user.hasMany(db.order, {
  as: "order"
});
db.order.belongsTo(db.user, {
  foreignKey: "userId",
  as: "user"
});
db.order.hasMany(db.item, {
  as: "item"
});
db.item.belongsTo(db.order, {
  foreignKey: "orderId",
  as: "order"
});
db.ROLES = ["guest", "user", "admin"];
module.exports = db;

Data model associations

As can be seen from the index.js data model script, after a Sequelize instance is instantiated, it loads the database configuration information from db.config.js as well as the table definitions from the individual model scripts.

Also included in the index.js script are examples of both the one-to-many and many-to-many association types. For instance, the relationship between table users and orders is one-to-many with userId as the foreign key:

db.user.hasMany(db.order, {
  as: "order"
});
db.order.belongsTo(db.user, {
  foreignKey: "userId",
  as: "user"
});

whereas relationship between users and roles is many-to-many.

db.role.belongsToMany(db.user, {
  through: "user_role"
});
db.user.belongsToMany(db.role, {
  through: "user_role"
});

Database schema naming conventions

Contrary to the camelCase naming style for variables in programming languages such as JavaScript, Java, Scala, conventional RDBMSes tend to use snake_case naming style for table and column names. To accommodate the different naming conventions, Sequelize automatically converts database schemas’ snake_case style to JavaScript objects’ camelCase. To keep the database schema in snake_case style one can customize the Sequelize instance by specifying underscored: true within the define {} segment as shown below.

As mentioned in an earlier section, Sequelize pluralizea database table names by default. To suppress the auto-pluralization, specifying also freezeTableName: true within define {} followed by defining the table with singular names within the individual model scripts.

const sequelize = new Sequelize(
  config.DB,
  config.USER,
  config.PASSWORD,
  {
    host: config.HOST,
    dialect: config.dialect,
    pool: {
      max: config.pool.max,
      min: config.pool.min,
      acquire: config.pool.acquire,
      idle: config.pool.idle
    },
    define: {
      underscored: true,
      freezeTableName: true
    }
  }
);

An “inconvenience” in PostgreSQL

Personally, I prefer keeping database table names singular. However, I have a table I’d like to name it user which is disallowed within PostgreSQL’s default schema namespace. That’s because PostgreSQL makes user a reserved keyword.

A work-around would be to define a custom schema that serves as a namespace in which all user-defined entities are contained. An inconvenient consequence is that when performing queries using tools like psql, one would need to alter the schema search path from the default public schema to the new one.

ALTER ROLE leo SET search_path TO myschema;

After weighing the pros and cons, I decided to go with Sequelize‘s default pluralized table naming. Other than this minor inconvenience, I find Sequelize an easy-to-pick-up ORM for wiring programmatic CRUD operations with PostgreSQL from within Node’s controller modules.

The following sample snippet highlights what a simple find-by-primary-key select and update might look like in a Node controller:

const db = require("../models");
const User = db.user;
...

exports.find = (req, res) => {
  const id = req.params.id;
  User.findByPk(id)
    .then(data => {
      if (data) {
        res.send(data);
      } else {
        res.status(404).send({
          message: `ERROR finding user with id=${id}!`
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: `ERROR retrieving user data!`
      });
    });
};

exports.update = (req, res) => {
  const id = req.params.id;
  User.update(req.body, {
    where: { id: id }
  })
    .then(num => {
      if (num == 1) {
        res.send({
          message: "User was updated successfully!"
        });
      } else {
        res.send({
          message: `ERROR updating user with id=${id}!`
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: `ERROR updating user data!`
      });
    });
};

In the next blog post, we’ll shift our focus towards the popular UI library React and how state changes propagate across the UI components and the React Redux central store.