0.0.1 • Published 4 years ago

myfatch v0.0.1

Weekly downloads
1
License
MIT
Repository
github
Last release
4 years ago

myfatch

Alternative javascript fetch api, you can presetup options and headers to create a request.

Installation

This is library available through npm registry.

npm install --save myfatch

Setup

Lets setup your options and headers for fetch request.

import * as myfatch from 'myfatch'

myfatch.setup({
  origin: 'https://example.com/api',
  options: {
    mode: 'cors'
  },
  headers: {
    'Accept-Type': 'application/json'
  }
})

The setup() method can accept one setting parameter with contain below settings.

NameTypeDescription
origin{String}Where a fetch request will be send, the origin is prefix for all send request.
options{Object}The root options of fetch api like mode, cache, etc.
headers{Object}Headers options.

Send request method

get()

Send request with method GET.

myfatch.get('users')
  .then(res => {
    console.log(res.ok)
  })

postData()

Send request with method POST. Automaticaly add headers Content-Type with value application/x-www-form-urlencoded and transform body object into form data.

myfatch.postData('login', {
  body: {
    username: 'username',
    password: 'password'
  }
})
  .then(res => {
    console.log(res.ok)
  })

uploadData()

Send request with method POST. Automaticaly add headers Content-Type with value multipart/form-data and transform body object into form data.

const fileField = document.querySelector('input[type="file"]');

myfatch.uploadData('user/profile', {
  body: {
    photo: fileField.files[0]
  }
})
  .then(res => {
    console.log(res.ok)
  })

postJSON()

Send request with method POST. Automaticaly add headers Content-Type with value application/json and transform body object into json data.

myfatch.postJSON('user/profile', {
  body: {
    first_name: 'FirstName',
    last_name: 'LastName'
  }
})
  .then(res => {
    console.log(res.ok)
  })

Parameters

All request method can accept two parameter.

NameTypeDescription
url{String}The path of request url.
setting{Object}Contain fetch setting.

PUT & DELETE

Same with GET and POST you can use PUT and DELETE method with similliar parameter with putData(), putJSON(), deleteData(), deleteJSON().