DEV Community

Cover image for Total.js API routing: The game changer
Louis Bertson
Louis Bertson

Posted on

1

Total.js API routing: The game changer

API routing is Total.js internal mechanism used to expose API endpoints in a very simple way. The mechanism is designed to focus on handling a maximum number of internal operations with a minimum number of external endpoints. Therefore API routing only works with Total.js Schema and their operations.

How does it work?

You can create one endpoint (e.g /api/) and use it to target an infinite number of operations within your application. All you have to do is call that endpoint with the POST method and have in the body of the request, a JSON payload to specify what operation of what schema to target.

Example :

Download empty project

$ git clone https://github.com/totaljs/emptyproject-restservice api
$ cd api
$ npm install total4
$ node index.js
Enter fullscreen mode Exit fullscreen mode

Declare your API routes

// in /controllers/api.js


// Users
ROUTE('API  /api/   -users_query            *Users    --> query');
ROUTE('API  /api/   -users_read/{id}        *Users    --> read');
ROUTE('API  /api/   +users_insert           *Users    --> check insert (response)');
ROUTE('API  /api/   +users_update/{id}      *Users    --> update');
ROUTE('API  /api/   -users_remove/{id}      *Users    --> remove');
ROUTE('API  /api/   -users_refresh          *Users    --> refresh');

// ...
Create Schema and operations


// in /schemas/users.js

NEWSCHEMA('Users', function(schema) {

    // Fields definition

    schema.setQuery(function($) { 
        $.callback([]);
    });

    schema.setRead(function($) { 
        $.callback({}); 
    });

    schema.setInsert(function($, model) { 
        $.done(model.id) 
    });

    schema.setUpdate(function($, model) { 
        $.done(model.id) 
    });

    schema.setRemove(function($) { 
        $.success();
    });

    // Async/Await workflow

    schema.addWorkflow('refresh', async function ($) {
        var data = await FUNC.fetchData();

        if (!data) {
            $.invalid(404);
            return;
        }

        $.callback(data);

    });
    // Custom workflows
});
Enter fullscreen mode Exit fullscreen mode

Call endpoint from external

POST /api/
Content-Type: application/json

{
    "schema": "users_query?page=1",
    "data": {}
}
Enter fullscreen mode Exit fullscreen mode

Output

[]
Enter fullscreen mode Exit fullscreen mode

Required The request body is in JSON format and expects two parameters:

schema ---> (schema_name/{dynamic_arg_1}/{dynamic_arg_2}?query=arguments) to specify schema (supports params and query).
data ---> data payload (optional).

Good to know

The routing can contain two times +/- characters.
First : ROUTE('+API ...') or ROUTE('-API ...') for authorization purpose. (Read more here).
Second: +schema_name or -schema_name to specify if data reception is expected or not.

Websocket API

Yes. The API Routing supports the WebSocket protocol and we recommend it too. Its declaration is the same as the standard API Routing, except that the route must contain identifiers in the form @YOUR_NAME instead of the relative URL address. Let us try it:

Declare your Websocket API routes


// Users
ROUTE('API  @api   -users_remove/{id}   *Users --> remove');

// ...

// IMPORTANT: socket route
ROUTE('SOCKET / @api');
Websocket message:

{
    "TYPE": "api",
    "callbackid": "CUSTOM_CALLBACK_ID", // The value will be returned back
    "data": {
        "schema": "schema_name/{dynamic_arg_1}/{dynamic_arg_2}?query=arguments",
        "data": {}
    }
}
Enter fullscreen mode Exit fullscreen mode

Documentation

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs