@devecorsoft/fetch-intercept
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

fetch-intercept

Statements Branches Functions Lines

add interceptors to fetch api without any hack in to window.fetch

Usage

Request interceptors

authorization interceptor

import {
  fetchFactory
} from "@devecorsoft/fetch-intercept"

describe('authorization interceptor', () => {
  it('should add authorization', async () => {
    const expectation = nock('http://localhost')
      .get('/path/to/resources')
      .matchHeader('Authorization', 'Bearer the-jwt-token')
      .reply(200, {id: 'resource id'})

    const fetch = fetchFactory().intercepts.interceptRequest((input, init) => {
      init = init ?? {}
      init.headers = new Headers()
      init.headers.append('Authorization', 'Bearer the-jwt-token')
      return [input, init]
    }).fetch
    await fetch('/path/to/resources')

    expectation.done()
  })
})

Response interceptors

Json body interceptor

import { fetchFactory, jsonBodyInterceptor } from "@devecorsoft/fetch-intercept"

describe('json body interceptor', () => {
  it('should able to extract json body when 200', async () => {
    const expectation = nock('http://localhost')
      .get('/path/to/resources')
      .reply(200, {id: 'resource id'})

    const fetch = fetchFactory().intercepts.interceptResponse(jsonBodyInterceptor).fetch
    const res = await fetch('/path/to/resources')

    expect(res).toEqual({id: 'resource id'})
    expectation.done()
  })

  it('should not error when 500', async () => {
    const expectation = nock('http://localhost')
      .get('/path/to/resources')
      .reply(500)

    const fetch = fetchFactory().intercepts.interceptResponse(jsonBodyInterceptor).fetch
    await fetch('/path/to/resources')

    expectation.done()
  })
})

customize response interceptor

import { fetchFactory, ResponseInterceptor } from "@devecorsoft/fetch-intercept"

describe('custom interceptor', () => {
  it('should able to customize server error interceptor', async () => {
    const expectation = nock('http://localhost')
      .get('/path/to/resources')
      .reply(500)

    const toErrorPageInterceptor: ResponseInterceptor = (response) => {
      if (response.status === 500) {
        location.assign('/error')
      }
      return response
    }
    const fetch = fetchFactory().intercepts.interceptResponse(toErrorPageInterceptor).fetch
    await fetch('/path/to/resources')

    expect(location.pathname).toEqual("/error")
    expectation.done()
  })
})

see tests for more examples.

Package Sidebar

Install

npm i @devecorsoft/fetch-intercept

Weekly Downloads

1

Version

1.0.1

License

MIT

Unpacked Size

7.5 kB

Total Files

5

Last publish

Collaborators

  • devecor