Skip to content

Latest commit

 

History

History
900 lines (693 loc) · 15.8 KB

File metadata and controls

900 lines (693 loc) · 15.8 KB

Klient instance

Constructor

The Klient constructor expect a single object representing the parameters. It will be stored as a deep js object in a bag.

Name Description Type Default
url Base url used for requests string | undefined undefined
request Static axios config to merge with all request config AxiosRequestConfig | undefined undefined
extensions Restrict extensions you want to load on new klient instance. string[] | undefined : use an empty array to init your klient with no extensions. Contrariwise, undefined means all extensions. undefined
debug Enable debug mode boolean | undefined false

The parameters can be extended with any property containing any value !

Usage

import Klient from '@klient/core';


//
// With no parameters
// Equal to new Klient('http://127.0.0.1');
//
new Klient();


//
// With base url as uniq parameter
//
new Klient('https://api.example.com/v1');


//
// With several parameters
//
new Klient({
  url: 'https://api.example.com/v1',
  extensions: [],
  debug: true,
  request: {
    headers: {
      'Content-Type': 'application/json',
    },
  },
});


//
// Read parameter
// 
klient.parameters.get('request.headers');


//
// Set a custom parameter
// 
klient.parameters.set('customKey', 'customValue');


//
// Overwrite an existant parameter
// 
klient.parameters.set('request.headers', {
  'Content-Type': 'application/json',
  'Authorization': 'Test',
});

// ... See bag documentation for more usages

Properties

Name Type Description
url string readonly The value of url defined into parameters.
extensions string[] readonly The names of loaded extensions.
debug boolean readonly Is debug mode enabled.
parameters Bag readonly Get parameters bag.
services Bag readonly Get services bag.
factory RequestFactory readonly Get factory instance from services bag.
dispatcher Dispatcher readonly Get dispatcher instance from services bag.

Usage

import Klient from '@klient/core';

//
// Initialize Klient instance with parameters
//
const klient = new Klient({
  url: 'https://api.example.com/v1',
  extensions: [],
  debug: false,
  request: {
    headers: {
      'Content-Type': 'application/json',
    },
  },
});



//
// Use Klient properties
//
console.log(
  klient.url,              // Print "https://api.example.com/v1"
  klient.extensions,       // Print []
  klient.debug,            // Print false
  klient.parameters.all(), // Print all defined parameters 
  klient.services.all(),   // Print all defined services 
  klient.factory,          // Print RequestFactory instance 
  klient.dispatcher,       // Print Dispatcher instance 
);

Methods

request


Perform an http request.

request(urlOrConfig: string | KlientRequestConfig | AxiosRequestConfig): Request<AxiosResponse>

Example

import Klient from '@klient/core';

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


//
// Add listener on request event to make action on specific context
//
klient.on('request', e => {
  if (e.context.action === 'create') {
    // Do something ...
  }
});


//
// The returned Request object is an extended Promise
//
const request = klient.request({
  url: '/messages',
  method: 'POST',
  data: { content: 'Hello, world !' },
  // Context is custom klient usable by listeners
  context: {
    action: 'create',
  },
});


//
// The Request is fulfilled as Axios does 
//
request
  .then(axiosResponse => {
    console.log(
      axiosResponse.status, // Print response http status code
      axiosResponse.data,   // Print response content
    )
  })
  .catch(axiosError => {
    if (axiosError.response) {
      console.log(
        axiosError.response.status, // Print response http status code
        axiosError.response.data,   // Print response content
      )
    }
  })
;


//
// Make GET request with no specific configuration
//
klient.request('/example');

 

get


Perform a GET request.

get(url: string, config?: KlientRequestConfig | AxiosRequestConfig): Request<AxiosResponse>

Example

import Klient from '@klient/core';

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


//
// GET Request with url only
//
klient
  .get('/example')
  .then(axiosResponse => {
    // ...
  })
  .catch(axiosError => {
    // ...
  })
;


//
// GET request with specific config
//
klient
  .get('/example', {
    params: {
      test: true
    }
  })
  .then(axiosResponse => {
    // ...
  })
  .catch(axiosError => {
    // ...
  })
;

 

post


Perform a POST request.

post(url: string, data: any, config?: KlientRequestConfig | AxiosRequestConfig): Request<AxiosResponse>

Example

import Klient from '@klient/core';

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


//
// POST request containing data
//
klient
  .post('/posts', { title: '...', content: '...' })
  .then(axiosResponse => {
    // ...
  })
  .catch(axiosError => {
    // ...
  })
;

 

put


Perform a PUT request.

put(url: string, data: any, config?: KlientRequestConfig | AxiosRequestConfig): Request<AxiosResponse>

Example

import Klient from '@klient/core';

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


//
// PUT request containing data
//
klient
  .put('/posts', { title: '...', content: '...' })
  .then(axiosResponse => {
    // ...
  })
  .catch(axiosError => {
    // ...
  })
;

 

patch


Perform a PATCH request.

patch(url: string, data: any, config?: KlientRequestConfig | AxiosRequestConfig): Request<AxiosResponse>

Example

import Klient from '@klient/core';

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


//
// PATCH request containing data
//
klient
  .patch('/posts/1', { title: '...' })
  .then(axiosResponse => {
    // ...
  })
  .catch(axiosError => {
    // ...
  })
;

 

delete


Perform a DELETE request.

delete(url: string, config?: KlientRequestConfig | AxiosRequestConfig): Request<AxiosResponse>

Example

import Klient from '@klient/core';

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


//
// DELETE Request with url only
//
klient
  .delete('/posts/1')
  .then(axiosResponse => {
    // ...
  })
  .catch(axiosError => {
    // ...
  })
;


//
// DELETE request with specific config
//
klient
  .delete('/posts/1', {
    params: {
      test: true
    }
  })
  .then(axiosResponse => {
    // ...
  })
  .catch(axiosError => {
    // ...
  })
;

 

head


Perform an HEAD request.

head(url: string, config?: KlientRequestConfig | AxiosRequestConfig): Request<AxiosResponse>

Example

import Klient from '@klient/core';

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


//
// HEAD Request with url only
//
klient
  .head('/posts/1')
  .then(axiosResponse => {
    // ...
  })
  .catch(axiosError => {
    // ...
  })
;


//
// HEAD request with specific config
//
klient
  .head('/posts/1', {
    params: {
      test: true
    }
  })
  .then(axiosResponse => {
    // ...
  })
  .catch(axiosError => {
    // ...
  })
;

 

options


Perform an OPTIONS request.

options(url: string, config?: KlientRequestConfig | AxiosRequestConfig): Request<AxiosResponse>

Example

import Klient from '@klient/core';

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


//
// OPTIONS Request with url only
//
klient
  .options('/posts/1')
  .then(axiosResponse => {
    // ...
  })
  .catch(axiosError => {
    // ...
  })
;


//
// OPTIONS request with specific config
//
klient
  .options('/posts/1', {
    params: {
      test: true
    }
  })
  .then(axiosResponse => {
    // ...
  })
  .catch(axiosError => {
    // ...
  })
;

 

file


Fetch file on server and transform it to Blob instance.

file(urlOrConfig: string | KlientRequestConfig | AxiosRequestConfig): Promise<Blob>

Example

import Klient from '@klient/core';

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


//
// File requests is flag as "file" action
//
klient.on('request', e => {
  if (e.context.action === 'file') {
    // ...
  }
});


//
// Fetch file https://api.example.com/v1/example.pdf
//
klient
  .file('example.pdf')
  .then(blob => {
    console.log(blob);
  })
  .catch(axiosError => {
    // ...
  })
;


//
// Precise whole url for by passing baseURL
//
klient
  .file({ url: 'https://api.example.com/documents/example.pdf' })
  .then(blob => {
    console.log(blob);
  })
  .catch(axiosError => {
    // ...
  })
;

 

on


Listen a specific event.

on(
  event: string,                                   // The event alias
  callback: (e: Event) => Promise<void> | void,    // The callback invoked on dispatch
  priority: number = 0,                            // Priority of callback
  once: boolean = false                            // Is once callback - use once method instead defining true
): Klient

Example

import Klient from '@klient/core';

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


//
// Declare listeners
//
const requestEventListener = e => {...};
const requestEventListenerBis = e => {...};
const requestDoneEventListener = e => {...};


//
// Register listeners
//
klient
  .on('request', requestEventListener)
  // This listener will be called before previous one
  // because its priority is higher
  .on('request', requestEventListenerBis, 2)
  .on('request:done', requestDoneEventListener)
;

 

once


Listen a specific event, once.

once(
  event: string,                                   // The event alias
  callback: (e: Event) => Promise<void> | void,    // The callback invoked on dispatch
  priority: number = 0                             // Priority of callback
): Klient

Example

import Klient from '@klient/core';

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


//
// Declare listeners
//
const requestEventListener = e => {...};
const requestDoneEventListener = e => {...};


//
// Register listeners callable once time
//
klient
  .once('request', requestEventListener)
  .once('request:done', requestDoneEventListener)
;

 

off


Unset a listener

off(
  event: string,                                   // The event alias
  callback: (e: Event) => Promise<void> | void,    // The callback invoked on dispatch
): Klient

Example

import Klient from '@klient/core';

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


//
// Declare listener
//
const requestEventListener = e => {...};


//
// Register listener
//
klient.on('request', requestEventListener);


//
// Unregister listener
//
klient.off('request', requestEventListener);

 

load


Manually load extensions after klient instance construction (see Extensions).

load(extensions: string[] | undefined): Klient

Example

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

//
// Create an extension
//
const extension = {
  name: '@klient/example',
  initialize: klient => {
    // Add features
    klient.services.set('test', {
      customMethod: true
    })
  }
}


//
// Register the extension
//
Extensions.push(extension);


//
// Build Klient instance
//
const klient = new Klient({
  url: 'https://api.example.com/v1',

  // Do not load extensions at instance construction
  extensions: [],
  
  // Specify extensions to load at instance construction
  // extensions: ['@klient/example'],

  // Load all extensions at instance construction
  // extensions: undefined,
});


//
// Load manually specific extensions
//
klient.load(['@klient/example']);


//
// Use features of your extension
//
klient.services.get('test').customMethod(); // Return true

 

extends


Add new method or property to a created klient instance.

extends(property: string, value: any, writable: boolean = false): Klient

Example

import Klient from '@klient/core';

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


//
// Create a counter for the example
//
klient
  .extends('counter', 0)
  .extends('increment', () => {
    klient.customCounter += 1;
    return klient;
  }, false)
;


//
// Use the counter
//
console.log(klient.increment().counter); // Print 1

 

cancelPendingRequests


Cancel all requests created by factory by calling Request.cancel method of pending requests. The requests will be cancelled by Axios at execution step. The request cannot be cancelled after Axios execution. Cancelling a request will reject the Request Promise, so you need to check it in catch block.

cancelPendingRequests(): Klient

Example

import Klient from '@klient/core';

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


//
// Make an http requests
//
klient
  .request('/posts')
  .catch(e => {
    if (klient.isCancel(e)) {
      // ...
    }
  })
;

klient
  .request('/foos')
  .catch(e => {
    if (klient.isCancel(e)) {
      // ...
    }
  })
;


//
// Cancel pending requests
//
klient.cancelPendingRequests();

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