Skip to content

A fully-featured Node.js REST client built for ease-of-use and resilience

License

Notifications You must be signed in to change notification settings

BBC-Knowlearn/flashheart

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

31 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

flashheart


Flashheart


Build Status Code Climate

A fully-featured Node.js REST client built for ease-of-use and resilience

flashheart is request with batteries included. It provides everything you need to build HTTP-based services with confidence.

Installation

npm install --save flashheart

Features

Usage

var client = require('flashheart').createClient({
  name: 'my_service',
  logger: console
});

client.get('http://echo.jsontest.com/key/value/', function (err, body) {
  if (err) throw err;

  console.log(body);
  // {key: "value"}
});

JSON

The client assumes you're working with a JSON API by default. It uses the json: true option in request to send the Accept: application/json header and automatically parse the response into an object. If you need to call an API that returns plain text, XML, animated GIFs etc. then set the json flag to false in your request options.

Errors

Unlike request, any response with a status code greater than or equal to 400 results in an error. There's no need to manually check the status code of the response. The status code is exposed as err.statusCode on the returned error object, and the body (if one exists) is assigned to err.body.

Timeout

The client has a default timeout of 2 seconds. You can override this when creating a client by setting the timeout property.

var client = require('flashheart').createClient({
  timeout: 50
});

Caching

The client will optionally cache any publicly cacheable response with a max-age directive. You can specify the caching storage with an instance of Catbox using the cache parameter.

var Catbox = require('catbox').Client;
var Memory = require('catbox-memory');
var storage = new Catbox(new Memory());
var client = require('flashheart').createClient({
  cache: storage
});

The cache varies on all request options (and therefore, headers) by default. If you don't want to vary on a particular header, use the doNotVary option:

var client = require('flashheart').createClient({
  cache: storage,
  doNotVary: ['Request-Id']
});

Logging

All requests can be logged at info level if you provide a logger that supports the standard logging API (like console or Winston)

var client = require('flashheart').createClient({
  logger: console
});

Stats

Metrics can be sent to StatsD by providing an instance of the node-statsd client:

var StatsD = require('node-statsd');
var stats = new StatsD();

var client = require('flashheart').createClient({
  stats: stats
});

The following metrics are sent from each client:

Name Type Description
{name}.requests Counter Incremented every time a request is made
{name}.responses.{code} Counter Incremented every time a response is received
{name}.request_errors Counter Incremented every time a request fails (timeout, DNS lookup fails etc.)
{name}.response_time Timer Measures of the response time in milliseconds across all requests
{name}.cache.hits Counter Incremented for each cache hit
{name}.cache.misses Counter Incremented for each cache miss
{name}.cache.errors Counter Incremented whenever there's is a problem communicating with the cache

The {name} variable comes from the name option you pass to createClient. It defaults to http if you don't name your client.

You can also add the name option on a per-request basis which will include the request name in the metric. For example: api.feed.cache.hits.

Retries

By default the client retries failed requests once, with a delay of 100 milliseconds between attempts. The number of times to retry and the delay between retries can be configured using the retries and retryTimeout properties.

For example, to retry 10 times, with a delay of 500ms:

var client = require('flashheart').createClient({
  retries: 10,
  retryTimeout: 500
});

Only request errors or server errors result in a retry; 4XX errors are not retried.

Circuit breaker

By default the client implements a circuit breaker using the Levee library. It is configured to trip after 100 failures and resets after 10 seconds. This can be configured using the circuitBreakerMaxFailures and circuitBreakerResetTimeout properties.

For example to trip after 200 failures and try to reset after 30 seconds:

var client = require('flashheart').createClient({
  circuitBreakerMaxFailures: 200,
  circuitBreakerResetTimeout: 30000
});

Advanced configuration

The client uses request to make HTTP requests. You can override the default request instance using the request parameter:

var request = require('request').defaults({
  json: false,
  headers: {
    'X-Api-Key': 'foo'
  }
});

var client = require('flashheart').createClient({
  request: request
});

Usage with client certificates

The request option can also be used to pass a pre-configured request client for HTTPS client certificate authentication:

var fs = require('fs');
var request = require('request').defaults({
  pfx: fs.readFileSync('/path/to/my/cert.p12'),
  passphrase: 'password',
  strictSSL: false
});

var client = require('flashheart').createClient({
  request: request
});

API

.createClient

Creates a new client.

Parameters

  • opts - An options object

Options

  • name - optional - A name to be used for logging and stats (default http)
  • cache - optional - A Catbox instance to use for caching
  • timeout - optional - A timeout in milliseconds (default 2000)
  • retries - optional - Number of times to retry failed requests (default 3)
  • retryTimeout - optional - Time to wait between retries in milliseconds (default 100)
  • circuitBreakerMaxFailures - optional - The number of failures required to trip the circuit breaker (default 100)
  • circuitBreakerResetTimeout - optional - Time in milliseconds to wait before the circuit breaker resets after opening (default 10000)
  • userAgent - optional - A custom user agent for the client (default flashheart/VERSION)
  • doNotVary - optional - An array of headers to ignore when creating cache keys (default [])
  • request - optional - A pre-configured instance of request

client.get

Parameters

  • url - The URL to be requested
  • opts - optional - A set of options. All of the request options are supported
  • callback - A function that is called with an error object and the response body as an object

client.put

Parameters

  • url - The URL to be requested
  • body - A JavaScript object to be used as the request body
  • opts - optional - A set of options. All of the request options are supported
  • callback - A function that is called with an error object and the response body as an object

client.post

Parameters

  • url - The URL to be requested
  • body - A JavaScript object to be used as the request body
  • opts - optional - A set of options. All of the request options are supported
  • callback - A function that is called with an error object and the response body as an object

client.patch

Parameters

  • url - The URL to be requested
  • body - A JavaScript object to be used as the request body
  • opts - optional - A set of options. All of the request options are supported
  • callback - A function that is called with an error object and the response body as an object

client.delete

Parameters

  • url - The URL to be requested
  • opts - optional - A set of options. All of the request options are supported
  • callback - A function that is called with an error object and the response body as an object

Contributing

  • If you're unsure if a feature would make a good addition, you can always create an issue first.
  • We aim for 100% test coverage. Please write tests for any new functionality or changes.
  • Make sure your code meets our linting standards. Run npm run lint to check your code.
  • Maintain the existing coding style. There are some settings in .jsbeautifyrc to help.

Why Flashheart?

Lord Flashheart is Blackadder's trusted friend, and a massive show-off.

Flashheart

About

A fully-featured Node.js REST client built for ease-of-use and resilience

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%