Moving into the second decade of the 21st century, if you have been immersed in the web development community — and more specifically, the JavaScript community — in any capacity, then you likely remember hearing something about Node.js discussed somewhere. Maybe you already know all about it, maybe you know a little, or maybe you’re not yet familiar with it. In what follows, we’re going to take a brief look at some of the components of Node.js, what it is, and why people have gotten excited about it.
Node.js Introduction
What is Node.js? Before we get into that, let’s back up a minute and start by talking about web servers. You know about web servers, right? They’re computers that have software running on them that are able to respond to HTTP requests from clients (which most of the time means browsers like Chrome, Firefox, Safari, and Internet Explorer… either desktop or mobile). They’re written in languages like Perl, C, and C++. Then they have other code like Python or PHP that runs on top of them so that when a client connects to a server, all the code runs, works it’s magic (hopefully in a semi-functional way) and returns a web page of HTML to the browser… or if the endpoint is a web service: XML or a JSON payload. This is a pretty standard interaction that occurs billions of times each day across the world. If you do anything on the Internet, you participate in this process most often without even thinking about what is going on behind the scenes in the client-server interaction.
So where does Node.js come into the picture? Basically Node.js is an implementation where, instead of responding to HTTP requests, processing them, and returning web pages using the aforementioned languages, you use JavaScript instead! Node.js becomes a web server written in JavaScript. And it doesn’t just stop there. You can also run Node.js right in your own desktop environment and use utilities to perform file processes and other tasks just as you could do if you were using an installed application that was written in Java or something else. So Node.js could perhaps be better described as “JavaScript running outside of the browser.” Local applications are definitely a very useful component of Node.js, but we’re going to specifically focus on the aspect of using Node.js as a web server. But I’d definitely recommend looking at a number of different utilities available for installation to see if you can use Node.js in your development processes or just as something that makes your life easier in some way.
Read More »
A lot has been written about WordPress over the years with a lot of the literature describing how flexible it is as a CMS and how you can, with a little know-how and a little work, turn it into whatever you want it to be. Much of this flexibility comes from the ability to register custom post types, where you can create “post types” of any kind within the WordPress CMS. For example, if I were using WordPress to run a company website I could create a “staff” post type, where every entry that I create would contain custom fields for the name of the staff member, their picture, their e-mail, and links to social media profiles. The same thing goes for just about any other post type you could think of: image galleries, sliders, portfolios, etc.
And if there is some functionality that you need that happens to be lacking in the native installation of WordPress, chances are you’ll be able to find something close to what you need in one of the tens of thousands of plugins that exist out on the web. By combining these 2 features (along with a host of others) WordPress is an immensely flexible content management system (CMS) and this is likely one of the reasons it has gained such popularity since it’s inception.
In what follows, we’re going to combine custom post types and WordPress plugin development and create a plugin that registers a custom “portfolio” post type and wraps all of the functionality for both the front and the back end within it. So we’re going to need to to create fields for the name of the portfolio item, fields for featured images, and fields for links to where the project is showcased. After we get through everything, this should give you a good roadmap to create any post type/plugin that you like. In fact, a lot of plugins do little more than register post types inside of some generic WordPress plugin scaffolding code. Because there is so much you can do with custom post types, this is often all you need.
Read More »
One of the most useful implementations of software design patterns is the “PubSub” pattern. “PubSub” is a shorthand term for “Publish-Subscribe” which is a description of what the pattern is actually doing. The reason it is so useful is because it is so universal to how applications work. Basically the idea is that you have pieces of code (publishers) that say “something happened” — a user logged in, there was an error retrieving data, a button was clicked — it could be anything. Then you have pieces of code (subscribers) that run when those events occur. They are called subscribers because they subscribe to the event that gets published. PubSub implementations will also have some sort of capability for previously set subscribers to unsubscribe from an event. If that event happens again after this, the subscriber code will no longer execute.
Sometimes the terms used in PubSub pattern can vary. Sometimes “subscribers” are referred to as “listeners” because they “listen” for certain events occurring. You might recognize this in things like JavaScript’s addEventListener where you can attach callback functions to run when certain DOM events (such as button clicks and mouse hovers) occur. jQuery’s on, off, and trigger methods, are 3 methods that you can use in tandem to easily implemennt PubSub, with “on” being the subscribe functionality, “off” being unsubscribe, and “trigger” being the publish functionality. Backbone.js also uses on, off and trigger in its eventing system. Whatever the terms are and however the code is structured, ultimately these are just variations of the PubSub pattern and will nearly always follow similar ideas and principles.
A lot of examples of PubSub will use something that is pre-built, like jQuery’s methods mentioned above, or a library that implements it, but what we’re going to do in the following paragraphs is look at a raw JavaScript implementation of PubSub where we can do brodcasting (publishing) of our own custom events and attach subscribers to these events. This will give us a good understanding of how PubSub works under the hood. Our implementation will be pretty simple and it will only handle custom events that we name ourselves, but it could be taken and expanded upon to include more standard universal events such as mouse events, load events, error events, and others.
Read More »
There may be times when you have need to sort object literals in JavaScript. Arrays containing primitive values are easy to sort in JavaScript because all you have to do is call the Array.sort() method on an array. But what about object literals? How can we sort those based off of a property value that we specify? For example, suppose we had a grocery store and had an array of inventory objects that we were getting back from some API in the store’s system…
var inventory = [
{ name: "Apples", quantity: 10, price: 2.00 },
{ name: "Bananas", quantity: 6, price: 4.00 },
{ name: "Pears", quantity: 13, price: 3.00 }
];
Note: If your API or service gives you back an object instead of an array of objects you could easily put each object into an array by looping through each sub-object literal in the main object literal (called inventoryObject) like so…
var inventory = [];
for(var i in inventoryObject) {
inventory.push[i];
}
However you get there, you’re going to want to get your set of objects into an array. It doesn’t have to be sorted yet. We’ll get to that below.
So now we have our objects unsorted in an array. How can we use the Array.sort() method on the inventory array to sort the objects based on a property (name, price, quantity) that we specify? Well, fortunately for us it turns out that the Array.sort() method actually can get passed an optional function that can be used to conduct the comparison of properties in our objects. According to the documentation on the Mozilla Developer Network the sort method evaluates the function passed in in the following manner (written in psuedocode)…
function compare(a, b) {
if (a is less than b by some ordering criterion)
return -1;
if (a is greater than b by the ordering criterion)
return 1;
// if we've made it this far a must be equal to b
return 0;
}
Based off of that we can just pass a function into the Array.sort() method and that will give us the result we are looking for. For example, if we wanted to sort by quantity we could just do something like the following…
inventoryArray.sort(function(a,b){
return a.quantity - b.quantity;
});
Now our array of objects is sorted according to quantity. And we could use the same process to sort by name and price if we wanted to.
That’s all there is to it! Until next time… cheers!
Now we’re going to talk a bit about security. I wouldn’t say this is really my area of expertise so take what follows with a bucket of salt, but I’ve recently been looking a bit deeper into REST API security; authenticating users, verifying requests… things of that nature. There are a number of different methods or protocols a developer can use to secure a REST API and all of them have strengths and weaknesses. One of the challenges that you face when handling REST API security is the fact that it is a principle of REST architecture to remain stateless where the server does not maintain any record of whether or not a user is authenticated/authorized (i.e. logged in via sessions). So in order to determine who is sending the request (and whether they are authorized to access a particular resource) on the server side, all of the information needed to handle this has to contained within the request coming from the client.
In other sections, some common methods of handling REST API authorization and authentication were discussed. Basic HTTP Authentication was discussed here and OAuth using Google as a provider was discussed here. In what follows, we’re going to look at another implementation that can also be a pretty good solution to securing REST APIs: HMAC. What is HMAC? No, it’s not a new burger that McDonalds is rolling out. HMAC stands for “hash-based message authentication code.” Like the name suggests, this means we’re going to be sending a hash (a jumble of letters and numbers) back and forth between the client and server and the system is going to be able to figure out (hopefully) if the request is coming from someone we trust or if it is coming from one of less than noble character.
There are some great articles that have been written on HMAC. Notably…
As is discussed in the articles above, the general idea behind HMAC is this… A client and a server know a secret key. This secret key is never sent over the wire. It is only used in combination with other pieces of data that *are* sent over the wire. That way, when we use our secret key and any other data transferred — say, a public key identifying the user (in the form of a header or a cookie), the message body, the current timestamp or anything else we want to use — and we run that data through an encryption algorithm such as SHA-1… we can create the same hash on both the client and the server! That’s how we know the request is valid. Only a client with the secret key would be able to reproduce the same hash it ends up sending to the server.
Read More »