• Stars
    star
    282
  • Rank 146,549 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A library that makes the Fetch API a breeze

zlFetch

zlFetch is a wrapper around fetch that provides you with a convenient way to make requests.

It's features are as follows:

Note: zlFetch is a ESM library since v4.0.0.

Installing zlFetch

Through npm (recommended)

# Installing through npm
npm install zl-fetch --save

Then you can use it by importing it in your JavaScript file.

import zlFetch from 'zl-fetch'

Using zlFetch without npm:

You can import zlFetch directly into JavaScript through a CDN.

To do this, you first need to set your script's type to module, then import zlFetch.

<script type="module">
  import zlFetch from 'https://cdn.jsdelivr.net/npm/[email protected]/src/index.js'
</script>

Quick Start

You can use zlFetch just like a normal fetch function. The only difference is you don't have to write a response.json or response.text method anymore!

zlFetch handles it for you automatically so you can go straight to using your response.

zlFetch('url')
  .then(response => console.log(response))
  .catch(error => console.log(error))

Shorthand methods for GET, POST, PUT, PATCH, and DELETE

zlFetch contains shorthand methods for these common REST methods so you can use them quickly.

zlFetch.get(/* some-url */)
zlFetch.post(/* some-url */)
zlFetch.put(/* some-url */)
zlFetch.patch(/* some-url */)
zlFetch.delete(/* some-url */)

Supported response types

zlFetch supports json, text, and blob response types so you don't have to write response.json(), response.text() or response.blob().

Other response types are not supported right now. If you need to support other response types, consider using your own response handler

The response contains all the data you may need

zlFetch sends you all the data you need in the response object. This includes the following:

  • headers: response headers
  • body: response body
  • status: response status
  • statusText: response status text
  • response: original response from Fetch

We do this so you don't have to fish out the headers, status, statusText or even the rest of the response object by yourself.

Debugging the request

New in v4.0.0: You can debug the request object by adding a debug option. This will reveal a debug object that contains the request being constructed.

  • url
  • method
  • headers
  • body
zlFetch('url', { debug: true })
  .then({ debug } => console.log(debug))

Error Handling

zlFetch directs all 400 and 500 errors to the catch method. Errors contain the same information as a response.

  • headers: response headers
  • body: response body
  • status: response status
  • statusText: response status text
  • response: original response from fetch

This makes is zlFetch super easy to use with promises.

zlFetch('some-url').catch(error => {
  /* Handle error */
})

// The above request can be written in Fetch like this:
fetch('some-url')
  .then(response => {
    if (!response.ok) {
      Promise.reject(response.json)
    }
  })
  .catch(error => {
    /* Handle error */
  })

Easy error handling when using async/await

zlFetch lets you pass all errors into an errors object. You can do this by adding a returnError option. This is useful when you work a lot with async/await.

const { response, error } = await zlFetch('some-url', { returnError: true })

Helpful Features

Query string helpers

You can add query or queries as an option and zlFetch will create a query string for you automatically. Use this with GET requests.

zlFetch('some-url', {
  queries: {
    param1: 'value1',
    param2: 'to encode',
  },
})

// The above request can be written in Fetch like this:
fetch('url?param1=value1&param2=to%20encode')

Content-Type generation based on body content

zlFetch sets Content-Type appropriately depending on your body data. It supports three kinds of data:

  • Object
  • Query Strings
  • Form Data

If you pass in an object, zlFetch will set Content-Type to application/json. It will also JSON.stringify your body so you don't have to do it yourself.

zlFetch.post('some-url', {
  body: { message: 'Good game' },
})

// The above request is equivalent to this
fetch('some-url', {
  method: 'post',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ message: 'Good game' }),
})

zlFetch contains a toObject helper that lets you convert Form Data into an object. This makes it super easy to zlFetch with forms.

import { toObject } from 'zl-fetch'
const data = new FormData(form.elements)

zlFetch('some-url', {
  body: toObject(data),
})

If you pass in a string, zlFetch will set Content-Type to application/x-www-form-urlencoded.

zlFetch also contains a toQueryString method that can help you convert objects to query strings so you can use this option easily.

import { toQueryString } from 'zl-fetch'

zlFetch.post('some-url', {
  body: toQueryString({ message: 'Good game' }),
})

// The above request is equivalent to this
fetch('some-url', {
  method: 'post',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: 'message=Good%20game',
})

If you pass in a Form Data, zlFetch will let the native fetch function handle the Content-Type. Generally, this will use multipart/form-data with the default options. If you use this, make sure your server can receive multipart/form-data!

import { toObject } from 'zl-fetch'
const data = new FormData(form.elements)

zlFetch('some-url', { body: data })

// The above request is equivalent to this
fetch('some-url', { body: data })

// Your server should be able to receive multipart/form-data if you do this. If you're using Express, you can a middleware like multer to make this possible:
import multer from 'multer'
const upload = multer()
app.use(upload.array())

Breaking Change in v5.0.0: If you pass in a Content-Type header, zlFetch will not set format your body content anymore. We expect you to be able to pass in the correct data type. (We had to do this to support the new API mentioned above).

Authorization header helpers

If you provide zlFetch with an auth property, it will generate an Authorization Header for you.

If you pass in a string (commonly for tokens) , it will generate a Bearer Auth.

zlFetch('some-url', { auth: 'token12345' })

// The above request can be written in Fetch like this:
fetch('some-url', {
  headers: { Authorization: `Bearer token12345` },
})

If you pass in an object, zlFetch will generate a Basic Auth for you.

zlFetch('some-url', {
  auth: {
    username: 'username'
    password: '12345678'
  }
})

// The above request can be written in Fetch like this:
fetch('some-url', {
  headers: { Authorization: `Basic ${btoa('username:12345678')}` }
});

Creating a zlFetch Instance

You can create an instance of zlFetch with predefined options. This is super helpful if you need to send requests with similar options or url.

  • url is required
  • options is optional
import { createZLFetch } from 'zl-fetch'

// Creating the instance
const api = zlFetch(baseUrl, options)

All instances have shorthand methods as well.

// Shorthand methods
const response = api.get(/* ... */)
const response = api.post(/* ... */)
const response = api.put(/* ... */)
const response = api.patch(/* ... */)
const response = api.delete(/* ... */)

New in v5.0.0

You can now use a zlFetch instance without passing a URL. This is useful if you have created an instance with the right endpoints.

import { createZLFetch } from 'zl-fetch'

// Creating the instance
const api = zlFetch(baseUrl, options)

All instances have shorthand methods as well.

// Shorthand methods
const response = api.get() // Without URL, without options
const response = api.get('some-url') // With URL, without options
const response = api.post('some-url', { body: 'message=good+game' }) // With URL, with options
const response = api.post({ body: 'message=good+game' }) // Without URL, with options

Custom response handler

If you want to handle a response not supported by zlFetch, you can pass customResponseParser: true into the options. This returns the response from a normal Fetch request without any additional treatments from zlFetch. You can then use response.json() or other methods as you deem fit.

const response = await zlFetch('url', {
  customResponseParser: true,
})
const data = await response.arrayBuffer()

More Repositories

1

typi

A sass mixin to make responsive typography easy
CSS
857
star
2

gulp-starter-csstricks

Gulp starter for CSS Tricks article
JavaScript
392
star
3

mappy-breakpoints

Breakpoints with Maps in Sass
SCSS
383
star
4

zellwk.com

Github repo for https://zellwk.com
MDX
348
star
5

crud-express-mongo

Repo for Zell's CRUD, Express and Mongo tutorial
JavaScript
176
star
6

dotfiles

Shell
172
star
7

crud-demo

Source code for "Building a CRUD app with Node, Express, and MongoDB tutorial"
JavaScript
165
star
8

javascript

A collection of useful JavaScript snippets curated by Zell
JavaScript
160
star
9

css-reset

Zell's personal CSS Reset
CSS
148
star
10

adaptive-placeholders

Float label pattern built with pure SCSS
CSS
129
star
11

endpoint-testing-example

JavaScript
47
star
12

gulp-susy-starter

Susy Starter that uses LibSass with Gulp
CSS
39
star
13

themify

Sass Mixin to create multiple themes easily
CSS
34
star
14

vertical-rhythms-without-compass

CSS
18
star
15

stripe-astro-recipe

Astro
13
star
16

build-and-deploy-workshop

Astro
10
star
17

ama

A repository where you can ask anything and Zell will answer.
9
star
18

source-for-automating-workflow-book

JavaScript
9
star
19

grunt-susy-starter

Susy Starter that uses LibSass with Grunt
CSS
8
star
20

devfest

github repo for the devfest.asia 2015
JavaScript
7
star
21

Learnjavascript-api

API for Learn JavaScript
JavaScript
6
star
22

convertkit-cli

A Simple CLI for Convertkit
JavaScript
6
star
23

CSSConf.Asia-animating-svg

JavaScript
6
star
24

demos

JavaScript
5
star
25

responsive-typography-slides

JavaScript
5
star
26

responsive-css-components-slides

JavaScript
5
star
27

devfest-2016

CSS
4
star
28

webpack-starter

Webpack starter (without React)
JavaScript
4
star
29

better-share-buttons

CSS
4
star
30

buffalo

Simple Blog site generator
JavaScript
4
star
31

Learning-Susy

The walkthrough codes for Learning Susy
CSS
3
star
32

simple-workflow

HTML
3
star
33

responsive-typography-workshop

CSS
3
star
34

FEWD

HTML
3
star
35

basic-susy-starter

A very simple Susy Starter that uses the terminal to compile Sass into CSS
CSS
3
star
36

learngit.io

Website for learngit.io
HTML
3
star
37

ava-mdb-test

JavaScript
2
star
38

Dojo-Playground

Astro
2
star
39

countdown

A simple countdown timer to a specific date (with timezone support)
JavaScript
2
star
40

susy-helpers

Helpers for Susy
CSS
2
star
41

scalable-components

JavaScript
2
star
42

simple-susy-starter

For easy Susy related layouts / tests
CSS
2
star
43

shuffle-and-split

Shuffles and splits and array into equal groups
JavaScript
2
star
44

publishing-to-npm

An example repository to teach people how to publish to npm
2
star
45

resize-images

Resizes images. Suitable for use directly in Node, or with a Gulp workflow
JavaScript
2
star
46

ayw

Website for AYW
Nunjucks
1
star
47

build-and-deploy-workshop-sanity

JavaScript
1
star
48

chatapp-polymer

Chatapp built with Polymer
HTML
1
star
49

roam-css

CSS
1
star
50

astro-integration-learning

JavaScript
1
star
51

cssnano-issue

JavaScript
1
star
52

devops

1
star
53

slides-scaling-components-cn

Slides for CSSConf China #4
JavaScript
1
star
54

compass-susy-starter

A very simple Susy Starter that uses Compass to compile Sass into CSS
CSS
1
star
55

jsroadmap.com

SCSS
1
star
56

zellwk-pdf-maker

Helps to make PDFs for https://zellwk.com
JavaScript
1
star
57

github-actions-tutorial

1
star
58

count-to-date

A simple countdown timer to a specific date
JavaScript
1
star
59

cohort19x

CSS
1
star
60

window-sizer

Small helper to make debugging responsive websites easier
JavaScript
1
star
61

crop-image-whitespace

JavaScript
1
star