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 API wrapper

  • 0.1.2
  • latest
  • 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 API 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 that maps response.status to validating transform and standard fetch arguments.

Read the docs here and check how fetchmap infers types at the playground. Also there is a compatible result library - ts-railway.

Example

Server code:

import express from 'express'

express()
  .get('/data', (_, res) => {
    const rnd = Math.random()

    if (rnd < 0.34) {
      res.status(200).json({ some: 'data' })
    } else if (rnd < 0.67) {
      res.status(201).send('This is not JSON!')
    } else {
      res.status(500).send('Server error!')
    }
  })
  .listen(5005)

Client code:

import { createFetchmap } from 'fetchmap'
import nodeFetch, { Response } from 'node-fetch'
import { isRecord } from 'ts-is-record'

// fetchmap compatible result creators
const success = <T>(value: T) => ({ tag: 'success', success: value } as const)
const failure = <T>(error: T) => ({ tag: 'failure', failure: error } as const)

// wrap any fetch-like function
const fetchmap = createFetchmap(nodeFetch)

// data is expected to be JSON, so it has to be validated
const validateData = (body: unknown) =>
  isRecord(body) && 'some' in body && typeof body.some === 'string'
    ? success(body)
    : failure('data validation failed' as const)

// error is just a string, in this example no validation needed
const validateError = (body: string, { status }: Response) => success({ message: body, status })

const dataResult = await fetchmap(
  {
    // for any response with a status inside inclusive range 200..299
    // call 'json' method and validate its result with `validateData` function
    ok: { json: validateData },

    // for any response with a status outside inclusive range 200..299
    // call 'text' method and validate its result with `validateError` function
    notOk: { text: validateError }
  },

  // first argument for a wrapped fetch function
  'https://localhost:5005/data',

  // second argument for a wrapped fetch function
  {
    // request options: method, headers, body etc.
  }
)

expect([
  { tag: 'success', success: { some: 'data' } },
  { tag: 'failure', failure: { serverError: { message: 'Server error!', status: 500 } } },
  {
    tag: 'failure',
    failure: { mapError: new SyntaxError('Unexpected token T in JSON at position 0') }
  }
]).toContainEqual(dataResult)

Keywords

FAQs

Package last updated on 12 Jun 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