An Introduction To JavaScript ES6 Classes

Share

ECMAScript 2015, formerly known as ECMAScript 6 (ES6) makes classes a first class citizen by introducing a few new keywords. At this time, however there are no new features when compared to the the good old JavaScript prototypes. The new keywords are simply a syntax sugar on top of the well established prototype system. This does make the code more readable and lays the path forward for new Object Oriented (OO) features in the upcoming spec releases.

The reason for this is to ensure backwards compatibility with existing code written using the ES6 and ES5 spec. In other words, older code should be able to be run side by side without any workarounds or hacks.

Defining Classes

Let’s refresh our memory and look at a typical way of wiring OO code in ES5. While Object.defineProperty is not very commonly used, I want to make a point of creating a read only property.

Pretty basic stuff, we’ve defined a Vehicle class with two read only properties and a custom toString method. Lets do the same thing in ES6.

The two examples are practically equal, however there’s one difference. To be able to take advantage of the new get syntax (which is actually part of the ES5 spec), we have to keep make and year around as properties using basic assignment. This leaves them vulnerable to being improperly changed. This feels like a pretty big omission in the spec – in order hang on to a value passed into a constructor privately, you still have to use defineProperty syntax.

Class Declaration

There are two ways to declare a class in ES6. The first one is called class declaration and that is what we used in the example above, eg:

One important thing to note here is that unlike function declarations, class declarations can’t be hoisted. For example, this code works fine:

However, the following is going to throw an exception:

Class Expressions

Another way to define a class is by using a class expression and it works exactly the same way as a function expression. A class expression can be named or unnamed.

Static Methods

The static keyword is another syntax sugar in ES6 that makes static function declaration a first class citizen (see what I did here?). In ES5 it looks like a basic property on a constructor function.

And the new shiny static syntax looks like this:

Under the covers, JavaScript is still just adding a property to the Vehicle constructor, it just ensures that the method is in fact static. Note that you can also add static value properties.

Class Extending

Prototypical inheritance is not unlike magic when used properly. This hasn’t been forgotten in ES6 with the introduction of the all new extends keyword. In the old world of ES5 we did something like this:

With the new extends keyword same example looks a lot more digestible:

The super keyword also works with static methods:

super

The last example also showed the usage of the super keyword. This is useful when you want to call functions of the object’s parent.

To call a parent constructor you simply use the super keyword as a function, eg super(make, year). For all other functions, use super as an object, eg super.toString(). Here’s what the updated example looks like:

Computed Method Names

When declaring properties or functions in a class, you can use expressions instead of statically defined names. This syntax feature will be very popular for ORM type libraries. Here is an example:

Bottom Line

At this time, there isn’t any advantage to using classes over prototypes other than better syntax. However, it’s a good to start developing a better practice and getting used to the new syntax. The tooling around JavaScript gets better every day and with proper class syntax you will be helping the tools help you.

ES6 Today

How can you take advantage of ES6 features today? Using transpilers in the last couple of years has become the norm. People and large companies no longer shy away. Babel is an ES6 to ES5 transpiler that supports all of the ES6 features.

If you are using something like Browserify in your JavaScript build pipeline, adding Babel transpilation takes only a couple of minutes. There is, of course, support for pretty much every common Node.js build system like Gulp, Grunt and many others.

What About The Browsers?

The majority of browsers are catching up on implementing new features but not one has full support. Does that mean you have to wait? It depends. It’s a good idea to begin using the language features that will be universally available in 1-2 years so that you are comfortable with them when the time comes. On the other hand, if you feel the need for 100% control over the source code, you should stick with ES5 for now.

 

Node.js Smart Profiling Using StrongLoop Arc

The StrongLoop Arc Profiler (released previously) enables you to gather and view CPU profiling and heap memory snapshot data for Node applications. With this release, the Profiler just became smarter! This blog post is intentionally written tutorial style and will show you how to take advantage of the new Smart Profiling support.

What is Smart Profiling?

Profiling is an important part of optimizing and troubleshooting any Node.js application. However, profiling an application has a couple of issues. It often causes significant overhead, making it difficult to use outside of testing environments. Also, many performance issues are intermittent, and require running the profiler for an extended period of time. This can make it difficult to isolate profiling information for the actual issue from the general background noise of running the profiler for so long.

Smart Profiling attempts to improve these two issues. It works by allowing you to specify a minimum threshold that the event loop must stall, before the profiler will capture any performance data for that event. This helps to reduce the amount of noise captured in the profile, and also dramatically reduces the overhead of running the profiler.

Let’s look at an example scenario where using Smart Profiling could be a useful tool.

Example Scenario

Read more

Part 1: Ionic & LoopBack Frameworks – Building a REST API

I have a confession: I hate native mobile development. Most of the reason why I started working with NodeJS was my struggles with managing mobile app development for a small startup in 2012. Back then, native mobile development struggled with painfully slow feedback – to see the results of your work in action, you need to start a server, re-compile, wait for the app to load, and click around in a simulator.

Code sharing was also a lost cause. In my experience, it’s hard to get code right once. When your server is in Ruby, your iOS app is in Objective-C, your Android app is in Java, and your web client is in JavaScript, you end up maintaining 4 separate implementations of the same code in 4 different languages. Even worse, each implementation is bound to have its own bugs, quirks, and performance issues.

Now, with StrongLoop LoopBack and the Ionic framework, you can quickly build out a server and a corresponding mobile app using only JavaScript. LoopBack enables you to quickly build up a REST API from your command line. Ionic enables you to build “hybrid” mobile apps, that is, mobile apps that work by launching a browser and executing JavaScript.

In this series of articles, you’ll see how you can build a server using LoopBack. Then you’ll use LoopBack’s AngularJS SDK to create AngularJS components which you will use to create an Ionic framework hybrid mobile app. There will be 4 articles in this series:

  1. Building a LoopBack REST API
  2. Building AngularJS Directives with the LoopBack AngularJS SDK
  3. Using AngularJS Directives in Ionic Framework Mobile Apps
  4. Testing Your Mobile App in Travis

You’ll be building a simple stopwatch application. Users of the app will be able to log in with Facebook, track times, and save their times to the server. Let’s get started!

Getting Started with LoopBack

StrongLoop LoopBack is a tool for rapidly generating NodeJS REST API’s. LoopBack also has a powerful AngularJS SDK that enables you to generate AngularJS clients for your REST API’s. Since the Ionic framework is based on AngularJS, the LoopBack AngularJS SDK makes building a mobile app even easier. You’ll learn more about the AngularJS SDK in the next article. In this article, you’ll use LoopBack to create a REST API with Facebook login. You can find the complete stopwatch server on GitHub

The first step is to install the strongloop npm module using npm install strongloop -g. The strongloop module gives you the slc executable. Run slc loopback to start a new application – you should see the below output in your terminal. Call your application stopwatch-server-example.

LoopBack will create a directory called stopwatch-server-example. The stopwatch-server-example directory’s code will look like this once LoopBack is done.

Read more

Announcing StrongLoop API Gateway Powered by Node.js

This morning, we announced the private beta of StrongLoop Gateway. We’ve never seen so much interest in a product that we haven’t even released or promoted. Of course, for any business, this is a “good problem” to have. It’s been rewarding to validate that the StrongLoop Gateway will meet the needs of so many people. It’s also rewarding to see that we have an advantage over competitors because the StrongLoop Gateway is tailored to the needs of API development and not – management.

Let’s start from the beginning and explain the overloaded term “gateway.”

Overview

An API gateway externalizes, secures, and manages APIs. It is an intermediary between API consumers (clients) and backend API providers (API servers).

Screen Shot 2015-07-29 at 2.13.14 PM

In this intermediary position, the API gateway performs several functions depending on the needs of the enterprise, as summarized in the table below.

Function API Gateway Role
Security Acts as both provider and delegator to authentication, authorization, and auditing (AAA) sources within the enterprise as the first intercept to establish identity.
Mediation and Transformation Mediates between protocols and transforms portions of the API payload (both header and body) for clients that have fixed and/or specific requirements for consumption.
Infrastructure QoS Performs infrastructure-level API consumption functions required by client such as pagination, throttling, caching, delivery guarantee, firewall,  and so on.
Monitoring and Reporting Instruments APIs to fulfill service-level agreements (SLAs) through the monitoring of APIs and also injects metadata to report on API usage, health, and other metrics.
Aggregation Composes coarse-grained APIs (mashups) from fine-grained micro-APIs to fulfill specific business case operations through dynamic invocation and construction.
Virtualization A layer of abstraction that virtualizes API endpoints and acts  as a reverse proxy to API server host instances for high availability, security and scale.

Read more

Getting Started with the StrongLoop Node.js API Gateway – Step by Step

The goal of this tutorial is to understand the design principles behind StrongLoop Node.js API Gateway and how you can configure it step by step to test your use cases.

The following diagram illustrates the API Gateway architecture.

APIGateway

Request/response pipeline

The gateway creates a “pipeline” of layers for API requests and responses. The layers of the pipeline correspond to different stages of processing API requests, and orchestrating and constructing API responses.

loopback-pipeline

The API Gateway “pipeline” has four layers:

  • Transport layer: Listen for incoming messages and un-marshal them into request objects. For example, LoopBack uses Express to accept HTTP requests and produce HTTP responses.
  • Remoting layer: Resolve the request objects to Node.js objects as receivers and methods to be invoked.
  • Model layer: Delegate data access requests to connector implementations
  • Connector layer: Dispatch CRUD and other model methods to database driver calls to the backend system.

Typical flow of an API request

  1. Client application requests an access token from the OAuth 2.0 authorization server.
  2. Client application sends an API request with the access token to the OAuth 2.0 resource server.
  3. Resource server validates the access token (including expiration, scope, client id and resource owner) to either allow or deny the access. If deny, an error response is sent to the client application and the flow terminates.
  4. Metrics middleware captures the API usage and updates the metrics.
  5. Rate limiting middleware introspects the API request and check the rate limits based on various keys. If it exceeds one of the limits, , an error response is sent to the client application and the flow terminates.
  6. Proxy middleware looks up the routing configuration to decide if the request should be handled locally or forwarded to a remote API server.
  7. API server processes the request and produces a response.
  8. Response is received by the proxy middleware, and then sent back to the original client application.

Here are the steps to get the Gateway up and running

First of all we assume you have StrongLoop installed. If not, do the following:

The StrongLoop Gateway is currently under private beta. Please contact sales@strongloop.com to have a license provisioned. After receiving confirmation that a license has been provisioned, run slc arc --licenses to retrieve the new license key. If you are provisioning the Gateway to a remote Linux server, please make sure you have StrongLoop Process Manager installed on that box. Please check: http://strong-pm.io. If you are testing on a local box, process manager is already installed when you did npm install -g strongloop.

Step 1: Setup a backend API/Resource server and a RESTful client

API Gateway is a configurable middleware module. We have built a sample application to configure and test the gateway. Clone the demonstration project as follows:

In this project, we have an API backend called notes-app-plain. This application is a standard loopback application. To set it up from scratch, please follow https://github.com/strongloop/strong-gateway-demo/tree/master/notes-app-plain. If you are an experienced Loopback user, you can skip this tutorial and just setup any loopback app with it’s API endpoints exposed over REST.

The below diagram depicts what we are setting up logically, the Resource Server (in OAuth) terms, being our API Server

You can simply run it by

Once the notes are retrieved, the web server displays it to the user:

Now that you are familiar with the Loopback backend, lets move to our main Gateway repository, called the “notes-app-gateway”

When you cloned the “strong-gateway-demo”, this repository was already included in that project, so you can just

We have some configuration scripts setup to make life easier. To setup the backend API app within the context of our gateway, learn how to build from scratch using https://github.com/strongloop/strong-gateway-demo/tree/master/notes-app-gateway#step-1—copy-files-from-notes-app-plain-to-notes-app-gateway or just run :

This script creates the Resource/API Server, resets StrongLoop Process Manager, builds and deploys the app and boots it up.

If you are really interested in what the setup script looks like, here is a sample

Step 2: Proxy requests through the auth server

In this step we will setup a proxy or an Authorization server, through which the requests & responses from the client to the Gateway will be handled.

To learn how to configure this from scratch, please check https://github.com/strongloop/strong-gateway-demo/tree/master/notes-app-gateway#step-2—proxy-requests-through-the-auth-server or simply run the following:

Browse to localhost:3001.You should be redirected to localhost:3101 and you should see:

After configuring the proxy (the setup script already does it for you), Browse to localhost:2001 and you should see:

While the results look identical to notes-app-plain, the client is now making requests to the auth server, which is acting as a proxy to the resource server. The client is now fully decoupled from the resource server.

Step 3: Enable security on the auth server

Now we will enable security (Authentication and ACL primarily) on the Auth Server. To learn how to configure this from scratch, please check https://github.com/strongloop/strong-gateway-demo/tree/master/notes-app-gateway#step-3—enable-security-on-the-auth-server or simply run the following:

After the config is setup (the install script does it for you) browse to localhost:2001. You should see:

The server is now denying requests from unauthorized users.

Step 4: Enable the OAuth2.0 Authorization Code flow on the client

The Gateway supports multiple Authorization flows. Namely:

Since the auth server is now blocking the client from retrieving notes, we need a way to authenticate it. To do this, We will use the OAuth 2.0 Authorization Code Grant flow to authenticate client requests. During this process we will also setup SSL certificates, routing and redirection.

To learn how to configure this from scratch, please check https://github.com/strongloop/strong-gateway-demo/tree/master/notes-app-gateway#step-4—enable-the-oauth-20-authorization-code-flow-on-the-client or simply run the following:

After the configuration (the script does it all for you) Browse to localhost:2001. You should see:

Click the “here” link. You should see:

Notice in the URL bar, you’ve been redirected to https://localhost:3202. Log in with the bob:secret credentials by clicking “Submit”. You should see:

Once you are authenticated as bob, the auth server asks if you want to allow demo-app access to your account.

Note : bob and demo-app are preregistered sample data values included with the auth server. StrongLoop API Gateway includes this data out of the box for demo purposes.

Click “Allow” to approve the permission request. You should see:

Step 5: Policy Management and enforcement

In addition to the basic gateway features, the StrongLoop API gateway also provides set of features known as policies.

In this step, we are primarily setting up rate-limiting policies. These policies can be based on user, application, user&application, IP Address, etc. Volumes are controlled by time buckets which are also a controlling parameter in the policies.

To learn how to configure this from scratch, please check https://github.com/strongloop/strong-gateway-demo/tree/master/notes-app-gateway#step-5—strongloop-api-gateway-policies or simply run the following:

To try it out :

Run the rate-limiting script:

You should see:

Notice the headers show the maximum number of requests (1000), the number of remaining requests (999, 998, …) and the time left (in ms) until that count resets (60000, 59982, …). See the official docs for more info.

Step 6: Check API Analytics

The StrongLoop API Gateway can gather analytics related to API usage. We will be using StrongLoop Arc (Arc) to view the collected data.

Start the auth server using PM:

Start Arc:

At this point, strong-arc will automatically open your browser.

Go to the “API Analytics” module

Arc_analytics

 

Enter the following info on the Process Manager tab:

pm_setup

Hostname: localhost
Port: 8701

Click the “Load” button on the left side of the API Analytics screen to load the graphs.

api_aggregation

Note: The graph does not update automatically, you will need to click the “Load” button to refresh the data. This will be addressed in a future update.

To create analytics to gather, we’ll reuse the rate-limiting script from the previous section:

This script will make a large number of requests and cause changes to the analytics graph data.

Go back to the Arc window and view the analytics again. Click “Load” again to refresh the data. You should many changes that correspond with the activity caused by the rate limiting script.

You can also view analytics broken down by time – hourly

hourly_breakdown

 

Once you drill down into the hourly breakup, you can see distribution of the API by response times and number of requests.

Analytics_graph2  Analytics_graph1

Step 7 (optional) – Use MongoDB for the auth server’s data source

We will not run this step. In case you are interested, please check the configuration as below. These step allow us to persist the role and api mapping metadata into an un-structured database like MongoDB or an objectDB which ships out of box with Loopback.

https://github.com/strongloop/strong-gateway-demo/tree/master/notes-app-gateway#step-6—use-mongodb-for-the-auth-servers-data-source

Step 8 (optional) – Use MySQL for the auth server’s data source

We will not run this step. In case you are interested, please check the configuration as below. These step allow us to persist the role and api mapping metadata into a structured database like MySQL, SQLServer or Oracle. Please note you will have to use the appropriate loopback connector for particular databases.

https://github.com/strongloop/strong-gateway-demo/tree/master/notes-app-gateway#step-7—use-mysql-for-the-auth-servers-data-source

Get Started Evaluating API Gateway

Send us an email to get your free evaluation started!

What’s next?