npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@sifrr/fetch

v0.0.9

Published

Fetch based http requests library for browsers.

Downloads

23

Readme

sifrr-fetch · npm version Doscify

Fetch API and websockets API based small, easy to use, promise based requests library for browsers.

Size

| Type | Size | | :--------------------------------------------- | :------------------------------------------------------: | | Minified (dist/sifrr.fetch.min.js) | | | Minified + Gzipped (dist/sifrr.fetch.min.js) | |

How to use

Directly in Browser using standalone distribution

Add script tag in your website.

<script src="https://unpkg.com/@sifrr/fetch@{version}/dist/sifrr.fetch.min.js"></script>

Browser API support needed for

| APIs | caniuse | polyfills | | :----------- | :----------------------------------- | :-------------------------------------------- | | Fetch API | https://caniuse.com/#feat=fetch | https://github.com/github/fetch | | Promises API | https://caniuse.com/#feat=promises | https://github.com/stefanpenner/es6-promise |

Using npm

Do npm i @sifrr/fetch or yarn add @sifrr/fetch or add the package to your package.json file.

example, put in your frontend js module (compatible with webpack/rollup/etc):

Commonjs

window.Sifrr = window.Sifrr || {};
window.Sifrr.Fetch = require('@sifrr/fetch');

ES modules

import Fetch from '@sifrr/fetch';
// or
import { Fetch, Socket } from '@sifrr/fetch';
// and use as Sifrr.Fetch or Sifrr.Fetch.Socket

With node

// set global.fetch
global.fetch = require('node-fetch);
const { Fetch } = require('@sifrr/fetch');
// use SFetch.get, post etc,
global.WebSocket = require('isomorphic-ws');
const { Socket } = require('@sifrr/fetch');

Note: You can not use websockets with node

API

HTTP Requests

options are Fetch API options with some extra keys:

  • params json object key, value pairs will be added to url as ?key=value
  • body json object | string body to send with post requests
  • onProgress function if response has content-length, this function will be called with
{
  loaded, // loaded bytes
  total, // total bytes (0 if response doesn't have content length)
  percent, // progress precentage
  speed, // speed in kbps
  value,
  ... // chunk value
}
  • timeout time in ms timeout for request
  • before function this function will be called with { url, options, method } and should return modified { url, options, method } which will be used to send requests
  • after function this function will be called with response and should return modified response
  • use function this function will be called with { url, options, method } and resolve/return with response which will be returned, if this function errors, response will be fetched normally (use case: use it as a middleware for cache)

GET request

you can add query parameters to get request options.

options.query = { key: 'value' };
Sifrr.Fetch.get(url, options)
  .then(response => {
    // This will send request to url?key=value
    // response is JSON if response has `content-type: application/json` header
    // else it is a Fetch API response object.
  })
  .catch(e => {
    // handle error, same for other type of requests
  });

PUT request

Sifrr.Fetch.put(url, options).then(response => {
  // response is JSON if response has `content-type: application/json` header
  // else it is a Fetch API response object.
});

POST request

you can add post request body parameters to post request options.

options.body = { key: 'value' };
options.headers = {
  'content-type': 'aaplication/json'
};
Sifrr.Fetch.post(url, options).then(response => {
  // response is JSON if response has `content-type: application/json` header
  // else it is a Fetch API response object.
});

DELETE request

Sifrr.Fetch.delete(url, options).then(response => {
  // response is JSON if response has `content-type: application/json` header
  // else it is a Fetch API response object.
});

GET file request

Sifrr.Fetch.file(url, options).then(response => {
  // response is a Fetch API response object.
  // You can get file text content using response.text() or other fetch response methods
});

GRAPHQL request

graphql request is a POST request.

Sifrr.Fetch.graphql(url, {
  query: 'graphql query string',
  variables: { a: 'b' },
  ...otherOptions
}).then(response => {
  // response is JSON if response has `content-type: application/json` header
  // else it is a Fetch API response object.
});

Cache as Middleware

const storage = new Sifrr.Storage();
function cacheOrGet(url) {
  Sifrr.Fetch.get(url, {
    use: url =>
      storage.get(url).then(v => (typeof v[url] === 'undefined' ? throw 'Not found' : v[url])),
    after: response => {
      storage.set(url, response);
      return response;
    }
  });
}

Instance with default options

const fetch = new Sifrr.Fetch(defaultOptions);

// then use
fetch.get;
fetch.put;
fetch.post;
fetch.delete;
fetch.graphql;

WebSockets

Automatic connection retries, calls fallback on message sending failure/error

WebSocket fetch

Note: Only works with JSON messages/responses

// Open a socket
const socket = new Sifrr.Fetch.Socket(url, protocols, fallback /* (message) => 'fallback response' */);
// send a message
socket.send(message [, type]).then(resp => {
  // do something
});

// Server will receive data as:
// {
//   id: Int,
//   type: type, (default: 'sifrr-fetch')
//   payload: message
// },
// and should send back
// {
//   id: same id as received
//   payload: response
// }
// then resp will be equal to response sent above
//
// If socket connection fails
// It will call fallback function with message and resolves with its return value

Graphql query over websocket (compatible with sifrr-server)

socket.graphql({
  query: ...,
  variables: ...
}).then(data => {
  // do something with data
});

Graphql Subscriptions (compatible with graphql-subscription-ws and sifrr-server)

let subscriptionId;
// subscribe
socket.subscribe({ query: `subscription { ... }`, variables: { ... } }, callback).then(id => subscriptionId = id);
// callback will be called with every data received from server

// unsubscribe
socket.unsubscribe(subscriptionId).then(...);

Traditional WebSocket messaging

// Open a socket
const socket = new Sifrr.Fetch.Socket(
  url,
  protocols,
  fallback /* (message) => 'fallback response' */
);
// send a message
socket.sendRaw(message);

Hooks

// same as websocket's hooks
socket.onmessage = event => {};
socker.onopen = () => {};
socker.onclose = () => {};
socker.onerror = e => {};

References