React JS – Infinite Sub Menu

I’m going to mention right off the bat this tutorial doesn’t end with you having a ready to use menu. BUT.. it shows you a simple concept you can use to create the elements necessary for the old school infinite sub menus.

Infinite Sub Menus Were All the Rage

It’s been quite some time since I’ve seen infinite menus used. Maybe it’s because people are becoming more mobile conscious in their design decisions. The only way I could see infinite sub menus be mobile friendly is if the sub menu completely replaced the previous one.

It’ll probably seem ridiculously obvious once you see the solution but it may come in handy in the future. Here are two React components; List and ListItem, that can be used to accomplish infinite sub menus.

The Components

 

 

Notice the second import statement. My components are in a directory structure as follows:
-components
–List
—index.js
—List.js
–ListItem
—index.js
—ListItem.js

Because I’m a sucker for modular organization even with simple examples.

Now for the ListItem component:

 

 

Basically the solution comes down to the line
{ items && <List items={items} />}.

We’ve created sort of a circular dependency where a List, has ListItems, which can potentially contain another list. If you’re not sure what’s happening, React is looking at the items variable, if it does not equal undefined, it will continue to the other half of the AND (&&) comparison displaying a new list.

This is also true for vanilla JavaScript. If the first half of an AND comparison fails it will not bother with the rest.

Finally, I’ll give you a quick example object passed to the List component.

That’s all there is to it. Let me know if you have any issues with the following code.

API Versioning – Using Date Released

While browsing Hacker News one day, my favorite news site, I came across Stripes versioning blog post. This was not the first time I had come across the idea of using dates to version your APIs, but this time I decided to give it a try.

Some Background

I’ve commonly seen others suggest simply putting version numbers in the URL to segregate major changes. This can work, but how often are major changes made to your API?

In my experience changes are typically updates to some of the returned data, or additional parameters required for precision. These are small changes but not always backward compatible.

If this happens somewhat often, you’ll be supporting many different versions simultaneously. Not only that, you’ll need to duplicate API endpoints that haven’t changed just to be part of these new versions.

Instead of duplicating the entire API to make some small changes, there is a way of just adding changes to the single endpoint. The following is mainly a proof of concept, but with some modifications it could definitely be a solution.

Using Dates to Access API Versions

So finally, I’ll get right to it. By utilizing the flexibility of the HTTP header we can send the date which our client is able to support. This is done by adding an API-Header with a value of let’s say ‘2017-02-10’.

By sending this date in the header, you’re saying that your client is compatible with all revisions prior to and including this date. If your client will always be up to date, simply use today’s date as the value.

Routing to Specific Versions of APIs

So now that you understand the client side, I’ll explain a little how the API routes the request. Express allows you to create multiple routers with different prefixes. The goal is to generate new routes based on timestamps of when the changes were done.

There is middleware in the express server that extracts the API-Version header value and converts it to a timestamp. The middleware then uses this timestamp to reroute the request to the version compatible with the timestamp. The following image will hopefully help explain.

Example of API Date Versioning Routing

You may be thinking, what happens when you release versions that don’t include changes to each endpoint. Well, in the same middleware the routing take place, it actually loops through the endpoints to find a matching url, such as ‘fn1’. The routers are obviously sorted in ascending order to match the latest one with the requested API version. But this way, if a version was not updated in the latest release that was requested, the latest updated version will be used.

It may be easier for some just to look at the code, so I’ve put together a quick project and threw it on GitHub. Check out my date-version-api project on GitHub. Let me know what you think.

API Blueprint – Mock Server

Mock Servers from API Specifications

Last week I mentioned an API specification called API Blueprint. Turns out not only does this allow us to document our API, but also use it.

That’s right, create a functioning mock server from that same API Blueprint used to document your API. I did mention this a bit in my previous post but I thought I’d put together a quick example.

Install Drakov

sudo npm install -g drakov

I just grabbed the Polls API example from the blueprint examples.

I renamed the file to have a .apib extension. Run drakov like the following:

drakov -f PollsAPI.apib

Now you can access a mock server to test your front end code with! See the picture below for example.

api-mock-server-drakov

Drakov Tips

If you’re running the mock server on a different host and from a browser, be sure to enable  OPTIONS. To do this use the –autoOptions argument. This is because when the browser is accessing another host it will send a pre-flight OPTIONS request to see if the intended request is allowed. This bit me when creating my first NodeJS Express applications, I will always remember, vividly.

Use Notepad++ to find and replace tabs in your API Blueprint. Drakov can’t parse blueprints with tabs 🙁 .

 

I’ve FInished Taking the Online Course – Intro to ReactJS

Full disclosure, I wrote my previous blog post about the Intro to ReactJS course a week or so after I started it.

For those who didn’t know, I started an edX course not too long ago. I chose ReactJS because I was already familiar with it but was hoping to find a few gems.

Intro to ReactJS is Basic, But Good!

Unfortunately because it was an introduction course, there wasn’t much to be learned from the content. However, the discussion boards were very good.

At the end of each module you’re asked to complete a lab assignment. This typically consisted of a small application showcasing recently learned aspects of ReactJS.

A graded mark was given out to those who reviewed and critiqued others’ work. This was a great way to see different ways a problem could be tackled. Having fellow programmers review my work was great too. I’m not perfect and the reviews gave me a better idea of how I should be designing ReactJS applications.

I was going to blow away my peers…

Since I was familiar with the library, I may have been a tad over-confident. The first module I designed my components in a way to be reused in multiple future situations.

You may think this is good. That’s how components are meant to be written(not really true). If the components needed to be reused later there would be very little to no refactoring.

YAGNI

The thing is, I knew this would be the last time I would open the source. There was never going to be any more updates to the application. This is where I should have thought of YAGNI (You Aren’t Gonna Need It).

Don’t get me wrong, thinking ahead and preparing for change is important. But what I really should have been considering, is the possibility of needing the functionality I was introducing. Which was zero.

It was a good learning experience and I’m glad a fellow peer had called me on it.

Course Content

The content I thought was well put together. This was my first edX course and it won’t be my last. I’ve already enrolled in another one.

The content includes both written and video media of the same content. This allows you to consume it how you like.

Personally I stuck with the text just because it was slightly faster.

The assessments (tests) were not bad. There were definitely some question/answers I thought could be improved. For the most part it was well done though.

The course was listed as an intermediate course as it should be. If you’re not familiar with JavaScript and HTML I don’t think you’ll do well. This course stays strictly on the topic ReactJS which was really nice. No fluff, just focused content.

I hope this helps anyone considering looking into edX’s courses, maybe I’ll see you on the discussion boards.

Have experience with other courses? Please leave a comment and let me know about it! Also if there are some resources you’d like to share, that would be great too.

Beautiful Code Formatting by Linting with ESLint

What is “Linting”?

Linting is a process of checking source code for suspicious or non-portable constructs. Or at least one definition… [1]

There are many extensions and programs to provide linting functionality for Javascript. Some of these are; JSHint, JSLint, and the one I have been using lately, ESLint.

Some may say that linting isn’t worth the effort. [2] I personally, disagree…

Linting provides a way to enforce code style standards. It can be hard to enforce code style standards on a team sometimes. People disagree with how things should be styled, they may have habits for their own style methods already, some even forget the standards exist.

Another great benefit is keeping your source lean. In ESLint at least, you can configure it to flag variables that are unused. It sounds obvious that you would just remove those variables. But in large files of source, it may be difficult to see the variable is no longer used after an update.

Tech Company Base Rules

Airbnb has a detailed style guide. I like the description, “A mostly reasonable approach to JavaScript“. [3] Probably not a complete solution for all, but it’s a good place to start. In addition to these rules, you can add your own or even override them.

My favorite part about their documentation is where they explain why they have implemented specific rules.

You’ll likely need to install a few modules if you’re using Node.JS but these rules will get you started. [4] I use the ESLint extension published by Dirk Baeumer and have had no complaints. [5]

Finally, enforcing some new JavaScript conventions. Using keywords such as const and let instead of var. This allows the programmer to better describe the variable and define more specific scope. [6]

ESLint warning for using the 'var' keyword.

[1] – What is “Linting”? – https://stackoverflow.com/questions/8503559/what-is-linting

[2] – After 3 Months Of JavaScript Linting, It’s Pretty Much All Pain And No Gain – https://www.bennadel.com/blog/3312-after-3-months-of-javascript-linting-it-s-pretty-much-all-pain-and-no-gain.htm

[3] – Javascript Style Guide – https://github.com/airbnb/javascript

[4] – eslint-config-airbnb-base – https://www.npmjs.com/package/eslint-config-airbnb-base

[5] – ESLint – Visual Studio Marketplace – https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint

[6] – What’s the difference between using “let” and “var” to declare a variable? – https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable

Modular Node.JS Application Programming

Modular Node.JS application programming has a number of benefits. You can isolate smaller portions of the application for packaging and testing. You can create small specialized packages to use with different hardware or peripherals.

One example I’ve used this approach with is microservices. Spinning up an unknown (to the application) amount of express servers.

In the following example I will show you how to create a simple helper module to import all modules within a specified folder. These modules can basically be anything you want as long as they’re contained in their own folders. It will help if all Node.JS modules contain a common function to initialize them.

The image below is the file structure I use for modular Node.JS applications.

Modular Node.JS File Structure

Let’s See the Source for Our Modular Node.JS App!

The following code block is libraryLoader.js:

So let’s quickly pick this apart. The function we will be calling from the main script of the application starts on line 23. I’ve separated the getLibraryDirectories defined on line 13 just to keep things clean.

In our main function, line 25, is simply using Node.JS’ path module to join a file path’s starting point, path to the directory, the operating systems separating character, then the directory itself.

Next, line 26, we use this full path to obtain the names of each directory in the target folder, they are stored in an array.

Line 28 is where the magic happens. For each item in the previously mentioned array of directory names, we import that folder and pass in an object to store it’s structure. This works because if you look at the file structure I provided earlier, modules in the lib folder have an index.js file. When importing, Node.JS will try and reference an index.js file in that directory if a file is not given.

Once the loop is complete, the filled libraries object is returned to whatever had called it.

I’ll now show you a small example of one of these modules in the lib folder to show how the libraries are added to the object.

The following code block is all the source located in index,js, the file I mentioned earlier that is invoked when a directory is imported.

This is extremely simple and only created for example purposes.

The passed in libraries object during the require can be seen on line 7. Node.JS will send a reference to that object which will include a reference to functions located in the app.js. In this case init(). According to Stack Overflow this is called square bracket notation.

A matching function can be found in Module1 and you’ll see why that is important shortly.

The following code block is app.js of the root of the application. This is where the libraryLoader helper will be called.

The usage is actually quite simple.

As you can see on line 9 is where we load all the libraries or modules and store them in a single object. This object contains keys which match the directory names located in the lib folder.

The parameters are:
__dirname – The current directory to start the path
‘.’ – A single dot to tell the function the directory is within the current location
‘lib’ – The directory name we’re looking for is lib, so each module will have to be contained in a folder within lib

Line 10 is just a simple example of how to call functions in all loaded modules. In most cases I will have an init function in all modules to set up loggers and configurations.

I’ll upload the source to Github shortly. Please let me know if you have any questions or comments!

Edit: I’ve finally uploaded the source to GitHub!