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

sleek-networking

v0.5.2

Published

A simple package to handle networking, cache, offline ?, etc

Downloads

2

Readme

Sleek Networking, 🚀

npm version dependencies status Build Status

A simple and efficient fetch wrapper that works across any Javascript (React/React Native/Vue JS, etc) app. It provides you with a clean and consistent way to call your Api, meanwhile handling JWT authentication, middlewares, etc.

Features

  • JWT authentication
  • Transparent absolute or relative url handling
  • Request retry
  • Middlewares
  • Custom headers functions

Install

npm install --save sleek-networking

or

yarn add sleek-networking

Api wrapper

In order to use the Api across your app, you need to instantiate it with your configuration. Here are the params you may pass to it :

import { Api, Jwt } from "sleek-networking";

const api = new Api({
  scheme: "http",
  retriesCount: 0,
  timeout: 1000,
  baseUrl: "google.fr/api/v1",
  afterEach: [request => {}],
  onError: [error => {}],
  headers: {
    "content-type": "Application/JSON",
    "X-Auth-Token": () => new Jwt("1234").generateToken()
  }
});

Usage

api.get("posts", options);
api.post("posts", body, options);
api.put("posts", body, options);
api.delete("posts", options);

api.get("posts").then(res => console.log(res));
/* 
Every request returns an object containing this format :
{ status: 200, body: { parsed: "JSON" }, header }
*/

By default, sleek-networking will assume you want to deal with JSON only. If you query a JSON endpoint, no need to parse it afterwards. If your Api returns something different from readable JSON, it will be returned as raw text.

If you want to send something different from Json, for example form data, you need to do the following :

const formData = new FormData();
formData.append("key", "value");

api.post("yourendpoint", formData, {
  headers: [("Content-Type": "multipart/form-data; boundary=----yourboundary")]
});

Providing JWT Header

With Sleek Networking it becomes easy to add JWT auth to your entire app. Simply import Jwt, provide your secret,

import { Jwt } from "sleek-networking";

new Jwt(secret, optionalPayload, optionalHeader).generateToken(optionalPayload);

Retrying fetch request

In case your request fails (timeout or no network), you can provide a retriesCount option to your config, and also to a single request configuration like that :

api.get("posts", { retriesCount: 5 });

Middlewares

You can execute code after executing a request and before returning it to your app. In order to do so, provide your config with a list of afterEach: [() => {}] functions to execute.

Example use case, disconnecting a user after any 401 received

new Api({
  ...restOfConfigOptions,
  afterEach: [verifyAuthentication, doSomethingElse]
});

function verifyAuthentication(response) {
  if (response.status === 401) user.logout();
}

Custom header function

In case you need to execute a function to add a header to any HTTP request, you may provide a function to your header configuration.

For example that allows you to use any kind of authentication library (in case your do not like the included JWT 😁).

new Api({
  ...restOfConfigOptions,
  headers: {
    "Content-Type": "Application/JSON",
    "Custom-Request-Signature": request => functionToCallEverytime(),
    "X-Auth-Token": request => new Jwt("1234").generateToken()
  }
});

If you need to visualize the request informations when processing your custom header function, you have a complete access to the Request object.

For example, say you need to add the HTTP method to the JWT payload, you can proceed like that :

'X-Auth-Token': request => new Jwt('1234').generateToken({ method: request.method }),
});

You can access anything related to the current Request including :

  • request.url
  • request.path
  • request.method
  • request.body
  • request.options which is an object containing headers and other fetch/api options

Response handling

Instead of returning the default fetch response which contains only status and hard to access body informations, it returns a formatted response.

| Methods | Description | Returns | | --------------- | -------------------------------------------------------------------------------------------- | ----------------- | | succeeded | Check if status is between 200 and 300 and if there is no error. | boolean | | bodyIfSucceeded | Return the body of the request if the status is between 200 and 300 else return false. | body or false | | bodyOrThrow | Return the body of the request if the status is between 200 and 300 else throw a error. | body or throw | | didNetworkFail | If the network request failed, return true or false | boolean | | didServerFail | Tell you if you get error from the server. | boolean |

Contribute

Please add consistent testing when contributing. Run tests with npm test.