All files / lib client.js

100% Statements 24/24
100% Branches 16/16
100% Functions 4/4
100% Lines 24/24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 532x 2x 2x 2x 2x     4x 6x 4x   2x   6x 1x     3x 1x   2x         5x             5x 5x       4x 2x 2x       2x 2x 2x       2x      
const document = require('./document')
const codecs = require('./codecs')
const errors = require('./errors')
const transports = require('./transports')
const utils = require('./utils')
 
function lookupLink (node, keys) {
  for (let key of keys) {
    if (node instanceof document.Document) {
      node = node.content[key]
    } else {
      node = node[key]
    }
    if (node === undefined) {
      throw new errors.LinkLookupError(`Invalid link lookup: ${JSON.stringify(keys)}`)
    }
  }
  if (!(node instanceof document.Link)) {
    throw new errors.LinkLookupError(`Invalid link lookup: ${JSON.stringify(keys)}`)
  }
  return node
}
 
class Client {
  constructor (options = {}) {
    const transportOptions = {
      auth: options.auth || null,
      headers: options.headers || {},
      requestCallback: options.requestCallback,
      responseCallback: options.responseCallback
    }
 
    this.decoders = options.decoders || [new codecs.CoreJSONCodec(), new codecs.JSONCodec(), new codecs.TextCodec()]
    this.transports = options.transports || [new transports.HTTPTransport(transportOptions)]
  }
 
  action (document, keys, params = {}) {
    const link = lookupLink(document, keys)
    const transport = utils.determineTransport(this.transports, link.url)
    return transport.action(link, this.decoders, params)
  }
 
  get (url) {
    const link = new document.Link(url, 'get')
    const transport = utils.determineTransport(this.transports, url)
    return transport.action(link, this.decoders)
  }
}
 
module.exports = {
  Client: Client
}