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

redux-rest-fetcher

v1.3.0

Published

Helper for creating and executing fetch calls that works standalone or can dispatch results to redux store.

Downloads

4

Readme

react-redux-fetcher

This library was made for my personal project. Not all use cases are tested. I welcome testers, sugestions, pull requests etc.

Small library for creating API endpoint calls and other fetch calls. Can be used in any project, but is meant to be used with redux to dispatch results to store.

Small, treeshaked lodash dependency.

Original at: https://github.com/klooperator/redux-rest-fetcher

Install

npm install redux-rest-fetcher --save
yarn add redux-rest-fetcher
bower install redux-rest-fetcher --save

Description & example

This library is influenced by redux-api, but instead od using FLUX architecture it will put all its calls under one named reducer.

Once setup you can create your calls like this:

    calls = {
         login:{
            url: "http://yoursite.com/api/login",
            method: 'post',
            headers:{
                Accept: 'application/json'
                }
         },
         getUser:{
            url: "http://yoursite.com/api/get-user/:id",
           method: 'get',
           headers:{
                Accept: 'application/json'
                }
        },
    }

After that you just make a call like this:

    Api.login({body: logindata});
    Api.getUser({id: userID})

Configuration

To configure it properly you should call an instance of it in you app entry point, right before you create a global store instance.

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import api from 'redux-rest-fetcher';
import apiCalls from './src/api/calls';

//here you can setup basic configuration that will be valid for all calls.
api.setBaseUrl('http://your-restapi-adress.com');
//you can ommit this, but in case you use other fetch (ex. polyfill) you can set it here
api.setFetch(window.fetch);
//also can be ommited, default is 'api(.)(.)'
//you will see this in redux actions: api(.)(.)callName
api.setPrefix('api@@');
//and of course api calls
api.setEndpoints(apiCalls);

At this point redux-rest-fetcher is ready to be passed to your store. Extract reducer from it

const apiReducer = api.getReducer()

and pass it to your store to be incorporated in your combineReducer()

const rootReducer = combineReducer({
	something,
	apiReducer,
	somethingElse
});

Once your store is created and populated with @@INIT, pass a dispatcher to api.

api.setDispatcher(store.dispatch)

Now any time you call you api calls, results will be placed to redux store.

Creating calls

You create your calls as key value object pairs. Where key will be a name of the function you call and value the call options. Yo can create multiple files, for ex. each for specific endpoint of your api

// /calls/User.js
const enpoint = 'user';
export default {
    login:{
        url: `${endpoint}/login`,
        options: {
            method: 'post',
            headers:{
                accept: 'application/json',
                }
            },
    },
    getGender:{
        url: `${endpoint}/gender/:id`,
        options: {
            headers:{
                Accept: "text/html",
                "Content-Type": "text/html;charset=utf-8",
                }
            },
    }
}
...
// calls/server.js
const enpoint = 'server';
export default {
    refresh:{
        url: `${endpoint}/refresh`,
        options: {
            credentials: 'omit',
            headers:{
                accept: 'application/json',

                }
            },
    },
}
...
// calls/index.js
import User from './User';
import Srv from './Server';
const calls = Object.assign({}, User, Srv);
export default calls;

Overrides and more overrides

There are 3 levels of constructing your request. Base options, options inside your calls and per call options.

Firstly you can set base options. If no other options are set this will be used for each call. In next example we will just implement default options ( this are already in there, if you skip this step, those will be your base options)

api.setBaseOptions({
      credentials: "include",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Cache: "no-cache",
        credentials: "same-origin"
      }
    })

Then you can override base options with options in call object.In example for refresh resulting options will be:

{
      credentials: "include",
      headers: {
        Accept: "text/html",
        "Content-Type": "text/html;charset=utf-8",
        Cache: "no-cache",
      }
    }

In the end you can override request per call by passing second paramater object with desired vaue like this:

api.refresh({},{
    headers:{
        Cache: 'force-cache'
        }
    });
//result:
{
      credentials: "include",
      headers: {
        Accept: "text/html",
        "Content-Type": "text/html;charset=utf-8",
        Cache: "force-cache",
      }
    }

Overiding URL

During your basic configuration you can setup base URL that will be attached to every call as prefix.

api.setBaseUrl('localhost:3030');

Defult base URL is empty string, so all calls will be made on same page. You can override URL on the flight with absolute url key. Redux-rest-fetcher will check if url has 'http', and if yes it will not attach baseUrl prefix to that call.

export default = {
	someService:{
		url:'http://someservice.com/api'//this will override baseUrl
	}
}

Features

There are several features included.

Body parsing

You can send either stringified JSON or plain object to your call.

api.login({body: obj});
//same as
api.login({body: JSON.stringify(obj)});

GET params

You can past your get params as object with key GET. It will be parsed and the result will be attached to your call URL.

api.someService({
    GET:{
        serial: '123456',
        foo: 'bar'
    }
});
// end url result:
'http://someservice.com/api?serial=123456&foo=bar'

expected

You can set what you expect to as return to prevent fetch errors before they occur.

Default expect is json.

api.getText({expected: 'text'})

Of course that means body, GET and expected are reserved and do not make keys in url params with those keywords (url/api/:GET or uer/api/:body)

Using without redux

You can use this library without redux. If you don't pass dispatch function to the library instance you will receive a fetch promise that you need to resolve yourself.

Roadmap

  1. Test sending formData, files and other non JSON cases
  2. Add postfetch tranformer methods like:
    • add to array
    • soft data update
  3. Resolve loading flag to be per call and as pool globaly
  4. Remove lodash dependency
  5. Fix rollup setup