2.0.1 • Published 6 years ago

go-n-fetch v2.0.1

Weekly downloads
1
License
GPL-3.0-or-later
Repository
gitlab
Last release
6 years ago

tested with jest jest

GoFetch

This project is a web request abstraction module that aims to reduce repetition

Installation

  • npm install go-n-fetch --save
  • yarn add go-n-fetch

For older browsers you can use promise-polyfill If you transpile your code be sure to use the corresponding fetch polyfills

Migration from v1 to v2

The usage is the same but for browser you need to change the import from go-n-fetch to go-n-fetch/browser

Usage

Fetch usage is almost exactly the same, you can prefill data and add behavior before and during the fetch request

Pre-filled request parameters

This will provide pre-filled request parameters to every subsequent call

import GoNFetch from 'go-n-fetch/browser'
// Pre-filling header data for authentication purposes
const goNFetch = GoNFetch({
  baseUrl: 'http://blog/api',
  headers: { "my-token": "super-secret-n-serialized-token" },
})

Options are:

  • baseUrl: Prefixes

Method calls

There are pre-filled methods that will ignore the request.method, usage is the same that fetch in every other aspect

GET

const posts = await goNFetch.get(`${url}/posts`).then(response.json())

POST

const newPost = { content: 'Lorem Ipsum', author: 'Dolor sit' }
const posts = await goNFetch.post(`${url}/posts`, { body: JSON.stringify(newPost) })

Supported verbs are:

  • GET
  • POST
  • PUT
  • DELETE
  • PATCH

IMPORTANT: the method parameters comes in UPPERCASE

Middlewares

You can register middlewares that intercept method calls before or after the fetch actual execution.

Provided events:

  • OnBeforeRequest
  • OnFetchFulfilled
  • OnFetchError

You can add middlewares using the register method

import GoNFetch from 'go-n-fetch/browser'
const goNFetch = GoNFetch({
  baseUrl: 'http://blog/api',
  headers: { "content-type": "application/json; charset=utf-8" },
})

// Create a middleware for body to be always stringified and a custom error log
goNFetch.register({
  // Middleware that serializes the body into a JSON string
  OnBeforeRequest: [async (request) => {
    if (request.body && request.method === 'POST' || request.method === 'PUT') {
      request.body = JSON.stringify(request.body)
    }
    return request
  }],
  OnFetchError: [async (error) => console.error(error)]
})

const newPost = { content: 'Lorem Ipsum', author: 'Dolor sit' }
// Every subsecuent call is simplified
const posts = await goNFetch.post('/posts', { body: newPost })

Middlewares are executed per event, in order of registration

Node Compatibilty

For Node implementation you need to install the optional dependency got and invoke it as documented in the library itself.

2.0.1

6 years ago

2.0.0

6 years ago

1.1.5

7 years ago

1.1.4

7 years ago

1.1.2

7 years ago

1.1.1

7 years ago

1.1.0

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago