Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JEC: Working With jslets in Node.js

DZone's Guide to

JEC: Working With jslets in Node.js

Jslet containers provide a portable solution to develop web applications faster, built in TypeScript and deployed over Node.js.

· Web Dev Zone ·
Free Resource

Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required

This article shows how to create web applications, a la JAVA, over Node.js by using the "JavaScript Enterprise Container" (JEC) specification and its default implementation: GlassCat application server.

Prerequisites

In order to follow this tutorial, you need to install a GlassCat server instance and deploy a basic JEC project.

JEC presentation and GlassCat installation are detailed in the article JavaScript Enterprise Container: From Java to Node.js. All videos are available from the JEC Video Channel.

Servlets and jslets

The Java Enterprise Edition specifies servlets as "Java programming language class used to extend the capabilities of servers that host applications accessed by means of a request-response programming model" [What Is a Servlet?, The Java EE 6 Tutorial]. The JEC specification introduces jslets to provide JavaScript developers the same kind of functionalities over the Node.js environment.

Like servlets, jslets are classes that are executed by the server to respond to an HTTP request. This mechanism offers several advantages:

  • The business layer is strictly uncoupled from technical structures, such as server config, monitoring tools, etc.
  • Common processes are centralized and hidden (e.g. HTTP transaction caching and serving, error handling...).
  • Developer accesses a standard API to build complex applications.
  • The developer gets the benefits of OOP encapsulation and modularity concepts to design better applications (testability, separation of concerns...).
  • Applications are portable.

Moreover, JEC takes metadata-based declarations and auto-wiring from the Spring principles to make app configuration as easy as possible. Consequently, web applications are much faster to develop than a standard Node.js app.

Anatomy of a jslet

As mentioned above, jslets are JavaScript classes. But, a particular point of the JEC specification is that all of its APIs have been designed on top of the TypeScript programming language. Thanks to TypeScript, the jslet specification has the benefits of static typing and ES7 metadata declarations (decorators).

So, jslet classes must implement the Jslet interface and use the @WebJslet decorator to ensure JEC specification compatibility and self-discoverability by JEC servers. The JEC "exchange" module provides an abstract class, HttpJslet, which should be used to safely create all jslets of an application.

The following code shows the minimal implementation provided by the developer to create a jslet:

import {HttpJslet, WebJslet} from "jec-exchange";
@WebJslet({
  name: "HelloWorld",
  urlPatterns: ["/hello"]
})
export class HelloWorld extends HttpJslet { }

Notice that JEC specifies that only one component declaration (jslets, resources, config classes...) is allowed for each TypeScript file. It means that it is not possible to create more than one jslet into a class declaration file.

The jslet API

The @WebJslet Decorator

The @WebJslet decorator allows devs to declare a TypeScript class as a JEC jslet component. It accepts configuration objects of the type of WebJsletParams as unique parameter. The WebJsletParams interface defines three properties:

  • names specifies the name of the jslet; you typically use the name of the jslet class to set this property. This parameter is required.
  • urlPatterns represents an array of URL paths that are mapped to this jslet. This parameter is required.
  • template is an optional parameter that provides the template to use to render response data. The default GlassCat template engine is EJS. JEC specifies that template engines can be set by using template connectors, but GlassCat does not support this functionality yet.

The Jslet Interface

The Jslet interface provides all methods that allows a developer to invoke different actions depending on the jslet lifecycle. It also provides access to the jslet context, which contains information about security and session contexts. The jslet context is itself an extension of the container context.

The HttpJslet Class

The HttpJslet abstract class interface implements the Jslet interface. It provides all methods to map HTTP verb-based transactions with TypeScript programming routines.

The construct of these methods is based on an HTTP verb, combined with the prefix “do.” Thus, the HTTP GET method will invoke the doGet() method, and so on...

Moreover, all of these transactional methods have the same signature:

doGet(req: HttpRequest, res: HttpResponse, exit: (req: HttpRequest, res: HttpResponse, data: any) => void): void;

The req parameter represents the current HTTP request and res the associated HTTP response. The exit() method is a declarative mechanism provided by JEC to let developers return data asynchronously.

Usage

To create your own jslet, you just have to combine all the preceding elements into a single class, as shown below:

import {WebJslet, HttpJslet, HttpRequest, HttpResponse} from "jec-exchange";
@WebJslet({
  name: "HelloWorld",
  urlPatterns: ["/hello"]
})
export class HelloWorld extends HttpJslet {
  public doGet(req: HttpRequest, res: HttpResponse, exit: Function): void {
    exit(req, res, "Hello World!");
  }
}

Now, by calling the /hello route on the app domain, the HTTP transaction will return the "Hello World!" string. The magic here is that you do not add additional configurations to tell the server that you have created a new jslet!

The auto-wiring process is carried by the @WebJslet metadata which hides complex configurations and lets developers focus on business implementations.

Serving Static Resources

In the series of articles Creating RESTful APIs With JEC, we have demonstrated how the JavaScript API for RESTful Services (JARS) can beneficially replace jslets to create a constellation of modern web services.

But, jslets are still pertinent in many use cases. In the following code, we show how to easily serve static resources, such as images, by using the jslet API:

import {HttpJslet, WebJslet, HttpRequest, HttpResponse, HttpHeader} from "jec-exchange";
import * as path from "path";
@WebJslet({
  name: "StaticResourceSample",
  urlPatterns: ["/images/*"]
})
export class StaticResourceSample extends HttpJslet {
  private readonly CACHE_CONTROL_RULE:string = "public, max-age=31536000";
  public doGet(req:HttpRequest, res:HttpResponse, exit:Function):void {
    const filePath:string = `${process.cwd()}/my-img-path/${path.basename(req.getPath())}`;
    res.setHeader(HttpHeader.CACHE_CONTROL, this.CACHE_CONTROL_RULE);
    exit(req, res.sendFile(filePath));
  }
}

The sample code above is picked up from the JEC sample application repository. The original implementation uses Dependency Injection for factoring cache control code.

JEC specifies that static resources can be served by using the @Static metadata:

import {HttpJslet, WebJslet, HttpRequest, HttpResponse, Static} from "jec-exchange";
import * as path from "path";
@WebJslet({
  name: "StaticResourceSample",
  urlPatterns: ["/images/*"]
})
export class StaticResourceSample extends HttpJslet {
  @Static()
  public doGet(req:HttpRequest, res:HttpResponse, exit:Function):void {
    const filePath:string = `${process.cwd()}/my-img-path/${path.basename(req.getPath())}`;
    exit(req, res.sendFile(filePath));
  }
}

Unfortunately, GlassCat server does not support the @Static metadata yet.

Where to Go From Here

The JEC wiki is a great place to get started.

The JEC Youtube channel provides videos on how to install a GlassCat server and how to create web apps from GlassCat Project Models (GPMs).

To get a deeper understanding of how JEC and GlassCat work, check out the article series Creating RESTful APIs With JEC.

Summary

In this article, we have discussed the jslet API, specified by JavaScript Enterprise Container (JEC), to help developers easily create standardized web services.

Jslet containers provide a portable solution to develop web applications faster, built in TypeScript and deployed over Node.js.

#1 for location developers in quality, price and choice, switch to HERE.

Topics:
servlet ,typescript ,web app architecture ,tutorial ,node.js ,web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}