Overview

API client based on Axios.

Reference

Instance Methods
Name Description
public constructor() Create a new instance of the API client class.
Parameters:
  • path: string
    Base path of the request URL. For example, "/person"
  • origin?: string
    Request URL origin. For example, "https://example.com". Default is the current origin (location.origin).
  • options?: axios.AxiosRequestConfig
    Request Config. See here for more details on options. The options default to the following.
    • baseURL: string URL with a combination of path and origin parameters.
    • timeout: number 60000
    • responseType: string json
    • withCredentials: boolean true
                    import {components} from 'metronic-extension';

// If the second parameter origin is omitted, the current origin (location.origin) is used in the request URL.
class PersonApi extends components.Api {
  constructor() {
    super('/api/persons');
  }
}

// The second parameter sets the origin of any request URL.
class CustomerApi extends components.Api {
  constructor() {
    super('/api/customers', 'https://example.com');
  }
}

// The third parameter allows you to set the request configuration.
class OrderApi extends components.Api {
  constructor() {
    super('/api/orders', 'https://example.com', {
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    });
  }
}
                  
protected beforeRequestHook() Called just before the request. This function receives the request configuration object (axios.AxiosRequestConfig).
Parameters:
  • config: axios.AxiosRequestConfig
    Request Config.
                    beforeRequestHook(config) {
  // Set a token in the request header.
  config.headers.Authorization = 'Bearer AbCdEf123456';
}
                  
protected afterResponseHook() Called immediately after the response. The function receives the response object (axios.AxiosResponse).
Parameters:
  • res: axios.AxiosResponse
    Response object.
                    afterResponseHook(res) {
  if (response.status === 401)
    // Alerts when an authentication error occurs.
    alert('You are not authorized');
}
                  
protected errorHook() Called on request errors. This function receives a request error object (axios.AxiosError).
Parameters:
  • httpStatusCode: number
    HTTP status code.
  • error: axios.AxiosError
    Request error object.
                    errorHook(httpStatusCode, error) {
  if (httpStatusCode === 403)
    // Redirect in case of authentication error (403).
    location.replace('/');
}
                  
public getCancelToken() Get a token to cancel the request.
Return:
  • axios.CancelTokenSource A cancellation token.
public isCancel() Checks the RequestError object to see if the error is due to the request being canceled.
Parameters:
  • thrown: any
    Request Error object.
Return:
  • boolean True if the error is due to cancellation of the request.
Instance Properties
Name Description
protected client: axios.AxiosInstance Axios Instance.

Basic

Create a Person API to retrieve a person with an arbitrary ID.
          import {components} from 'metronic-extension';

class PersonApi extends components.Api {
  constructor() {
    super('/api/persons', 'https://example.com');
  }

  /**
   * Create person (POST https://example.com/api/persons).
   * @param {FormData} formData
   */
  async createPerson(formData) {
    return this.client.post('/', formData);
  }

  /**
   * Update person (PUT https://example.com/api/persons/:id).
   * @param {number} personId
   * @param {FormData} formData
   */
  async updatePerson(personId, formData) {
    return this.client.put(`/${personId}`, formData);
  }

  /**
   * Get person (GET https://example.com/api/persons/:id).
   * @param {number} personId
   */
  async getPerson(personId) {
    return this.client.get(`/${personId}`);
  }

  /**
   * Delete person (DELETE https://example.com/api/persons/:id).
   * @param {number} personId
   */
  async deletePerson(personId) {
    return this.client.delete(`/${personId}`);
  }
}

// API client.
const personApi = new PersonApi();

// Get person.
const personId = 1;
await personApi.get(personId);