Skip to content

Latest commit

 

History

History
269 lines (198 loc) · 8.07 KB

1.Usage.md

File metadata and controls

269 lines (198 loc) · 8.07 KB

Usage

The principal role of core library is to export the Klient class, used to create client instances for each API you need to deal with. The result object will be used to make requests on target host. The klient object contains an event system which allows you to customize requests or make actions during their lifecycle (before or after Axios execution).

To be the most configurable possible, the Klient class is composed of useful elements :

  • services : A Bag which contains js objects used as service. All Klient methods invoke a specific service. The Klient core library is composed of 2 services : the "dispatcher" (the event system) and the "factory" (the request builder).
  • parameters : A Bag which contains js plain object. Services behaviour can be customized with parameters.
  • extensions : Extensions can register reusable services and expect for specific parameters.

Setup a Klient instance

When you build a new Klient instance, the most important is to initialize it with the correct hostname of your target webservice. This value will be stored inside a Bag named parameters, used by core services. Custom parameters keys can also be defined for your application or by extensions you are using. See Klient API for more details about each basic parameters.

import Klient from '@klient/core';


//
// Enable extensions we need
//
import '@klient/rest';
import '@klient/mock';


//
// Build new Klient instance by defining core (and custom) parameters
//
new Klient({
  url: 'https://example.rest/api',                  // Target host
  debug: true,                                      // Enable debug mode
  extensions: ['@klient/mock', '@klient/rest'],     // Optionally specify extensions to load
  request: {                                        // Static Axios request config to use for all requests
    headers: {
      'Content-Type': 'application/json',
    }
  }
});


//
// 127.0.0.1:80 will be used if you do not provide any args
//
new Klient();


//
// You can also initialize instance just with baseURL
//
new Klient('https://example.rest/api');

Use a Klient instance

Once configured, the Klient instance can be used to execute request to your webservice. The request will be constructed by the service "factory". The Request class is a Promise that uses the service "dispatcher" to emit events during its lifecycle. By default, the returned Promise will be resolved as Axios does.

Find all available methods and properties in the Klient API documentation.

import Klient from '@klient/core';


//
// Setup new Klient object
//
const klient = new Klient();


//
// Execute a request
//
klient
  .request({
    url: '/example',
    method: 'POST',
    data: { prop: 'value' },
    context: {
      // Define custom request context, usable by listeners
    }
  })
  .then(axiosResponse => {
    // Deal with AxiosResponse object
    console.log(
      axiosResponse.status,
      axiosResponse.data,
      // ...
    )
  })
  .catch(err => {
    // Deal with Error or AxiosError object
    if (err.response) {
      // ...
    }
  })
;


//
// Execute a request with "verb" methods. See Klient API for more details.
//
klient.post('/example', { prop: 'value' });


//
// Create a request instance and execute it manually
//
const request = klient.factory.createRequest({
  url: '/example',
  method: 'POST',
  data: { prop: 'value' },
  headers: {},
});

// You are allowed to change configuration before execution
request.config.headers.Authorization = 'Bearer token';

// Call "execute" method to start request process
request.execute().then(axiosResponse => {...});

Customize a Klient instance

The klient object can be extended by many ways. You can define custom properties/methods directly to klient object or add custom services and listeners. It's also possible to extends the Klient class for specific needs.

In most of cases, you need to call a webservice based on a specific architecture (rest, soap, ...). As Klient is fully extendable, you probably use inner concepts (services, parameters) for making it easy to use in your application. For example, if your Klient is used to call a REST API, you can create a service able to manage registered resources simply (able to determine uri for each resource, etc...). That's role of services defined by @klient/rest package.

Generally, the extensions can be used for configuring a Klient instance quickly.

import Klient from '@klient/core';

//
// Enable extensions
//
import '@klient/rest';


//
// Setup new Klient instance
//
const klient = new Klient();


//
// Add methods/properties directly to Klient instance
//
klient.extends(
  'customProp',    // Accessible property name
  'someValue',     // Set a value
  true             // Is writable property
);

klient.extends(
  'customFn',      // Accessible method name
  () => null,      // Define custom function
  false            // Is method overridable
);

// Use custom methods/properties
console.log(
  klient.customProp, // Print "someValue"
  klient.customFn()  // Print null
);


//
// Alternatively, use services Bag to store anything reusable
//
klient.services.set('example', {
  sayHelloWorld() {
    // Use parameters to make you service configurable simply
    if (klient.parameters.get('helloWorldEnabled') === false) {
      return null;
    }

    return 'Hello world!';
  }
});

// Create a method on Klient instance which is a shortcut to your service method
klient.extends('helloWorld', () => klient.services.example.sayHelloWorld());

// Use your service (multiple ways)
console.log(
  klient.services.get('example').sayHelloWorld(), // Print "Hello world!"
  klient.services.example.sayHelloWorld(),        // Print "Hello world!"
  klient.helloWorld()                             // Print "Hello world!"
);

klient.parameters.set('helloWorldEnabled', false);

console.log(
  klient.helloWorld() // Print null
);

Listen for events

When a request is executed, it will emit events before and after Axios execution. You can add listeners on events for performing an action at any moment. Listeners can deal with request configuration, response, errors, and can perform async actions if need.

Please refer to Events documentation for more details.

import Klient from '@klient/core';


//
// Setup new Klient instance
//
const klient = new Klient();


//
// Listen for all requests executed with the klient declared below
//

// Before Axios execution
klient.on('request', event => {
  console.log(event.config);    // Access to request config
});

// After Axios execution, on success case
klient.on('request:success', event => {
  console.log(event.data);      // Access to AxiosResponse.data property
});

// After Axios execution, on failure case
klient.on('request:error', event => {
  console.log(event.error);     // Access to Error
  console.log(event.response);  // Access to AxiosResponse if exists
});

// After Axios execution, request:success and request:error events
klient.on('request:done', event => {
  console.log(event.result);    // Access to response/error object
});


//
// Execute a request will invoke listeners
//
klient.request('/example').then(...);

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