View on GitHub

kinka

⚡️ HTTP web client for browsers ⚡️

Documentation

Here is all public documentation about kinka.
If you didn’t find the answer on your question don’t be shy to post your question here

Kinka have two versions: development and production (~4KB)
For using production version needs set environment variable NODE_ENV to production

process.env.NODE_ENV = 'production'

Kinka instance

kinka['name'](options)
Name Options Returns Description
abort cancelToken: string undefined abort request by abortable key
example:
kinka.get('/users', { cancelToken: 'usersKey' }) kinka.abort('usersKey') //GET:/users request will been canceled
all requests: Array<Promise> Promise<Response[]> That method can helps if needed to wait more than one request
Return a promise that is fulfilled when all the items in the array are fulfilled.
example:
const [friends, family, donuts] = await kinka.all([ kinka.get('/friends'), kinka.get('/family'), kinka.get('/donuts'), ]) console.log(friends.data) console.log(family.data) console.log(donuts.data)
create object?: config (KinkaInstanceOptions) Kinka create new kinka instance with your own options.
example:
const api = kinka.create({baseURL: 'myapi.com'}) api.get('/all') // GET: myapi.com/all promise
custom method: string,
path: string,
options?: RequestOptions
Promise<Response> create request with custom method name. example:
const promise = kinka.custom('kill', '/all') // KILL: myapi.com/all promise
delete path: string,
options?: RequestOptions
Promise<Response> create request with DELETE method.
get path: string,
options?: RequestOptions
Promise<Response> create request with GET method.
head path: string,
options?: RequestOptions
Promise<Response> create request with HEAD method.
options path: string,
options?: RequestOptions
Promise<Response> create request with OPTIONS method.
patch path: string,
data?: any,
options?: RequestOptions
Promise<Response> create request with PATCH method.
post path: string,
data?: any,
options?: RequestOptions
Promise<Response> create request with POST method.
put path: string,
data?: any,
options?: RequestOptions
Promise<Response> create request with PUT method.
clone Kinka create a new copy of the current kinka instance

Interfaces

</table>
RequestOptions: object
Property Default Description
query?: object undefined query params for your http request
example:

kinka.get('/all', { 
    query: { 
        disabled: true, 
        sortBy: 'date' 
    }})
// request will have url: 
// /all?disabled=true&sortBy=date
    
cancelToken?:string undefined With abortable key your request have ability to cancel last request if request with the same key is start launching
omitCatches?: bool instance.omitCatches | true With true your responses will not be throwing exceptions and you don't need to wrap your requests in try/catch.
And if you want to catch exception you can get this from response.err or response.isError
Example:

const { err, status } = await kinka.get('/bad-request')
if(err){
    // catched exception
}
  
Otherwise:

try{
    const { data } = await kinka.get('/bad-request')
}catch(e){
    // catched exception
}
  
</td> </tr>
credentials?: bool false Indicates that this request should use credentials
(like cookies or specific auth headers)
Sets flag withCredentials
Read more about it here...
successStatus?: number range between 200 and 300 Allows to set specific success status for your http request
If you added this property with 201 value then all another responses
with success status codes will be catches an exception,
or will have fulfilled `err` property
Example:

const { data, err } = await kinka.get('/wrong-request', {
  successStatus: 401 
})
// request returned 401 status code then
// this condition have truthy value
if(!err) {
  console.log('response -> ', data)
}
  
headers?: object {} Sets request headers
Example:

await kinka.get('/donuts/all', { 
    headers: { 
        ['Specific-Header']: 'arrgghhh' 
    } 
})
    
data?: any undefined Sets the request body. It is content which needed to send on server
timeout?: number 0 Sets the number of milliseconds after which
request automatically will be terminated. 0 value means no timeout.
Read more about it here...
auth?: any undefined Sets data for the instance `auth` mixin.
Only works if `auth` mixin is setted in instance options
Example:

const api = kinka.create({
  baseURL: `${baseURL}/${apiPath}`,
  auth: ({ username, password }) => ({
    headers: {
      Authorization: 
        `Token ${username}:${stringToSHA256(password)}`,
    },
  }),
})
api.post(
  '/user',
  { fullName: 'John Week' },
  {
    auth: { 
      username: 'boss-killer', 
      password: 'IloveCats<3'
    },
  }
)
    
onDownloadProgress?: function undefined Allows to handle progress of the request download

const response = await kinka.get('/kittens', {
  onDownloadProgress: ({ total, loaded }) => {
    console.log(
      'kittens downloaded at ',
      Math.floor(loaded * 100 / total),
      '%'
    )
  },
})
    
onUploadProgress?: function undefined Allows to handle progress of the request upload

const response = await kinka.post('/kittens', {
  onUploadProgress: ({ total, loaded }) => {
    console.log(
      'kittens uploaded at ',
      Math.floor(loaded * 100 / total),
      '%'
    )
  },
})
    
InstanceOptions: object
Property Default Description
baseURL?: string location.origin Sets the `baseURL` for instance.
Allows to set base url address for server.
Example:

const api = kinka.create({ baseURL: 'https://api.com' })
api.get('/data') //GET: https://api.com/data
        
customMethods?: (string[] | null) null Allows to create instance methods which will have special http methods.
Example:

const api = kinka.create({
    baseURL: 'https://api.com',
    customMethods: ['move'],
})
api.move('/data', { data: { files: null } })
// MOVE: https://api.com/data
        
headers?: object {} Allows to set specific headers for each request created via instance
Example:

const api = kinka.create({
    baseURL: 'https://api.com',
    headers: {
        'API_VERSION': '01',
    },
})
api.get('/data')
/*
    GET: https://api.com/data
    headers: {
        "API_VERSION": "01"
    }
*/
        
omitCatches?: bool true Same option as in `RequestOptions` but it works globally
for each request created via instance
timeout?: number 0 Same option as in `RequestOptions` but it works globally
for each request created via instance
inspectors?: object {} Allows to attach inspectors to your kinka instance.
Inspectors it is watchers for requests or responses
which allows dynamically change request options or response data.
If needed to change request options or response data then
need to return modified options/response. Example:

const api = kinka.create({
  baseURL: `${baseURL}/${apiPath}`,
  inspectors: {
    request: (url, method, options) => {
      console.log(`request ${url}`, options)
      // here request will be not modified
    },
    response: (url, method, response) => {
      console.log(`response ${url}`, response)
      if(!response.data){
          response.data = null
      }
      // here response will be modified
      // and data will be null 
      return response
    },
  },
})
        
middlewares?: function[] [] Allows to attach middlewares to your kinka instance.
Middleware have ability to change behaviour of all actions created via kinka
Example:

const api = kinka.create({
  baseURL: `${baseURL}/${apiPath}`,
  middlewares: [
    (instance) => {
      // some code
    }
  ]
})
        
auth?(authData):RequestOptions undefined Allows to attach auth mixin for requests in your kinka instance.
It mixin will be modify your request options before sending request.
Example:

const api = kinka.create({
  baseURL: `${baseURL}/${apiPath}`,
  auth: ({ username, password }) => ({
    headers: {
      Auth: `Token ${username}:${stringToSHA256(password)}`,
    },
  }),
})
api.get('/data', {
  auth: { username: 'TheFlash', password: 'SpeedF0rce' },
})
        
credentials?: bool false Indicates that this request should use credentials
(like cookies or specific auth headers)
Sets flag withCredentials
Read more about it here...
# Examples ```js import kinka from 'kinka' kinka.get('https://test-api.com/users').then(response => { // GET: https://test-api.com/users if (!response.err) { console.log(response.data) } }) ``` ```js import kinka from 'kinka' const api = kinka.create({ baseURL: 'https://test-api.com' }) api.get('/users').then(response => { // GET: https://test-api.com/users if (!response.err) { console.log(response.data) } }) ``` ```js import kinka from 'kinka' const api = kinka.create({ baseURL: 'https://test-api.com' }) api .post( '/users', { firstName: 'David', lastName: 'Bowie', }, { query: { as: 'admin' }, } ) .then(({ err, isSuccess, data }) => { // POST: https://test-api.com/users if (!err && isSuccess) { // err = undefined, isSuccess = true console.log(data) // response data } }) ``` ```js import kinka from 'kinka' const api = kinka.create({ baseURL: 'https://test-api.com' }) const getUsers = () => api.get('/users', { query: { queryParam1: 1, queryParam2: 'test', queryParam3: false, }, cancelToken: 'usersAbortableKey', headers: { 'Specific-Header': 'some header data', }, }) const test = async () => { const users = await api.all([getUsers(), getUsers(), getUsers()]) // all requests will be GET: https://test-api.com/users?queryParam1=1&queryParam2=test&queryParam3=false // first and second requests has been catched because for each one specified same param 'cancelToken' if (users[0].err && users[1].err && !users[2].err) { const data = users[2].data console.log('data', data) } } test() ```