Skip to content

Latest commit

 

History

History
258 lines (184 loc) · 8.66 KB

2.Events.md

File metadata and controls

258 lines (184 loc) · 8.66 KB

Events

By default, only request events are emitted and allow to deal with request configuration, response, errors, etc..

Listeners

These are caracteristics of a listeners :

  • A listener is a callback attached to an uniq event.
  • Listeners will be invoked in order of their priorities.
  • A listener can return a Promise to perfom an async actions, but it will suspend the dispatch process untill the returned Promise isn't fullfilled.
  • A listener is considerated as failed if an error is thrown or if a rejected Promise is returned.
  • A listener can abort the event propagation by using event.stopPropagation(), so the listeners with lower priorities will be skipped. It can also skip a specific listener on need (see example below).

Note that the dispatch process purposes 2 different strategies : "abort on listener failure" OR "ignore listeners failures" (See Dispatch events)

import Klient from '@klient/core';

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


//
// Register a listener on request event with no priority (0 by default)
//
klient.on('request', e => {...});


//
// This listener will be invoked before previous one because its priority is higher.
// As the listener is returning a Promise, this will suspend the dispatch process.
// The previous registered listener will be called only after this listener treatment (if succeed).
//
klient.on('request', e => {
  // Simulate an async process
  return new Promise(resolve => {
    // The next listener will be executed only after 3 seconds
    setTimeout(resolve, 3000);
  });
}, 2);


//
// This listener will stop event propagation, so listeners with priority lower than "1" won't be invoked 
// So, for a file request, the first listener declared will be skipped.
//
klient.on('request', e => {
  if (e.context.action === 'file') {
    // If e.stopPropagation is called, listeners with lower priority won't be invoked
    e.stopPropagation();

    // If e.skipNextListeners is called, the next X listeners won't be invoked
    // e.skipNextListeners(2);

    // If e.skipToListener is called, the next listeners won't be invoked untill listener with defined id 
    // The id represents its registration position
    // e.skipUntilListener(5);
  }
}, 1);


//
// Register listeners on many events
//
klient.on('request:success', e => {...});
klient.on('request:error', e => {...});
klient.on('request:done', e => {...});


//
// Register a listener invokable once
//
klient.once('request', e => {...});


//
// The first declared listener won't be invoked
//
klient.file('/robots.txt');

Request events

By default only request events are dispatched. To get more details about request lifecycle (and events order), please refer to Request documentation.

RequestEvent

alias = request

The request event is dispatched with abortOnFailure strategy on, so if a listener failed, the request will be rejected.

Properties

Name Type Description
request Request The current request object.
config AxiosRequestConfig Get current request config.
context object Get current request context.

RequestSuccessEvent

alias = request:success

The RequestSuccessEvent is emitted after Axios execution (in success case). It allows to access AxiosResponse.

Properties

All properties of RequestEvent are also available.

Name Type Description
relatedEvent RequestEvent The RequestEvent instance emitted before Axios execution.
response AxiosResponse The current response object.
data AxiosResponse.data The current response data.

RequestErrorEvent

alias = request:error

The RequestErrorEvent is emitted after Axios execution (in failure case). It allows to access AxiosError.

Properties

All properties of RequestEvent are also available.

Name Type Description
relatedEvent RequestEvent The RequestEvent instance emitted before Axios execution.
error AxiosError | Error The current error object.
response AxiosError.response The current error response object (available only if Axios failed for an invalid response code).
data AxiosError.response.data The current error response data.

RequestDoneEvent

alias = request:done

The RequestDoneEvent is emitted just after RequestSuccessEvent or RequestErrorEvent.

Properties

All properties of RequestEvent are also available.

Name Type Description
relatedEvent RequestSuccessEvent | RequestErrorEvent The event dispatched before this one.
result AxiosResponse | AxiosError | Error Get request result.
success boolean Check if result is an instance of Error.
data AxiosResponse.data | AxiosError.response.data

RequestCancelEvent

alias = request:cancel

The RequestCancelEvent is emitted when the request cancel method is called.

Properties

All properties of RequestEvent are also available.

Name Type Description
relatedEvent RequestEvent The event dispatched before this one.

Dispatch custom events

You can dispatch your own custom event by creating an Event class, instanciate an object of this class and dispatch it using the dispatcher service. Note that your custom event class must extend of base Event class exported by Klient core.

import Klient, { Event } from '@klient/core';

//
// Create custom event class extending of base Event class
//
class CustomEvent extends Event {
  // The event name can be used to listen it, should be uniq !
  static NAME = 'custom-event';

  constructor(relatedObject) {
    this.relatedObject = relatedObject;
  }
}


//
// Build Klient instance
//
const klient = new Klient('...');


//
// Register a listener to invoke when custom event is dispatched
//
klient.on('custom-event', e => {
  console.log(e.relatedObject.test); // Print true
});


//
// Create an instance of CustomEvent class, ready to be dispatched
//
const event = new CustomEvent({ test: true });


//
// Dispatch your event with strategy "abort when listener failed"
//
klient.dispatcher.dispatch(event)
  .then(() => {
    // All listeners has been called
  })
  .catch(listenerError => {
    // A listener has failed
  })
;


//
// Dispatch your event with strategy "ignore listeners failures"
//
klient.dispatcher.dispatch(event, false)
  .then(() => {
    // All listeners has been called
  })
  .catch(() => {
    // As failures are ignored, this catch block will never be called
  })
;

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