JavaScript Guide

Contents

  1. Prerequisites
  2. Download and import
  3. Attributes of a response
  4. Using pre-defined responses
  5. Encoding responses to JSON format
  6. More pre-defined responses
  7. Including data in responses
  8. Using custom classes in responses
  9. Adding lists
  10. Creating custom responses
  11. Decoding JSON text into Response objects

Prerequisites
  • JavaScript ECMA5+
  • A modern browser or JavaScript compiler
Download and import

To begin, download the Responz library for JavaScript.

Extract the folder 'Responz' from the downloaded ZIP file inside your JavaScript file directory. The folder contains two types of files:

  • Responz.js - This is a JavaScript file that can be imported in web pages (HTML). This is used mostly on the client-side.
  • Responz.mjs - This is a JavaScript module meant for use as an import within other JS scripts. This can be used on the server-side.

You can import the Responz library as a JavaScript file within HTML using:

<script src="js/Responz.js"></script>

However, the Responz library is not of much use on the client-side. Alternatively, you can import the Response library as a module in your own JavaScript code (which can be hosted on the server-side) using:

import {
    RESPONSE_OK,
    RESPONSE_ERROR,
    Response,
    ErrorResponse,
    SuccessResponse,
    MissingParameterResponse,
    InvalidParameterResponse,
    SecurityResponse,
    UnknownFailureResponse
} from "../src/Responz/Responz.mjs";

Note: You may remove or add new imports as needed but each class and variable should be imported separately. Also be careful to import the correct file of the two.


Components of a response

All responses contain four internal components, inherited from a base class called Response. These are:

  • status - is either "ok" or "error" and is used to indicate the result of the request.
  • title - contains a title that very briefly describes the result of the request.
  • message - contains a message to the client describing the result in more detail.
  • timestamp - timestamp that indicates the time the request was processed.
  • data - (Optional) contains data returned related to the client's request. The data object will be omitted from any serialized JSON if it is not defined.

Using pre-defined responses

The library offers two existing responses that extend the Response base class by implicitly specifying the status. These are the SuccessResponse, which indicates that the user's request has been executed successfully (status = ok) and ErrorResponse, which indicates that an error occured when trying the execute the request (status = error). The following example shows how to instantiate a simple response, a Success response and an Error response.

//A generic response:
const response = new Response(RESPONSE_OK, "My title", "My message", null);

//A successful response:
const successResponse = new SuccessResponse("Success", "This is a successful response.", null);

//An error response:
const errorResponse = new ErrorResponse("Error", "This is an error response.", null);

Encoding responses to JSON format

You can encode a Response object into a JSON string using the toJSON() method:

const json = response.toJSON();

This should produce the following JSON text:

{"status":"OK","title":"My title","message":"My message","datetime":"2019-07-28 00:20:29"}
More pre-defined responses

There are some additional Response classes you can use. These are based on common responses that can be found in a large variety of projects.

  • InvalidParameterResponse - Commonly used when an invalid parameter is submitted in the request. For example, an integer was expected, but a string was found.
  • MissingParameterResponse - Commonly used when a parameter was expected but not provided.
  • SecurityResponse - Commonly used when a user makes a request that requires authentication/authorization and is denied access.
  • UnknownFailureResponse - Commonly used when something has gone wrong on the server side. This is usually used in conjunction with exceptions or other fault-dealing mechanisms.

For more information about pre-defined responses, check out the Documentation.

const invalidParameterResponse = new InvalidParameterResponse("myParam", "an integer, found string.", null);

const missingResponse = new MissingParameterResponse("myParam", null);

const securityResponse = new SecurityResponse(null);

const unknownFailureResponse = new UnknownFailureResponse("A failure has occurred, please contact the administrator.", null);

Including data in responses

Each response has a data member which allows insertion of an arbitrary number of other objects. This member is initially null and will therefore not be printed in any encoded JSON text.

Creating data objects:

You can add raw data (Strings, Characters, Numbers and Booleans) by creating a new object and passing your data as parameters:

//Create a data object that contains the data:
let data = {
    myInt: 3,
    myString: "hello",
    myBoolean: true
};

You can also nest an object inside another object:

//Create an inner object:
let innerObject = {
    myInnerInt: 4,
    myInnerBoolean: false
};

//Set the inner object as a property of the outer object (in this case 'data'):
data.myInnerObject = innerObject;

To set the data of the response in the constructor use:

//Create a new response and pass the data object in the constructor:
let myResponse = new Response(RESPONSE_OK, "My response title", "My response message.", data);

Alternatively, you can set the data of a response after initialization by assigning your data object as the data property of your response:

let newData = {
    newInteger: 94,
    newString: "abcdef"
};

//Assign the new data as the data of the response:
myResponse.data = newData;
Using custom classes in responses

You can also define your own classes:

//Create the new class:
class Person {
    constructor(firstname, lastname, age) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.age = age;
    }
}

Note: If your class is on a different file, you need to import it as well.

To include an instance of your class in a response, create an object of the class and assign it to a data object as a property:

//Create an instance of the class:
let myPerson = new Person("John", "Doe", 50);

//Define a new data object and assign the custom object as a property of the data:
let customObjectData = {
    person: myPerson
};

//Assign the data object as the data property of the response:
myResponse.data = customObjectData;

Adding lists

You can also add lists by defining an array, putting items inside it and assigning the array as a property of a data object:

//Create a new array:
let peopleArray = [];

//Add some people:
for (let i = 0; i < 5; i++) {
    let newPerson = new Person("Firstname " + i, "Lastname " + i, 30 + i);
    peopleArray.push(newPerson);
}

//Create a data object and assign the array as a property of the data object:
let peopleObjectData = {
    people: peopleArray
};

//Assign the data object as the data property of the response:
myResponse.data = peopleObjectData;

Creating custom responses

You can create your own custom response by extending the Response, SuccessResponse or ErrorResponse classes:

//Create a new response type by extending the Response, ErrorResponse or SuccessResponse classes:
class MyCustomResponse extends SuccessResponse {
    constructor(message) {
        super("Custom title", message, null);
    }
}

//Instantiate the new custom response:
let customResponse = new MyCustomResponse("Hello World!");

Decoding JSON text

You can decode JSON formatted text using JavaScript's native JSON.parse() method:

//Let's instantiate a response just for an example:
let responseObject = new Response(RESPONSE_OK, "This is a title", "This is a message.", {myNumber: 54, myBoolean: true});

//Serialize/Encode to JSON text:
let responseJSON = responseObject.toJSON();

//Parse using JavaScripts native JSON.parse() method:
let decodedResponse = JSON.parse(responseJSON);

You can then get the values of statuses, titles, messages, date-time and data properties using:

console.log("Status => " + decodedResponse.status);
console.log("Title => " + decodedResponse.title);
console.log("Message => " + decodedResponse.message);
console.log("Date/Time => " + decodedResponse.datetime);
console.log("Data[myNumber] => " + decodedResponse.data.myNumber);
console.log("Data[myBoolean] => " + decodedResponse.data.myBoolean);

For more information on the Responz library, please visit the documentation.