Skip to content

Latest commit

 

History

History
203 lines (157 loc) · 5.43 KB

3.Request.md

File metadata and controls

203 lines (157 loc) · 5.43 KB

Request

A Request is an extended Promise object with custom methods (like cancel), instanciated and configured by factory service (on need). It will be initialized with the dispatcher service, used by request object to emit events before and after Axios execution.

The factory will keep requests during their execution only.

Lifecycle

When a request is going to be executed, specific events are dispatched in order described below.

klient
  .request('/workflow')
    |
    |
   (1)───[ Dispatch "request" Event ]
    |
    |    This event allows listeners to edit/finalize request config.
    |    For example, a listener can append an auth token in headers.
    |    This event is dispatch with "abort on listener failure" strategy,
    |    so, if a listener failed on this event, request will be rejected.
    |
    |
   (2)───[ Execute request with Axios ]
    |
    |
   (3)─────────[ OPTIONAL : Dispatch "request:cancel" Event ]
    |
    |          If the request cancel method has been called before/during axios execution,
    |          the request will be rejected with an AxiosCancelledError.
    |
    |
    |
    |─── At this point, the request has been executed with Axios
    |    and the result is available.
    |
    |
   (4)───[ Dispatch "request:success" OR "request:error" Event ]
    |
    |    Theses events give access to request hydrated with the Axios result.
    |
    |
    |
   (5)───[ Dispatch "request:done" Event ]
    |
    |    It's the last event emitted on every request, dispatched whenever the result type.
    |
    |
    |
   (6)───[ Request promise is fulfilled as Axios does ]
    |
    |
   .then(axiosResponse => {...})
   .catch(axiosError => {...})
;

Please refer to Event documentation for details of each events.

Manual execution

By default, the requests are directly executed when using Klient methods. But sometimes you want to prepare a request object for executing it later. In that case, you will need to create a request using the factory service.

import Klient from '@klient/core';

//
// Build Klient instance
//
const klient = new Klient('https://api.example.com/v1');


//
// At this step, request is a Promise object but the process is waiting
//
const request = klient.factory.createRequest({ url: '/test' });


//
// Call "execute" method will start the request process
//
request.execute().then(...).catch(...);

Cancellation

The request can be cancelled by using "cancel" method of Request class or by cancelling all pending requests, by using factory. The cancel method uses the "abortController" of Axios config (automatically configured).

The request can be cancelled only before the end of Axios execution, but will be really cancelled only during axios execution step ! The cancellation will reject your request promise as Axios does. For more information, please refer to Axios documentation.

import Klient from '@klient/core';

//
// Build Klient instance
//
const klient = new Klient('https://api.example.com/v1');


//
// Perform a request
//
const request = klient.request({ url: '/test' })
  .then(() => {...})
  .catch(e => {
    if (klient.isCancel(e)) {
      return;
    }

    // ...
  })
;


//
// Cancel a single request
//
request.cancel();


//
// Cancel all pending requests (using factory)
//
klient.cancelPendingRequests();

Override Axios execution

By default the request handler is Axios, but you can replace it by your own. It can be useful to mock some response for some specific request or for managing offline usage, etc...

import Klient from '@klient/core';


//
// Create custom request handler like Axios : AxiosRequestConfig => Promise<AxiosResponse>
//
const postListMockHandler = config => {
  // Reject example
  // return Promise.reject(new Error());

  // Resolve request like Axios does
  return Promise.resolve({
    status: 200,
    data: [
      { title: '...', content: '...' }
    ],
  });
}


//
// Override request handler by using a listener
//
klient.on('request', event => {
  // Ignore request which is not [GET] /posts
  if (config.url !== '/posts' || config.method !== 'GET') {
    return;
  }

  // Replace request handler with custom one
  event.request.handler = postListMockHandler;
});


//
// Make request [GET] /posts will invoke our listener defined before
// so request will be resolved with the result of postListMockHandler
//
klient.get('/posts').then(axiosResponse => {
  console.log(axiosResponse.data[0].title); // Print "..."
});


//
// Override request handler by using request object
//
const request = klient.factory.createRequest('/posts');
request.handler = customRequestHandler;

TOC   >   Introduction   >   Usage   >   Events   >   Request   >   Extensions   >   Utilities   >   API