National Preventative Mechanism

    snuffles

    1.2.2 • Public • Published

    A wrapper around the native fetch function, providing a more convenient way to use it for JSON requests

    At its core, Snuffles is just a very slim wrapper around the native fetch function. It allows for setting a base url and default options for your request, provides some wrappers around some of the more frequently used HTTP methods and takes care of all casing. You send camelCased objects in, you get camelCased objects out.

    Installation

    npm install --save snuffles

    Usage

    import Snuffles from 'snuffles'
     
    export default function myApiWrapper() {
      const defaultRequestOptions = {
        headers: {
          'X-AUTH-TOKEN': 'my-secret-token'
        }
      }
     
      const metaOptions = {
        bodyKeyCase: 'CAMEL_CASE'
      }
     
      const api = new Snuffles(
        'http://base-url.tld',
        defaultRequestOptions,
        metaOptions
      )
     
      const user = api.get('/user')
    }

    To create a new instance of Snuffles:

    const api = new Snuffles(baseUrl[, defaultRequestOptions, metaOptions])
    • baseUrl: The base url of the API you want to make requests agains
    • defaultRequestOptions (optional): An Object, containing a set of default options you want to sent in every request, e.g. headers for authentication
    • metaOptions (optional): An object containing meta configuration for Snuffles. For possible options, please refer to the list below

    Default Request Options

    Snuffles accepts all options that fetch accepts as its init parameter (docs). In fact, snuffles does not validate the options that are passed at all.

    Meta Options

    The metaOptions object accepts the following configureations:

    • bodyKeyCase: A string defining which casing the keys of a request body for outgoing requests should have. Can be either of SNAKE_CASE, CAMEL_CASE or PARAM_CASE.
    • logger: A custom logger function (see Logging section)

    If no object is passed for metaOptions, the following defaul configuration will be used:

    {
      bodyKeyCase: 'SNAKE_CASE',
      logger: () => {} // no-op logger
    }

    Supported HTTP Methods

    As of now, Snuffles has wrappers for 5 request methods:

    • get(path[, options])
    • post(path[, options])
    • put(path[, options])
    • patch(path[, options])
    • delete(path[, options])

    Where

    • path: the path you want that specific request to go to
    • options (optional): An Object containing a set of options you want to merge with the base options on this specific request. Options passed to the wrapper functions are deep-merged, but will override identical keys.

    Using querystrings

    Snuffles does support the setting of querystrings via its options parameter. You can pass in a query object with the desired key-value-pairs. For example:

    const api = new Snuffles('http://base-url.tld')
     
    const options = {
      query: {
        name: 'sirius',
        animal: 'dog'
      }
    }
     
    const user = api.get('/user', options)
     
    // => fetch('http://base-url.tld/user?name=sirius&animal=dog')

    Casing

    Snuffles will take care of transforming the casing of response and request bodies, so that you can pass in a camelCased object as a request body (passed via options.body) and get out the response body as a camelCased object as well.

    Response bodies

    Assuming GET https://your-api/users/1 would return a response with a body of

    {
      "user_name": "John Doe",
      "paid_user": false
    }

    If you make this request with snuffles, it would look like

    const api = new Snuffles('https://your-api')
     
    const res = api.get('/users/1')
     
    // res =>
    // {
    //   userName: "John Doe",
    //   paidUser: false
    // }
    //

    Request bodies:

    const api = new Snuffles('http://base-url.tld')
     
    const options = {
      body: {
        userName: 'sirius',
        paidUser: true
      }
    }
     
    api.post('/users', options)
     
    // sends a request to 'http://base-url.tld/users', with the body
    // {
    //    user_name: 'sirius',
    //    paid_user: true
    // }

    Logging

    For normal browser-based development the network tab in your browser's developer tools is probably all you need.

    If you should have custom logging requirements (e.g. if you work with React Native, where you cannot use the network tab in the remote React Native Debugger) you can pass in your custom logger function as an option to the 3rd argument of the Snuffles() constructor.

    Here is an example using debug as a custom logger:

    import createDebug from 'debug'
    const debug = createDebug('api')
     
    const apiClient = new Snuffles(
      apiUrl,
      { ... }
      { logger: debug }
    )

    The first argument of each log call is always the type of the log entry (either 'request' or 'response'), so you can take advantage of this to log them differently. E.g. into separate logging namespaces:

    { logger: (type, ...data) => createDebug(`api:${type}`)(...data) }

    Beware: if the logs should get persisted/streamed to anywhere, be careful that you could be exposing sensitive information like passwords, API tokens, which are part of the logged HTTP requests.

    License

    MIT © railslove

    Dog Illustrastion from Pixabay under CC0-License.

    Made with 💚 in Cologne

    Keywords

    none

    Install

    npm i snuffles

    DownloadsWeekly Downloads

    2

    Version

    1.2.2

    License

    MIT

    Unpacked Size

    166 kB

    Total Files

    7

    Last publish

    Collaborators

    • timomeh
    • chrispop
    • danieldiekmeier