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

interfacer

v0.1.4

Published

Module for working with REST API

Downloads

9

Readme

Interfacer.js

Interfacer.js is a convenient module for working with RESTful API from Client.

Key Features:

  • Unopinionated about frameworks you use
  • Highly customizable
  • Memoization by default
  • Simple error handling, that fits your system
  • Customizable query construction
  • Optional normalizr integration

How to install

yarn add interfacer

or

npm install interfacer --save

Configuration & Interface Creation

The most advanced feature, Interfacer.js provides, are 3 levels of configuration (Application level, Single Interface/Collection level, Request level). In every configuration level you can define things like defaultError, baseUrl, custom querybuilder and more. Each level of configuration overrides previous (more global ones), so you can change everything, mid-action, on the fly if you need to.

Don't panic as you'll see all them references to Redux like dispatch. Their's purpose is purely illustrative. you can provide any kind of function, that handles your data.

Application Level

import interfacer from 'interfacer';

const globalConfig = {
  baseUrl: 'http://localhost:8080/api',
  defaultError: new Error('Something broke'),
  errorHandler: ({error, message}) => dispatch({ type: 'API_ERROR', payload: message })
}

const createInterface = interfacer(globalConfig);

All of above settings will apply to every interface instance you create with this createInterface function, unless overwritten by later configurations in more "local" level.

Interface level

Also can be perceived as "collection level". In for example Redux I'd recommend to have one interface for each collection reducer. From server perspective, there is one interface per resource.

const localConfig = {
  defaultError: new Error('Articles API error'),
  querybuilder: myCustomQueryBuilder,
  headers: { 'Content-Type': 'text/html' }
  request: { mode: 'cors' },
  flatMethod: parseXMLFunction,
  errorHandler: err => dispatch({ type: 'API_ERROR', payload: err })
}

const articleInterface = createInterface('/articles', localConfig);

On Interface level you always specify resource. That is route that will be appended to baseUrl in all requests you do, with this interface. resource string is always passed to createInterface function as a first paramtere. Obviously you can (and will) have many different Interfaces.

Request level

This final and most local level references to a certain requests you make with your interface. Each call returns a promise with your flattened (see flatMethod) response.

const requestOptions = {
  query: { fields: ['title', 'author']},
  defaultError: new Error('Articles Collection failed to fetch')
};

articleInterface
	.getCollection(requestOptions)
  .then(data =>
  	dispatch({ type: 'RECIEVE_ARTICLES', payload: data })
  );

Overview

Once you've created your interface network and configured it, it's time for you to do some fetching. Every interface has following methods get, getCollection, update, create and remove. Once called, each function returns a Promise, that contains response of the fetch as a frist parameter. Here is their API annotation.

get

(id :string | number, requestConfig? :Object) => Promise<Response>

getCollection

(requestConfig? :Object) => Promise<Response>

create

(body :Object, requestConfig? :Object) => Promise<Response>

remove

(id :ID, requestConfig? :Object) => Promise<Response>

update

(id :string, body :Object, requestConfig? :Object) => Promise<Response>

API Reference

Config Properties

| Property | Meaning | Type | Default | |----------|---------|------|---------| | error| Error that gets sent to you via throwError fn once it occures | string or object | "unhandled" | | defaultError | If no error is found, defaultError gets sent to you | string or object | "unhandled" | | errorHandler | Function that gets called if error occurs. As first argument your error will be passed | console.error | | headers | Object containting headers your request should have | object | "Content-Type": "application/json" | |flatMethod| Function that will be used on raw response from the fetch| function | .json()| | request | This object will be added to request options. It's the same as pasting an object into second argument of fetch function | {} | | query | Object that gets passed to queryparser fn | object | {} | | baseUrl | baseUrl that your API runs on | string | "/" | | querybuilder | Function that transform query object into a query string | function| querybuilder | makeBody | Function that'll be run on body, right before request is made. | function | body => body| | schema | If you're using normalizr you can specify, response will be normalized using this schema. | object | |

Note on normalization:

Normalization of the response will take place after flatMethod is applied. Also schema property can be only configured in either Interface level or Request level config, as it doesn't really make sense to use one schema for all requests.

URL Queries

You can pass your own querybuilder into any config, but you can also use default one. Annotation of querybuilder looks like this

 querybuilder(query :Object) => string

Default querybuilder builds queries like this...

querybuilder({
  filters: 'over18',
  fields: ['title', 'years old']
});
// -> 'filters=over18&fields=title&fields=years%20old'