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

fetchum

v5.2.0

Published

A better fetch and local storage system

Downloads

167

Readme

Fetchum

Downloads Downloads NPM Version Dependencies Dev Dependencies License

A better fetch api

The main bulk of the local storage wrapper has been moved out into betterstorage. The token related methods still exist but are now promise based.

Install

npm i -S fetchum

yarn add fetchum

Setup

<script>
  window.FETCHUM_BASE = 'localhost:3000/api';
  window.FETCHUM_PREFIX = '@my-app';
</script>

For use Node side set env vars ie:

process.env.FETCHUM_BASE = 'localhost:3000/api';
process.env.FETCHUM_PREFIX = '@my-app';

For universal set both.

import fetchum from 'fetchum';

fetchum.setConfig('/api/', '@app-prefix');

Api - generateRequest

generateRequest returns a function to call that will make a request based on set options.

Options

  • method : http verb
  • route : url string
  • headers : object for default request headers (default: {})
  • form : boolean if submit as form data (default: false)
  • token : boolean if set Auth header from local storage token (default: false)
  • external : boolean if should not prepend route with api base (default: false)

Function Params

  • params : json object matching keys for parameterized routes ie: /user/:id
  • body : json request body/url params
  • headers : json request headers
  • customToken : !Only if external option is false
  • tokenType : !Only if external option is false. Default Bearer.

Examples

import fetchum from 'fetchum';

const getRandomUser = fetchum.generateRequest({
  method: 'GET',
  external: true,
  route: 'http://uifaces.com/api/v1/random',
});

Create and update a user with profile image on a authenticated api

import fetchum from 'fetchum';

const postUser = fetchum.generateRequest({
  method: 'POST',
  form: true,
  token: true,
  route: '/v1/user',
});

const putUser = fetchum.generateRequest({
  method: 'PUT',
  form: true,
  token: true,
  route: '/v1/user/:id',
});

const createUser = (data) => {
  postUser({}, data)
    .then((res) => { console.log('created', res.data); })
    .catch((res) => { console.warn(res); });
};

const updateUser = (id, data) => {
  putUser({id}, data)
    .then((res) => { console.log('updated', res.data); })
    .catch((res) => { console.warn(res); });
};

Api - generateCRUDRequests

Like generateRequest generateCRUDRequests will generate request structure but it does more returning a object with all the basic crud actions.

Function Params

  • baseUrl : url string to base crud actions off ie: /user
  • idVar : the var name of the id url param id the :id in /user/:id. The : should not be passed.
  • Defualt - 'id'
  • useToken : if the routes should have the token option set.
  • Defualt - false

Examples

import fetchum from 'fetchum';

const userApi = fetchum.generateCRUDRequests('/users', 'id', true);

userApi.fetchOne({ id: 0 })
  .then((res) => {
    this.user = res.data.user;
  });

Returned Requests

  • fetchAll - GET to base url
  • create - POST to base url
  • fetchOne - GET to base url and added id Var ie: /users/:id
  • update - PUT to base url and added id Var ie: /users/:id
  • delete - DELETE to base url and added id Var ie: /users/:id

Api - LocalStorage

Fetchum has a build in LocalStorage wrapper for convenience and for the specific use of getting the auth token.

To use the token option in the generateRequest call you will need to use this LocalStorage wrapper;

Methods

  • set - sets var in storage ie LocalStorage.set('varName', varValue)
  • get - gets a var value from storage ie: const varValue = LocalStorage.set('varName')
  • remove - removes a var from storage
  • isSet - returns boolean for if a var is in storage
  • setToken - sets a token in storage used by requests
  • getToken - gets a token from storage
  • removeToken - removes a token from storage

Examples

import {LocalStorage} from 'fetchum';

const setToken = (token) => {
  LocalStorage.set('token', token);
};

Login and out example

import fetchum from 'fetchum';

const apiLogin = fetchum.generateRequest({
  method: 'POST',
  route: '/v1/login',
});

const login = (data) => {
  apiLogin(data)
    .then((res) => {
      fetchum.LocalStorage.setToken(res.data.token);
      fetchum.LocalStorage.set('user', res.data.user);
    })
    .catch((res) => { console.warn(res); });
};

const getCurrentUser = () => {
  return fetchum.LocalStorage.get('user');
};

const logout = () => {
  fetchum.LocalStorage.remove('user');
  fetchum.LocalStorage.removeToken();
};

Random Usage Examples

import fetchum from 'fetchum';

/**
 * API Calls
 *
 */
export default {
  login: fetchum.generateRequest({
    method: 'POST',
    route: '/v1/login',
  }),
  user: {
    getAll: fetchum.generateRequest({
      method: 'GET',
      token: true,
      route: '/v1/users',
    }),
    show: fetchum.generateRequest({
      method: 'GET',
      token: true,
      route: '/v1/users/:id',
    }),
    update: fetchum.generateRequest({
      method: 'PUT',
      token: true,
      route: '/v1/users/:id',
    }),
    remove: fetchum.generateRequest({
      method: 'DELETE',
      token: true,
      route: '/v1/users/:id',
    }),
    create: fetchum.generateRequest({
      method: 'POST',
      token: true,
      route: '/v1/users',
    }),
  }
};
import { apiRequests } from 'fetchum';

const getUsersDirect = () => {
  apiRequests.get('/v1/users')
    .then((res) => { console.log('my users', res.data); })
    .catch((res, err) => { console.warn(res); });
};

Api request - methods

/**
 * Generate a api request
 * @param  {Object} options - {method, token, route, external, form, headers}
 *
 */
generateRequest

/**
 * Generate a crud api requests
 * @param  {Object} baseUrl
 * @param  {Object} idVar
 * @param  {Object} useToken
 *
 */
generateCRUDRequests

/**
 * Base request call
 * @param  {Boolean} isFormData
 * @param  {String} method
 * @param  {String} url
 * @param  {JSON} body
 * @param  {Object} headers
 * @param  {Object} otherConfig
 *
 */
request

/**
 * Basic http requests
 * @param  {String} url
 * @param  {JSON} body
 * @param  {Object} headers
 * @param  {Object} otherConfig
 *
 */
requests.get, requests.put, requests.post, requests.patch, requests.delete

/**
 * Form requests - the body JSON is converted into FormData
 * @param  {String} url
 * @param  {JSON} body
 * @param  {Object} headers
 * @param  {Object} otherConfig
 *
 */
requests.putForm, requests.postForm

/**
 * Calls the request and prepends route with api base
 * @param  {Boolean} isFormData
 * @param  {String} method
 * @param  {String} url
 * @param  {JSON} body
 * @param  {Object} headers
 * @param  {Object} otherConfig
 *
 */
apiRequest

/**
 * Basic http requests that prepend route with api base
 * @param  {String} url
 * @param  {JSON} body
 * @param  {Object} headers
 * @param  {Object} otherConfig
 *
 */
apiRequests.get, apiRequests.put, apiRequests.post, apiRequests.patch, apiRequests.delete

/**
 * API Form requests - the body JSON is converted into FormData
 * @param  {String} url
 * @param  {JSON} body
 * @param  {Object} headers
 * @param  {Object} otherConfig
 *
 */
apiRequests.putForm, apiRequests.postForm