Skip to content

Cookbook: debugging

Eugene Lazutkin edited this page Nov 7, 2019 · 2 revisions

While a bundle is transferred as a JSON object, individual payloads are sent as text strings for compatibility making them difficult to inspect with an interactive debugger. Usually a debugger knows how to show objects in a hierarchical fashion, while strings are shown as is.

The protocol allows for sending JSON objects as is, which simplifies debugging greatly.

All we have to do is to supply a proper processResult callback:

var bundler = require('heya-bundler');
var express = require('express');

var app = express();
var router = express.Router();

router.put('/', bundler({
  isUrlAcceptable: isUrlAcceptable,
  processResult:   processResult
}));

app.use('/bundle', router);

// the rest of the setup

function processResult (result) {
  var response = result.response,
      contentType = getContentType(response.headers),
      isJson = /^application\/json/.test(contentType);
  // send JSON as an object, not as its textual representation
  // useful for debugging
  if (isJson && response.responseText) {
    try {
      response.response = JSON.parse(response.responseText);
      response.responseType = 'json';
      delete response.responseText;
    } catch(e) {
      // Wrong JSON: skip
    }
  }
  return result;
}

var prefixLength = 'Content-Type: '.length;
function getContentType (headers) {
  var values = headers.match(/^Content-Type: .*$/gmi);
  return values ? values.map(function (s) { return s.slice(prefixLength); }).join(', ') : null;
}

function isUrlAcceptable (url) {
  // accept only local absolute URLs
  return /^\/\w/.test(url);
}

Clone this wiki locally