@corpsmap/create-jwt-api-bundle

0.5.0 • Public • Published

CREATE JWT API BUNDLE

Auto-wire your api calls to use a JWT (https://jwt.io) for authentication / authorization. Requires a selector to get the token, typically would be used in concert with the @corpsmap/create-auth-bundle but that's not required as long as you provide a selctor that returns a string token.

Usage

// returns a bundle, see redux-bundler documentation for more info on that
import createJwtApiBundle from "@corpsmap/create-jwt-api-bundle";

// default values for options shown
const apiBundle = createJwtApiBundle({
  name: "api", // optional string
  root: "", // required string, path to your api, won't really work with the default
  tokenSelector: "selectAuthToken", // optional string
  unless: null, // optional object, use to skip adding token to requests conditionally see below
});

Use the apiBundle in your composeBundles workflow to integrate it with your app store.

This will expose new api functions to all of your other action creators:

// in your custom bundle
doFetch: () => ({ dispatch, store, apiGet }) => {};

This bundle will expose the following:

  • apiFetch returns the fetch promise that you can treat as if you used the native fetch api.
  • apiGet fires a GET request, takes a path and a callback similar to the older-school ajax libraries. This was to make it plug and play with legacy code.
  • apiPut fires a PUT request, takes a path, a JSON payload and a callback function
  • apiPost firse a POST request, takes a path, a JSON payload and a callback function
  • apiDelete fires a DELETE request, takes a path and a callback function

Unless

If you want to bypass adding the token, say you want to make some of the requests anonymously in order to present users with some data without requiring them to log in you can set the unless option. This is modelled after the express-unless module, but uses a subset of their options:

unless should be set to an object that may contain one or more of the following keys that will be used to evaluate if the token should be added.

  • method it could be an string or an array of strings. If you want to allow all calls using this method to be anonymous, set it here.
  • path it could be an string, a regexp or an array of any of those. It also could be an array of object which is url and methods key-pairs. If the request path or path and method match, the call will be anonymous.
  • custom it must be a function that accepts an object containing the method and url and returns true / false. If the function returns true for the given request, the request will be sent anonymously.

Readme

Keywords

none

Package Sidebar

Install

npm i @corpsmap/create-jwt-api-bundle

Weekly Downloads

1

Version

0.5.0

License

MIT

Unpacked Size

10.7 kB

Total Files

5

Last publish

Collaborators

  • willbreitkreutz
  • charleshowe
  • gbraide
  • rcrosby
  • rwolniak