Table of Contents for
Node.js 8 the Right Way

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Node.js 8 the Right Way by Jim Wilson Published by Pragmatic Bookshelf, 2018
  1. Title Page
  2. Node.js 8 the Right Way
  3. Node.js 8 the Right Way
  4. Node.js 8 the Right Way
  5. Node.js 8 the Right Way
  6.  Acknowledgments
  7.  Preface
  8. Why Node.js the Right Way?
  9. What’s in This Book
  10. What This Book Is Not
  11. Code Examples and Conventions
  12. Online Resources
  13. Part I. Getting Up to Speed on Node.js 8
  14. 1. Getting Started
  15. Thinking Beyond the web
  16. Node.js’s Niche
  17. How Node.js Applications Work
  18. Aspects of Node.js Development
  19. Installing Node.js
  20. 2. Wrangling the File System
  21. Programming for the Node.js Event Loop
  22. Spawning a Child Process
  23. Capturing Data from an EventEmitter
  24. Reading and Writing Files Asynchronously
  25. The Two Phases of a Node.js Program
  26. Wrapping Up
  27. 3. Networking with Sockets
  28. Listening for Socket Connections
  29. Implementing a Messaging Protocol
  30. Creating Socket Client Connections
  31. Testing Network Application Functionality
  32. Extending Core Classes in Custom Modules
  33. Developing Unit Tests with Mocha
  34. Wrapping Up
  35. 4. Connecting Robust Microservices
  36. Installing ØMQ
  37. Publishing and Subscribing to Messages
  38. Responding to Requests
  39. Routing and Dealing Messages
  40. Clustering Node.js Processes
  41. Pushing and Pulling Messages
  42. Wrapping Up
  43. Node.js 8 the Right Way
  44. Part II. Working with Data
  45. 5. Transforming Data and Testing Continuously
  46. Procuring External Data
  47. Behavior-Driven Development with Mocha and Chai
  48. Extracting Data from XML with Cheerio
  49. Processing Data Files Sequentially
  50. Debugging Tests with Chrome DevTools
  51. Wrapping Up
  52. 6. Commanding Databases
  53. Introducing Elasticsearch
  54. Creating a Command-Line Program in Node.js with Commander
  55. Using request to Fetch JSON over HTTP
  56. Shaping JSON with jq
  57. Inserting Elasticsearch Documents in Bulk
  58. Implementing an Elasticsearch Query Command
  59. Wrapping Up
  60. Node.js 8 the Right Way
  61. Part III. Creating an Application from the Ground Up
  62. 7. Developing RESTful Web Services
  63. Advantages of Express
  64. Serving APIs with Express
  65. Writing Modular Express Services
  66. Keeping Services Running with nodemon
  67. Adding Search APIs
  68. Simplifying Code Flows with Promises
  69. Manipulating Documents RESTfully
  70. Emulating Synchronous Style with async and await
  71. Providing an Async Handler Function to Express
  72. Wrapping Up
  73. 8. Creating a Beautiful User Experience
  74. Getting Started with webpack
  75. Generating Your First webpack Bundle
  76. Sprucing Up Your UI with Bootstrap
  77. Bringing in Bootstrap JavaScript and jQuery
  78. Transpiling with TypeScript
  79. Templating HTML with Handlebars
  80. Implementing hashChange Navigation
  81. Listing Objects in a View
  82. Saving Data with a Form
  83. Wrapping Up
  84. 9. Fortifying Your Application
  85. Setting Up the Initial Project
  86. Managing User Sessions in Express
  87. Adding Authentication UI Elements
  88. Setting Up Passport
  89. Authenticating with Facebook, Twitter, and Google
  90. Composing an Express Router
  91. Bringing in the Book Bundle UI
  92. Serving in Production
  93. Wrapping Up
  94. Node.js 8 the Right Way
  95. 10. BONUS: Developing Flows with Node-RED
  96. Setting Up Node-RED
  97. Securing Node-RED
  98. Developing a Node-RED Flow
  99. Creating HTTP APIs with Node-RED
  100. Handling Errors in Node-RED Flows
  101. Wrapping Up
  102. A1. Setting Up Angular
  103. A2. Setting Up React
  104. Node.js 8 the Right Way

Listing Objects in a View

Using the webpack dev server, it’s easy to quickly see the rendered output of statically served content. But how do you access web services like those we implemented in the last chapter?

Ideally, we’d have one Node.js server that serves the front-end static content and handles the API requests. We’ll achieve that in the next chapter, when we pull it all together, but for now they’re two separate things.

Fortunately, the webpack dev server has a capability that can help us. By configuring proxies in the webpack.config.js file, we can have the webpack dev server reach out to API endpoints and forward the results.

Configuring a webpack-dev-server Proxy

Web browsers have strict rules about the conditions under which a page can connect to a service. A proxy is an endpoint that acts as a passthrough to another service. For development purposes, configuring a webpack-dev-server proxy is a convenient way to provide access to services before the whole system is ready end to end.

To configure the proxies, start by opening your webpack.config.js file for editing. In the module.exports, under the devServer configuration, add a proxy object to make it look like the following:

 devServer: {
  contentBase: distDir,
  port: 60800,
  proxy: {
 '/api'​: ​'http://localhost:60702'​,
 '/es'​: {
  target: ​'http://localhost:9200'​,
  pathRewrite: {​'^/es'​ : ​''​},
  }
  },
 },

This specifies that requests to /api should be sent as is to the localhost service running on port 60702—that is, the Express server we developed in Writing Modular Express Services.

It also exposes requests directly to Elasticsearch through the endpoint /es. We haven’t developed APIs that work for specific users yet, so we need to bypass the API layer and go directly to Elasticsearch for some things. This is a temporary workaround that we won’t need in the next chapter, when we create a consolidated server and fill in the authenticated user APIs.

Elasticsearch APIs begin at the root, so we need to strip off the leading /es, which is what the pathRewrite setting is for. You could use this same technique to proxy requests to other services as well, but you should be careful with what you proxy. Unconstrained proxy services can become vulnerabilities when they expose access to services, or levels of privilege on those services, that should not be available to the end user.

Once you save this file, you’ll need to restart your webpack dev server to pick up the changes. You’ll also need to make sure you’re running the Express web services from the last chapter, and make sure your local Elasticsearch cluster is up and running. With those services running, now we can implement a view that uses data from them, as served through the proxy.

Implementing a View

To implement a view that lists the user’s bundles, we’ll need a couple of things. First we’ll need a way of retrieving the bundles asynchronously from the server. Next we’ll need a function that renders the list using a compiled Handlebars template to produce displayable HTML. And lastly we’ll need to add the hash route to the showView function to tie it all together.

Let’s start with the bundle-retrieving task. Open your app/index.ts and insert the following getBundles async function after the imports and page-setup part of the file.

 const​ getBundles = ​async​ () => {
 const​ esRes = ​await​ fetch(​'/es/b4/bundle/_search?size=1000'​);
 
 const​ esResBody = ​await​ esRes.json();
 
 return​ esResBody.hits.hits.map(hit => ({
  id: hit._id,
  name: hit._source.name,
  }));
 };

This method starts off by issuing an asynchronous request to Elasticsearch through the global fetch method.[81] This is a Promise-producing function that initiates an HTTP request with the provided settings. In this case, we’re passing in an Elasticsearch query URL in which we hope to retrieve up to 1,000 bundle documents from the b4 index.

The fetch API is relatively new, and meant to supplant the older XMLHttpRequest API. It is widely available, with the notable exceptions being Safari and Internet Explorer. If you need to support these browsers, you can pull in a popular polyfill implementation from the npm package whatwg-fetch.[82]

As a Promise-producing request API, fetch is quite similar to the request-promise module we used in the last chapter. One notable difference is the way that the response body content is handled. To decode the body content as JSON using the fetch API, you need to call the response object’s json method, which is another asynchronous, Promise-producing function. So here we await the results of that operation.

Once the JSON body has been decoded, we extract the Elasticsearch results (hits.hits) as an array of objects containing the automatically generated id of the document and the name of the bundle. Since getBundles is an async function, if anything goes wrong it will result in a rejection of the returned Promise. We’re explicitly not handling those potential errors here. Instead, we’ll rely on the caller to handle the error by alerting the user.

Still in app/index.ts, let’s add a listBundles function that renders the list of bundles using a Handlebars template. Insert the following after your getBundles function.

 const​ listBundles = bundles => {
  mainElement.innerHTML = templates.listBundles({bundles});
 };

Currently all this function does is render the bundles using an as-yet-unimplemented Handlebars template also called listBundles. Later we’ll add more functionality to this function, but it’s good enough for now.

We need to make one more change to the app/index.ts before we backfill the missing Handlebars template. Down in the showView function, we need to add a handler for the #list-bundles hash route. Insert the following into the switch ladder.

 case​ ​'#list-bundles'​:
 const​ bundles = ​await​ getBundles();
  listBundles(bundles);
 break​;

After you save the file, open your app/templates.ts. Add the following implementation of the listBundles template.

 export​ ​const​ listBundles = Handlebars.compile(​`
  <div class="panel panel-default">
  <div class="panel-heading">Your Bundles</div>
  {{#if bundles.length}}
  <table class="table">
  <tr>
  <th>Bundle Name</th>
  <th>Actions</th>
  </tr>
  {{#each bundles}}
  <tr>
  <td>
  <a href="#view-bundle/{{id}}">{{name}}</a>
  </td>
  <td>
  <button class="btn delete" data-bundle-id="{{id}}">Delete</button>
  </td>
  </tr>
  {{/each}}
  </table>
  {{else}}
  <div class="panel-body">
  <p>None yet!</p>
  </div>
  {{/if}}
  </div>
 `​);

This template uses the array of bundle passed in to render a Bootstrap panel containing a two-column table. The left column of the table contains the name of the bundle and the right column has a Delete button. Neither the bundle-name link nor the Delete button will do anything yet—we have to add that later.

This template uses a couple of Handlebars features. First, the {{#if}}{{else}}{{/if}} block expression does what you might expect. If the condition in the {{#if}} is true, then Handlebars renders the first part; otherwise it renders the {{else}} part. So if you have no bundles, you’ll see a message instead of a table.

The {{#each}} block expression iterates over an array or object. Here we create a new <tr> for each bundle, and fill it with two <td> cells. Inside the {{#each}} expression, the context is the current element, so we can use {{id}} and {{name}} to refer to the current bundle’s ID and name, respectively.

Notice that the bundle name links to #view-bundle/{{id}}. Once we add #view-bundle to the showView switch ladder, these links will take you to a view showing the particular bundle.

Finally, observe the data-bundle-id attribute on the Delete button. This is not required by Bootstrap, but exists so that we know which bundle to delete when the user clicks this button.

Once you save the app/templates.ts file, everything should be in place to see the #list-bundles view from end to end. Start up your webpack dev server, if it’s not running already, then navigate to localhost:60800/#list-bundles. It should look something like this:

images/ux-webpack-dev-server-list-bundles-initial.png

If you haven’t created any bundles yet, you’ll see a message stating None yet! instead of the table. You can create a bundle using the bundle API from Manipulating Documents RESTfully, with curl and jq.

 $ ​​curl​​ ​​-s​​ ​​-X​​ ​​POST​​ ​​localhost:60702/api/bundle?name=light%20reading​​ ​​|​​ ​​jq​​ ​​'.'
 {
  "_index": "b4",
  "_type": "bundle",
  "_id": "AVuFkyXcpWVRyMBC8pgr",
  "_version": 1,
  "result": "created",
  "_shards": {
  "total": 2,
  "successful": 1,
  "failed": 0
  },
  "created": true
 }

So far so good, but what about adding a new bundle? Let’s add a form to do that next.