Posts Tagged: ‘JSX’

node.js, domino-db & Docker (4): Error Handling

1. November 2018 Posted by Sven Hasselbach

When we started our express application and accessed it in the browser, an error raised on the console and no response was sent back to the browser. The reason for this behaviour is that the database connection is not correctly configured, and the request from our application fails.

For a better understanding I have refactored the code to „old-school“ Javascript. The functions are called in a promise chain.

router.get('/', function(req, res, next) {
  useServer(serverConfig)
  .then(
      function(server){
        return server.useDatabase(databaseConfig)
      })
  .then(
      function(database){
        return database.bulkCreateDocuments(createOptions)
      })
  .then(
      function(response){
        const unids = response.documents.map(doc => doc['@unid']);
        res.render('index', { title: 'Express', result: `Documents created: ${unids}` });
      }
  );
});

1. The get method of the router calls the anonymous function (2nd parameter).

2. The chain starts: This function calls the useServer method of the domino-db package with the serverConfig.

3. If everything is OK, the next method in the chain is called with the server object (the result of the previous operation).

4. If everything is OK, the next method in the chain is called with the database object.

5. If everything is OK, the next method in the chain is called with the result object.

Promises have two callback functions: The first parameter is always the „success“ callback, and the second the „error“ callback. But we are not using a second parameter, because this allows us to use a catch function at the end of our chain:

router.get('/', function(req, res, next) {
  useServer(serverConfig)
  .then(
      ... )
  .then(
      ... )
  .then(
      ... )
  .catch(
    function(error) {
      console.log(error);
      res.render('error', { title: 'Error', error });
    }
  );
});

The catch block handles every error in our chain, and renders the view ‚error‚ with the reason of the failure.

If we now restart our application, the error is displayed to the end user with a stacktrace:

And now, we are refactoring the code using the arrow syntax:

router.get('/', (req, res) => {
  useServer(serverConfig)
  .then(server => server.useDatabase(databaseConfig))
  .then(database => database.bulkCreateDocuments(createOptions))
  .then(response => {
        const unids = response.documents.map(doc => doc['@unid']);
        res.render('index', { title: 'Express', result: `Documents created: ${unids}` });
  })
  .catch(error => {
      console.log(error);
      res.render('error', { title: 'Error', error });
    }
  );
});

A lot shorter, isn’t it?

At the end, we are using async/await syntax to shorten the promise chain too:

router.get('/', (req, res) => {
  useServer(serverConfig).then(
    async server => {
      const database = await server.useDatabase(databaseConfig);
      const response = await database.bulkCreateDocuments(createOptions);
      const unids = response.documents.map(doc => doc['@unid']);
      res.render('index', { title: 'Express', result: `Documents created: ${unids}` });
    }
  ).catch(error => {
      console.log(error);
      res.render('error', { title: 'Error', error });
  });
});

node.js, domino-db & Docker (3): Adding domino-db

31. Oktober 2018 Posted by Sven Hasselbach

The created express application is still the boilerplate created by express generator. Now let’s look into the existing code and use the domino-db package. First we have to understand express a little bit better. I won’t go deeply into details, because there are many tutorials available, and the documentation is really awesome.

Overview

Directory structure

/domino-express
   |-app
      |-app.js
      |-bin
         |-...
      |-public
         |-...
      |-routes
         |-...
      |-views
         |-...

app.js

This is the main application. It contains the configuration of the application and global modules (like used the middleware, global route handlers, etc.) are registered. At the moment we don’t need to change anything here.

/bin

This folder contains the starting script for the application.

/public

Contains publicly accessible static resources like images, stylesheets, etc.

/routes

The handling for existing routes, which means how the application should process incoming requests.

/views

Contains the templates for the generated output. We are using Jade as our template engine.

The boilerplate

The first thing to look at is the /routes/index.js file. Just open it in Atom, and see what the express generator created for us:

The first line loads the express package and gives access to it. The next line gives us access to the router, which then is used to define a handle for all incoming requests on the application root (http://localhost:3000/).

When this route is called, the defined function renders the response using the view template ‚index‘ (which can be found in the /views folder). The variables used in the template are contained in the object handed over as second parameter.

The last line exports the router instance and gives access to it outside of our module. Just for a better understanding: Everything in this file (aka module) is private, and here it is defined what is public to the rest of our express application. For more details, have a look here: https://www.sitepoint.com/understanding-module-exports-exports-node-js/

Change to JSX

After changing everything as proposed by the editor, the code should now look like this:

const express = require('express');

const router = express.Router();

/* GET home page. */
router.get('/', (req, res) => {
  res.render('index', { title: 'Express' });
});

module.exports = router;

Now we add the requirement for the domino-db package:

const { useServer } = require('@domino/domino-db');

The curly brackets notation is used to „import“ only the useServer element from the domino-db package.

Then we add the configuration for our Domino backend (shamelessly copied from the example in the dev pack):

const serverConfig = {
  hostName: 'your.server.com', // Host name of your server
  connection: {
    port: '3002', // Proton port on your server
  },
};

const databaseConfig = {
  filePath: 'node-demo.nsf', // The database file name
};

const createOptions = {
  documents: [
    {
      Form: 'Contact',
      FirstName: 'Aaron',
      LastName: 'Aardman',
      City: 'Arlington',
      State: 'MA',
    },
    {
      Form: 'Contact',
      FirstName: 'Brian',
      LastName: 'Zelnick',
      City: 'Chelmsford',
      State: 'MA',
    },
  ],
};

And now we add the connection of the database query when our base path is accessed:

router.get('/', (req, res) => {
  useServer(serverConfig).then(
      async server => {
        const database = await server.useDatabase(databaseConfig);
        const response = await database.bulkCreateDocuments(createOptions);

        // Display the new document UNIDs
        const unids = response.documents.map(doc => doc['@unid']);
        res.render('index', { title: 'Express', result: `Documents created: ${unids}` });
  });
});

Before we get into the details of this code, let’s start our application with npm start.After accessing the URL of the application http://localhost:3000, nothing happens.

Just some console output tells us that we need some error handling when our Domino server is not reachble.

GET / - - ms - -
(node:13268) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 6): DominoDbError: gRPC client error

This topic and more details about the domino-db module will be covered in the next post.

node.js, domino-db & Docker (2): Dev Environment

30. Oktober 2018 Posted by Sven Hasselbach

Before we can start to create a new app we first have to setup a development environment. While there are multiple IDE’s around, I have made most of my node.js development with Atom instead of an IDE like Eclipse or Visual Studio. Maybe this will change in the future, but for a better understanding, let’s start with Atom and do the required steps manually.

By default, there is no support for JSX, so we need to make an additional installation after installing the editor:

1. Download Atom from https://atom.io/

2. Go to Atom > Preferences

3. Install linter-eslint package

4. Additional packages must be installed (This happens multiple times):

5. In a console, go to the domino-express which we have created before:

cd domino-express/

6. Install eslint-config-rallycoding module

npm install --save-dev eslint-config-rallycoding

This step has to be done for every new project. The module is required to enable the JSX support for every project, but only during development.

7. Create a file named .eslintrc in the project folder and add the following content:

{
   "extends": "rallycoding"
}

8. Change the dependency for the domino-db package:

"@domino/domino-db": "file:./domino-domino-db-1.0.0-package"

The path has to be changed because for the Docker setup it is in the /src folder, now it is in the project root.

9. Install the required npm modules

npm install

10. Restart Atom and open the project folder

11. If everything worked correctly, you should now see an error in the index.js file (maybe you have to open the file first):

12. When opening the file, you should see an error in the first line and an explanation about the problem:

13. Click on „Fix“, then var should change to let

14. An new problem occurs, because the variable is never changed. So the advice is to change it to const.

15. Done. Now we are ready for developing.