logo

RestAPI

The RestAPI class manages the requests to a REST API.

  • The base URL of the API is automatically concatenated to the path of the requests.
  • The config of the API is automatically merged with the config of the requests.
  • The status of the requests is automatically tracked and can be accessed through the status property.
  • The requests are sent with the Fetch class, so all features of the Fetch class are available.

Properties

  • baseURL (string): The base URL of the REST API. This is the URL that will be prepended to all request paths.
  • config (T extends RestApiConfig): The default configuration for the REST API. This configuration will be merged with the configuration of individual requests.
  • status (Status): The status of the requests. This property tracks the status of each request (e.g., pending, success, error) and can be accessed to check the status of a request.

Send a request

The connect, delete, get, head, options, patch, post, put and trace methods are used to send a request to the REST API.

import { RestAPI } from '@aracna/core';

const api = new RestAPI('https://dummyjson.com/');

(async () => {
  let response;

  response = await api.get('users');
  if (response instanceof Error) return;

  // will log FetchResponse
  console.log(response.data);
})();

Track the status of a request

The status property in the RestAPI class is an instance of the Status class. It is used to track the status of the requests sent by the RestAPI class.

import { RestAPI, wf } from '@aracna/core';

const api = new RestAPI('https://dummyjson.com/');

(async () => {
  // will log "IDLE"
  console.log(api.status.get('GET', 'test'));

  api.get('test').then(() => {
    // will log "SUCCESS"
    console.log(api.status.get('GET', 'test'));
  });

  // will log "PENDING"
  console.log(api.status.get('GET', 'test'));

  await wf(() => api.status.isSuccess('GET', 'test'));

  // will log "IDLE"
  console.log(api.status.get('GET', 'unknown'));

  api.get('unknown').then(() => {
    // will log "ERROR"
    console.log(api.status.get('GET', 'unknown'));
  });

  // will log "PENDING"
  console.log(api.status.get('GET', 'unknown'));
})();

Transform the request body

The transformBody method is used to transform the body of a request before it is sent.

This method accepts four parameters:

  • method: A string representing the HTTP method of the request.
  • path: A string representing the path of the request.
  • body: The body of the request. It can be any type and it can be undefined.
  • config: The configuration of the request. It is an instance of the RestApiConfig class.

The transformBody method is asynchronous and returns a promise that resolves with the transformed body.

import { RestAPI } from '@aracna/core';

class MyAPI extends RestAPI {
  async transformBody(method, path, body, config) {
    body.firstName = body.name.split(' ')[0];
    body.lastName = body.name.split(' ')[1];

    return body;
  }
}

const api = new MyAPI('https://dummyjson.com/');

(async () => {
  let body, response;

  body = {
    email: 'john.doe@email.com',
    name: 'John Doe'
  };

  response = await api.post('users/add', body);
  if (response instanceof Error) return;

  // will log FetchResponse
  console.log(response.data);
})();

Transform the request query params

The transformQueryParameters method is used to transform the query parameters of a request before it is sent.

This method accepts four parameters:

  • method: A string representing the HTTP method of the request.
  • path: A string representing the path of the request.
  • body: The body of the request. It can be any type and it can be undefined.
  • config: The configuration of the request. It is an instance of the RestApiConfig class.

The transformQueryParameters method is asynchronous and returns a promise that resolves with the transformed query parameters as a string.

import { RestAPI, serializeQueryParameters } from '@aracna/core';

class MyAPI extends RestAPI {
  async transformQueryParameters(method, path, body, config) {
    if (config.query.limit === 0) {
      delete config.query.limit;
    }

    return serializeQueryParameters(config.query);
  }
}

const api = new MyAPI('https://dummyjson.com/');

(async () => {
  let query, response;

  query = {
    limit: 0,
    select: ['email', 'firstName', 'lastName']
  };

  response = await api.get('users', { query });
  if (response instanceof Error) return;

  // will log FetchResponse
  console.log(response.data);
})();

Use a custom error status handler

The handleError method is used to handle any errors that occur during the execution of a request.

This method accepts five parameters:

  • method: A string representing the HTTP method of the request.
  • path: A string representing the path of the request.
  • body: The body of the request. It can be any type and it can be undefined.
  • config: The configuration of the request. It is an instance of the RestApiConfig class.
  • error: The error that occurred during the execution of the request. It is an instance of the FetchError class.

The handleError method returns a boolean indicating whether the error was handled. If the method returns true, the error was handled and the request can continue. If the method returns false, the error was not handled and the request should be aborted.

import { RestAPI } from '@aracna/core';

class MyAPI extends RestAPI {
  async handleError(method, path, body, config, error) {
    if (path === 'unknown') {
      return true;
    }

    return false;
  }
}

const api = new MyAPI('https://dummyjson.com/');

(async () => {
  await api.get('unknown');

  // will log "SUCCESS"
  console.log(api.status.get('GET', 'unknown'));
})();

Use a custom pending status handler

The handlePending method is used to handle the pending state of a request. This method is called before the request is sent.

This method accepts four parameters:

  • method: A string representing the HTTP method of the request.
  • path: A string representing the path of the request.
  • body: The body of the request. It can be any type and it can be undefined.
  • config: The configuration of the request. It is an instance of the RestApiConfig class.

The handlePending method is asynchronous and returns a promise that resolves with a boolean indicating whether the pending state was handled. If the method returns true, the pending state was handled and the request can continue. If the method returns false, the pending state was not handled and the request should be aborted.

import { RestAPI } from '@aracna/core';

class MyAPI extends RestAPI {
  async handlePending(method, path, body, config) {
    if (path === 'users') {
      return false;
    }

    return true;
  }
}

const api = new MyAPI('https://dummyjson.com/');

(async () => {
  let response;

  response = await api.get('users');

  // will log FetchError
  console.log(response);
})();

Use a custom success status handler

The handleSuccess method is used to handle the successful state of a request. This method is called after the request is successfully completed.

This method accepts five parameters:

  • method: A string representing the HTTP method of the request.
  • path: A string representing the path of the request.
  • body: The body of the request. It can be any type and it can be undefined.
  • config: The configuration of the request. It is an instance of the RestApiConfig class.
  • response: The response of the request. It is an instance of the FetchResponse class.

The handleSuccess method is asynchronous and returns a promise that resolves with a boolean indicating whether the successful state was handled. If the method returns true, the successful state was handled and the request can continue. If the method returns false, the successful state was not handled and the request should be aborted.

import { RestAPI } from '@aracna/core';

class MyAPI extends RestAPI {
  async handleSuccess(method, path, body, config, response) {
    if (path === 'users') {
      return false;
    }

    return true;
  }
}

const api = new MyAPI('https://dummyjson.com/');

(async () => {
  let response;

  response = await api.get('users');

  // will log FetchError
  console.log(response);
})();