Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

fetchmap

Package Overview
Dependencies
Maintainers
1
Versions
26
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fetchmap

Non-throwing fetch wrapper

  • 0.0.20
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
5
increased by400%
Maintainers
1
Weekly downloads
 
Created
Source

fetchmap

npm build publish codecov Type Coverage Libraries.io dependency status for latest release Bundlephobia npm

Non-throwing fetch wrapper

Getting started

npm i fetchmap

Description

This is a simple wrapper for a fetch-like function that catches all possible exceptions and returns a 'success or failure' wrapped value. It takes an object to map response.status to <T, U>(body: U, response: Response) => T transform and standard fetch arguments.

Example

// server code
import express from 'express'

express()
  .get('/json', (_, res) => {
    res.json({ some: 'data' })
  })
  .listen(5005)

// client code
import { createFetchmap } from 'fetchmap'
import fetch from 'node-fetch'

const success = <T>(value: T) => ({ tag: 'success', success: value } as const)

const fetchmap = createFetchmap(fetch)

const mock_data_validator = (data: unknown) => success(data)

const json_success = await fetchmap(
  { ok: { json: mock_data_validator } },
  'https://localhost:5005/json'
)
expect(json_success).toEqual({ tag: 'success', success: { some: 'data' } })

const json_success_only_200 = await fetchmap(
  { 200: mock_data_validator },
  'https://localhost:5005/json'
)
expect(json_success_only_200).toEqual({ tag: 'success', success: { some: 'data' } })

const invalid_url_failure = await fetchmap({}, '1234')
expect(invalid_url_failure).toEqual({
  tag: 'failure',
  failure: { clientError: new TypeError('Only absolute URLs are supported') }
})

const not_found_error_with_request_init = await fetchmap(
  { notOk: ({ status }) => status },
  'https://localhost:5005/invalid',
  { method: 'POST', credentials: 'include' }
)
expect(not_found_error_with_request_init).toEqual({ tag: 'failure', failure: { serverError: 404 } })

Usage

See test or playground

Misc

ts-railway - compatible result library

Keywords

FAQs

Package last updated on 25 May 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc