How To: Work with API

This section presents ways to extend the application components responsible for sending requests to the backend.

Extension for API Requests

API request object modification

The API request is configured via the description of the AxiosRequest object, which can be changed by subscribing to the events of the requestSubscriber object:

requestSubscriber.on('sra_products.get', ({request}) => {
request.params.limit = 100
})

Event name is the address of the entity being called + method (get, post, and others). Here is a list of requests and their events:

  • Request address https://m.pwajet.simtechdev.us/api/4.0/sra_cart_content/ - event sra_cart_content.get.
  • Request address https://m.pwajet.simtechdev.us/api/4.0/sra_ext_bm_layouts/spalayout/sra_ext_bm_locations/index/sra_ext_bm_blocks/ - event sra_ext_bm_layouts.get.
  • Request address https://m.pwajet.simtechdev.us/api/4.0/sra_storefront/ - event sra_storefront.get.

Note

Like all other event emitters in PWAjet, requestSubscriber supports a debug method that enables all events to be output to the console: requestSubscriber.debug ().

Location: pwajet.core.api.requestSubscriber.

When to use: * to modify an existing request;

  • to add parameters, correct data in a request, add headers (for example, authorization).

How To Extend the AbstractRequest class

import { core: { api: { client, AbstractRequest }}} from 'pwajet'

class VendorsRequest extends AbstractRequest {
 entityPath = 'vendors';
 prefix = 'sra_';
 handlerParams:  any;
 params: any;

constructor(
  client: ReturnType<typeof client.getClient>,
  config: ReturnType<typeof client.getConfig>
 ) {
   super(client, config)
  this.handlerParams = {}
this.params = {}
}

protected buildUrl(): string {
 let url = super.buildUrl()
url = url + (this.handlerParams.id ? `${this.handlerParams.id}/` : '')

 return url
 }

protected initParams(): void {
this.params = {
...this.params,
language:   this.config.language,
sl:         this.config.language,
lang_code:  this.config.language,
}

if (this.handlerParams.orderBy) {
this.params.sort_by = this.handlerParams.orderBy
}

if (this.handlerParams.order) {
this.params.sort_order = this.handlerParams.order
}

if (this.handlerParams.search) {
this.params.q = this.handlerParams.search
}
}
}

export default VendorsRequest

Location: pwajet.core.api.AbstractRequest

When to use: * to create requests for new resources.