RestAPI

A REST-backed datasource for reading and writing application state over HTTP.

Import
the javascript logo
import { RestAPI } from "@schukai/monster/source/data/datasource/server/restapi.mjs";
Source
the git logo
Package
the npm logo
Since
1.22.0

RestAPI binds the datasource contract to HTTP endpoints. It is the default choice when application state should be loaded from and written back to a REST-style backend.

The value is not only the fetch call itself. The class combines endpoint configuration with mapping, accepted status handling, custom response callbacks, validation report extraction and partial-write hooks, all behind the same datasource surface.

That makes it suitable for forms, dashboards and CRUD flows where backend payloads need more structure than a bare fetch() call would provide.

Configure Read And Write Endpoints

import { RestAPI } from "@schukai/monster/source/data/datasource/server/restapi.mjs";

const output = document.getElementById("restapi-output");

document.getElementById("restapi-run").addEventListener("click", () => {
    const datasource = new RestAPI({
        read: {
            url: "/api/orders/7",
            acceptedStatus: [200],
        },
        write: {
            url: "/api/orders/7",
            init: {
                method: "PATCH",
            },
            acceptedStatus: [200, 204],
        },
    });

    output.textContent = JSON.stringify(
        {
            readUrl: datasource.getOption("read.url"),
            writeUrl: datasource.getOption("write.url"),
            writeMethod: datasource.getOption("write.init.method"),
        },
        null,
        2,
    );
});
Open in playground

Replace The Default Read Callback With A Custom Assignment Flow

import { RestAPI } from "@schukai/monster/source/data/datasource/server/restapi.mjs";

const datasource = new RestAPI({
    read: {
        url: "/api/releases/7",
        responseCallback(payload) {
            return {
                acceptedStatus: [200],
                assignedPayload: payload,
            };
        },
    },
});

const output = document.getElementById("restapi-callback-output");

document.getElementById("restapi-callback-run").addEventListener("click", () => {
    output.textContent = JSON.stringify(
        {
            readUrl: datasource.getOption("read.url"),
            customCallbackDefined: typeof datasource.getOption("read.responseCallback") === "function",
        },
        null,
        2,
    );
});
Open in playground

Patch Only Changed Fields Before Sending A Write Request

import { RestAPI } from "@schukai/monster/source/data/datasource/server/restapi.mjs";

const datasource = new RestAPI({
    write: {
        url: "/api/profile/12",
        init: {
            method: "PATCH",
        },
        partial: {
            callback(source, changes) {
                return {
                    patch: changes.map((entry) => ({
                        path: entry.path,
                        value: entry.actual,
                    })),
                };
            },
        },
    },
});

datasource.transformServerPayload({
    displayName: "Vera",
    timezone: "Europe/Berlin",
});

datasource.set({
    displayName: "Vera Schukai",
    timezone: "Europe/Berlin",
});

const output = document.getElementById("restapi-partial-output");

document.getElementById("restapi-partial-run").addEventListener("click", () => {
    output.textContent = JSON.stringify(
        {
            method: datasource.getOption("write.init.method"),
            body: datasource.prepareServerPayload(datasource.get()),
        },
        null,
        2,
    );
});
Open in playground

Read Validation Reports From A Nested Response Path

import { RestAPI } from "@schukai/monster/source/data/datasource/server/restapi.mjs";

const datasource = new RestAPI({
    write: {
        url: "/api/orders/7",
        report: {
            path: "meta.validation",
        },
    },
});

const output = document.getElementById("restapi-report-output");

document.getElementById("restapi-report-run").addEventListener("click", () => {
    output.textContent = JSON.stringify(
        {
            reportPath: datasource.getOption("write.report.path"),
            expectedServerShape: {
                meta: {
                    validation: {
                        field: "quantity",
                        message: "must be greater than zero",
                    },
                },
            },
        },
        null,
        2,
    );
});
Open in playground

Exported

RestAPI

Derived from

Server

Options

The Options listed in this section are defined directly within the class. This class is derived from several parent classes. Therefore, it inherits Options from these parent classes. If you cannot find a specific Options in this list, we recommend consulting the documentation of the Server.

Option
Type
Default
Description
write
object
{}
write.init
object
{}
ct, containing any custom settings that you want to apply to the request. The parameters are identical to those of the {@link https://developer.mozilla.org/en-US/docs/Web/API/Request/Request|Request constructor}
string
write.init.method=POST
write.init.headers
headers
undefined
Object containing any custom headers that you want to apply to the request.
write.responseCallback
string
Callback function to be executed after the request has been completed.
string
write.acceptedStatus=[200,201]
write.url
string
URL
write.mapping
object
undefined
the mapping is applied before writing.
write.mapping.transformer
string
Transformer to select the appropriate entries
write.mapping.callback
examplecallback[]
undefined
with the help of the callback, the structures can be adjusted before writing.
object
write.report
write.report.path
string
Path to validations
object
write.partial
write.partial.callback
function
Callback function to be executed after the request has been completed. (obj, diffResult) => obj
object
write.sheathing
write.sheathing.object
object
Object to be wrapped
write.sheathing.path
string
Path to the data
read
object
{}
read.init
object
{}
ect containing any custom settings that you want to apply to the request. The parameters are identical to those of the {@link https://developer.mozilla.org/en-US/docs/Web/API/Request/Request|Request constructor}
string
read.init.method=GET
array
read.acceptedStatus=[200]
read.url
string
URL
read.mapping
object
undefined
the mapping is applied after reading.
read.mapping.transformer
string
Transformer to select the appropriate entries
read.mapping.callback
examplecallback[]
undefined
with the help of the callback, the structures can be adjusted after reading.

Properties

The Properties listed in this section are defined directly within the class. This class is derived from several parent classes. Therefore, it inherits Properties from these parent classes. If you cannot find a specific Properties in this list, we recommend consulting the documentation of the Server.

Methods

The methods listed in this section are defined directly within the class. This class is derived from several parent classes. Therefore, it inherits methods from these parent classes. If you cannot find a specific method in this list, we recommend consulting the documentation of the Server.

Constructor

constructor([options])
Parameters
  • [options] {object}: options contains definitions for the datasource.

Structural methods

getClone()
Returns
  • {RestAPI}

Static methods

[instanceSymbol]()2.1.0
Returns
  • {symbol}
This method is called by the instanceof operator.

Other methods

read()
Returns
  • {Promise}
Throws
  • {Error} the options does not contain a valid json definition
  • {TypeError} value is not a object
  • {Error} the data cannot be read
write()
Returns
  • {Promise}
Throws
  • {WriteError} the data cannot be written

Events

This component does not fire any public events. It may fire events that are inherited from its parent classes.

The current width of the area is too small to display the content correctly.