Achieve — High Level Logic Project. Creating a new meta design pattern.

Friendly in development. Fast in production. Just build your apps. Let Achieve do the rest.

← Back to documentation index

Backend: JavaScript Servlets

A servlet is a small server program that achieve invokes in response to a request. The term is well known in the Java web server world. JavaScript Servlets (JSS) use the same basic idea, with the servlet written in JavaScript.

A servlet exports a function named servlet. achieve calls the function and provides a session object that links the servlet to the current request.

Servlets may be written as CommonJS or ESM modules.

CommonJS:

exports.servlet = function(session) {
    return "Hello World!";
}

ESM:

export function servlet(session) {
    return "Hello World!";
}

Servlet file names

The .jss marker identifies backend JavaScript that achieve executes but does not serve as source.

CommonJS servlets use .jss or .jss.cjs. ESM servlets use .jss.mjs.

Development and production

achieve has two modes, development (default) and production. In development mode, achieve automatically reloads a servlet when its file changes. There is no need to restart the server after editing the servlet.

Error protection is provided in both modes. achieve catches errors that occur while loading or running a servlet, including rejection of a Promise returned by the servlet, and reports them as servlet errors rather than allowing them to terminate normal request processing.

achieve filters error information to provide a concise, useful diagnostic similar to what you are accustomed to seeing in a browser dev console. Runtime errors normally include the application filename, line and column. For syntax and module-loading errors, achieve reports the most useful source information available and identifies the module being loaded when an exact source location is unavailable.

When achieve can safely respond, processed error information is returned to the client. Development mode also displays concise diagnostics in the console. Persistent server logging, when enabled, records server errors in server log files; it does not enable CLI diagnostics.

To select production mode:

achieve.setMode('production');

A first servlet

An ESM servlet can simply return its result:

export function servlet(session) {
    return "Hello World!";
}

The CommonJS form is:

exports.servlet = function(session) {
    return "Hello World!";
}

achieve provides the session object, supplies the default text/plain response type, protects the managed servlet process from errors, and completes the HTTP response.

Response types

The servlet has access to the complete Node.js response object through session.response. For example, application code can set the response type:

export function servlet(session) {
    session.response.setHeader(
        "Content-Type",
        "application/json; charset=utf-8"
    );
    return JSON.stringify({message:"Hello World!"});
}

GET and POST parameters

For GET requests, achieve parses parameters from the URL query string into session.params. This includes HTML forms using method="get", which construct the query string from the form data.

For POST requests, achieve parses HTML form data and JSON into session.params. For other request data, use session.request directly.

Loading backend modules

Additional back-end modules can be loaded with session.load().

CommonJS modules are loaded synchronously:

let mod = session.load("second.jss");

ESM modules are loaded asynchronously:

let mod = await session.load("second.jss.mjs");

Errors from modules loaded with session.load() receive the same error processing when they propagate through the managed servlet invocation or its returned Promise.

In development mode, modules loaded with session.load() are reloaded when their files change. In production mode, loaded modules are cached for efficient repeated use.

Empty results

If a servlet returns undefined or null while the response status is still the default 200, achieve changes the status to 204 No Content. If application code has selected another status, achieve preserves it. An empty string is valid response content and retains the current status.

A resolved Promise or thenable follows the same completion rules as a directly returned result. For a HEAD request, achieve suppresses the response body while preserving the status selected by these rules or by application code.

Development mode provides a friendly INFO message to help identify an unintended empty result.

Asynchronous Processing

Servlets can use ordinary JavaScript asynchronous processing. So long as the servlet waits for asynchronous processing to complete before returning its result, the normal servlet contract remains unchanged.

export async function servlet(session) {
    const result = await something();
    return result;
}

achieve waits for the returned Promise and completes the response when the result is available.

Application-owned response completion

session.autoEnd is a Boolean property that controls who completes a normal HTTP response. Its default is true, so achieve completes the response from the servlet's returned result.

Set session.autoEnd to false when application code will complete the response itself.

exports.servlet = function(session) {
    session.autoEnd = false;

    session.response.write("Hello ");
    session.response.end("World!");
}

With session.autoEnd = false, achieve does not automatically inspect the returned value or Promise and does not end the response when the servlet returns. The application is responsible for eventually completing the response.

Ordinary use of async and await does not require changing autoEnd. When autoEnd remains true, achieve waits for a returned Promise and completes the response from its resolved value.

autoEnd = false does not suppress an error that achieve catches while it can still safely respond. If headers have not been sent, achieve can return its normal 500 response. Once headers have been sent, achieve reports the error and terminates an incomplete response without attempting to replace it with a new 500. Errors in detached asynchronous work after the servlet has returned are the application's responsibility.