Skip to content

safe-std/fetch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

A light fetch wrapper that returns errors as values.

Fetch API

import * as fetcher from '@safe-std/fetch';
import * as st from '@safe-std/error';

// Return errors as values
const res = await fetcher.query('http://localhost:3000', {
  ...
});
if (st.isErr(res)) {
  // Unwrap thrown errors
  const nativeErr = st.payload(res);

  // Error names are fully typed
  switch (nativeErr.name) {
    case 'AbortError': ...;
    case 'NotAllowedError': ...;
    case 'TypeErr': ...;
  }
} else {
  res; // Response
}

// Fetch shorthand for methods
fetcher.get(...);
fetcher.post(...);
fetcher.put(...);
fetcher.del(...);
fetcher.patch(...);

Body parsing API

...
if (st.isErr(res)) {
  ...
} else {
  // Parse body as text
  const body = await fetcher.text(res);

  // Parse body as JSON
  const body = await fetcher.json(res);

  // Parse body as UInt8Array
  const body = await fetcher.bytes(res);

  // Parse body as ArrayBuffer
  const body = await fetcher.buffer(res);

  // Parse body as FormData
  const body = await fetcher.form(res);

  // Parse body as Blob
  const body = await fetcher.blob(res);
}

About

Fetch with type safe errors

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published