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

frak-js

v0.1.7

Published

Implementation of the Fetch API specifically for JSON based Web Service requests and responses

Downloads

2

Readme

Frak (frak-js)

An implementation of the fetch API specifically for JSON based requests and responses

Installation

Recommended is via NPM / YARN

In your package.json for your app:

{
  "frak-js": "^0.1.6"
}

Install with NPM or YARN:

npm install

yarn install

Implementation

Here's a simple example of a GET request using Frak:

    import { Frak } from 'frak-js';
    const frak = new Frak();
    
    getExample = (uri) => {
      return frak.get(uri)
      .then((json) =>
      {
        console.log(json);
      })
      .catch((error) => {
        console.log('Something went wrong', error);
      });
    };
    
    getExample('http://localhost/8080/endpoint');

Frak constructor

For most applications the defaults for Frak should be sufficient. The constructor takes two optional arguments for the cases where you need Frak behave differently.

  /**
   * Constructor argument is a settings hash and can be undefined to use the defaults
   *
   * @param {object | undefined} settings 
   * @param {object | undefined} options
   */
  Frak(settings, options)

settings is an object hash for how Frak should behave:

| Property | Default | Description | | -------- | ------- | ----------- | | throwErrorOnFailedStatus | false | Set this to true if you want Frak to behave more like Jquery's Ajax | | requestDefaultHeaders | see below | Headers to send for each HTTP method (see below) | | abort | null | Signal |

requestDefaultHeaders default:

    {
      get: [{ 'content-type': null }],
      post: [{ 'content-type': 'application/json' }],
      put: [{ 'content-type': 'application/json' }],
      patch: [{ 'content-type': 'application/json' }],
      delete: [{ 'content-type': null }],
      head: [{ 'content-type': null }],
      options: [{ 'content-type': null }],
      connect: [{ 'content-type': null }],
      trace: [{ 'content-type': null }]
    }

options is also an object hash with the following defaults:

| Property | Default | Description | | -------- | ------- | ----------- | | cache | 'default' | Use the default cache scheme | | mode | 'cors' | Cross-Origin Resource Sharing enabled | | headers | {} | Headers to send with each request |

The above settings are implicitly set and any Request property can be used in this hash.

Frak supports all the standard HTTP web methods.

Frak acts as a proxy to fetch() exposing methods matching the names of the HTTP web methods (with the exception of DELETE -- which is named delete_ so JS doesn't pitch a fit).

The common methods of GET, POST, PATCH, and PUT have an expectation that the response 'Content-Type' (if any) will be 'application/json'. If there is a payload (response content body) that is of a different content type than JSON then Frak will throw an error.

Frak is implemented as a Promise. What follows are Frak's public methods and their signatures.

Methods

Note: The optional options argument for all methods corresponds to an object hash for Request Properties

    /**
    * GET web method for the given url
    * @param {string} url The endpoint for the GET request
    * @param {object} [options] 
    * @returns {Promise} contains the response.body.json() object on success.
    */
    get(url, options)
    
    /**
    * POST web method for the given url and body
    * @param {string} url The URL endpoint
    * @param {object | string} body The body of the request (if a string it must be valid JSON)
    * @param {object} [options] 
    * @returns {Promise} contains the response.body.json() object on success.
    */
    post(url, body, options)
    
    /**
    * PATCH web method for the given url and body
    * @param {string} url - Endpoint for the request
    * @param {object | string} body - The body of the PATCH request (if a string it must be valid JSON)
    * @param {object} [options] 
    * @returns {Promise} contains the response.body.json() object on success.
    */
    patch(url, body, options)
    
    /**
    * PUT web method for the given url and body
    * @param {string} url - Endpoint for the PUT method
    * @param {object | string} body -The body of the PUT request (if a string it must be valid JSON)
    * @param {object} [options] 
    * @returns {Promise} contains the response.body.json() object on success.
    */
    put(url, body, options)
    
    /**
    * DELETE web method for the given url
    * @param {string} url - Endpoint for the DELETE request
    * @param {object} [options] 
    * @returns {Promise}
    * 
    * NOTE: This method is called `delete_` with an underscore.
    *       It is done this way because in some edge cases the JS VM was interpreting this as a JS DELETE command.
    */
    delete_(url, options)
    
    /**
    * HEAD web method for the given url
    * @param {string} url Endpoint for the HEAD request.
    * @param {object} [options]
    * @returns {Promise}
    */
    head(url, options)
    
    /**
    * OPTIONS web method for the given url
    * @param {string} url Endpoint for the OPTIONS request.
    * @param {object} [options]
    * @returns {Promise}
    */
    options(url, options)
    
    /**
    * CONNECT web method for the given url and optional body.
    * @param {string} url Endpoint for the CONNECT method.
    * @param {string} [body] Body to include with the CONNECT request if any.
    * @param {object} [options] 
    * @returns {Promise}
    */
    connect(url, body, options)
    
    /**
     * TRACE web method for the given url
     * @param {string} url Endpoint for the TRACE request.
     * @param {object} [options] Request object @see https://developer.mozilla.org/en-US/docs/Web/API/Request
     * @returns {Promise}
     * 
     * Note: Included only for completeness. There are potential security exploits with this web method and its
     * general use is discouraged.
     * @link https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
     */
    trace(url, options)

Why use Frak and what is with the name Frak?

It's certainly possible to simply use fetch() directly.

Frak is an opinionated JavaScript class library that targets a JSON request/response scenario. If you need to deal with XML or some other data format then Frak is not a good fit in these situations.

When you call a Frak method such as get(), valid JSON is expected in the promise and captured in then() otherwise error details will be in the catch(). Frak is a wrapper around fetch() which is similar to XMLHttpRequest() and Jquery's $.Ajax() -- with the biggest significant difference being that a failed response status (ex: 404 Not Found) doesn't indicate an exception or error. You can make Frak behave more like Ajax by setting throwErrorOnFailedStatus to true:

    import { Frak } from 'frak-js';
    const frak = new Frak({throwErrorOnFailedStatus: true});

fetch() typically only throws an exception when a network error occurs. Frak takes this one step further for responses expecting JSON in the body that has something else will throw an error. Upon success the promise will contain a valid JSON payload (for methods that return a body).

Another difference is that CORS is enabled by default. The reasoning for this is that CORS is an annoying necessary evil with tons of documented issues where developers stub their toes and break their fingers trying to get fetch or even Ajax request/response to work.

If you are detecting some personal annoyance at CORS by the developer of Frak you are correct.

Enabling CORS by default is admittedly a potential security risk but for the sake of developers sanity and the technical support nightmare that CORS is it will remain enabled by default in Frak.

The name Frak is a nod in the direction of Battlestar Galatica The developer of Frak found himself saying "What the frak?!?" over and over especially when it came to dealing with the CORS insanity.

Note: Frak works really well with the Slim Framework and is the primary reason that Frak exists in the first place. (Not to say that Frak will not work with other server side web services)


Question: Why did you name this class library frak-js and not just frak?

Answer: frak at NPM is already taken (although it appears to be 4 year old abandonware).

Contributing

If you find a bug or would like to include a feature then post a new issue in github.

For security related issues please look in package.json and email the developer directly.

If you want to contribute code to Frak you are encouraged to fork this repo and create a pull request.