<commit_before>/* global JsonRoutes:true */

var Fiber = Npm.require("fibers");
var connect = Npm.require('connect');
var connectRoute = Npm.require('connect-route');

JsonRoutes = {};

WebApp.rawConnectHandlers.use(connect.bodyParser());
WebApp.rawConnectHandlers.use(connect.query());

JsonRoutes.middleWare = connect();
WebApp.rawConnectHandlers.use(JsonRoutes.middleWare);

// List of all defined JSON API endpoints
JsonRoutes.routes = [];

// Save reference to router for later
var connectRouter;

// Register as a middleware
WebApp.rawConnectHandlers.use(connectRoute(function (router) {
  connectRouter = router;
}));

JsonRoutes.add = function (method, path, handler) {
  // Make sure path starts with a slash
  if (path[0] !== "/") {
    path = "/" + path;
  }

  // Add to list of known endpoints
  JsonRoutes.routes.push({
    method: method,
    path: path
  });

  connectRouter[method.toLowerCase()](path, function (req, res, next) {
    Fiber(function () {
      try {
        handler(req, res, next);
      } catch (err) {
        JsonRoutes.sendError(res, null, err);
      }
    }).run();
  });
};

var responseHeaders = {
  "Cache-Control": "no-store",
  "Pragma": "no-cache"
};

JsonRoutes.setResponseHeaders = function (headers) {
  responseHeaders = headers;
};

/**
 * Convert `Error` objects to plain response objects suitable
 * for serialization.
 *
 * @param {Any} [data] Should be a Meteor.Error or Error object. If anything
 *   else is passed or this argument isn't provided, a generic
 *   "internal-server-error" object is returned
 */
JsonRoutes._errorToJson = function (data) {
  if (data instanceof Meteor.Error) {
    return buildErrorResponse(data);
  } else if (data && data.sanitizedError instanceof Meteor.Error) {
    return buildErrorResponse(data.sanitizedError);
  } else {
    return {
      error: 'internal-server-error',
      reason: 'Internal server error'
    };
  }
};

/**
 * Sets the response headers, status code, and body, and ends it.
 * The JSON response will be pretty printed if NODE_ENV is `development`.
 *
 * @param {Object} res Response object
 * @param {Number} code HTTP status code.
 * @param {Object|Array|null|undefined} data The object to stringify as
 *   the response. If `null`, the response will be "null". If
 *   `undefined`, there will be no response body.
 */
JsonRoutes.sendResult = function (res, code, data) {
  // Set headers on response
  setHeaders(res);

  // Set status code on response
  res.statusCode = code || 200;

  // Set response body
  writeJsonToBody(res, data);

  // Send the response
  res.end();
};

/**
 * Sets the response headers, status code, and body, and ends it.
 * The JSON response will be pretty printed if NODE_ENV is `development`.
 *
 * @param {Object} res Response object
 * @param {Number} code The status code to send. Default is taken from
 *   `error.statusCode` if present. Otherwise 400.
 * @param {Error|Meteor.Error} error The error object to stringify as
 *   the response. A JSON representation of the error details will be
 *   sent. You can set `error.data` or `error.sanitizedError.data` to
 *   some extra data to be serialized and sent with the response.
 */
JsonRoutes.sendError = function (res, code, error) {
  // Set headers on response
  setHeaders(res);

  // If no error passed in, use the default empty error
  error = error || new Error();

  // Set status code on response
  res.statusCode = code || getStatusCodeFromError(error);

  // Convert `Error` objects to JSON representations
  var json = JsonRoutes._errorToJson(error);

  // Set response body
  writeJsonToBody(res, json);

  // Send the response
  res.end();
};

function setHeaders(res) {
  _.each(responseHeaders, function (value, key) {
    res.setHeader(key, value);
  });
}

function getStatusCodeFromError(error) {
  // So that we don't have to keep checking if error exists
  if (! error) {
    return 500;
  }

  // If an error or sanitizedError has a `statusCode` property, we use that.
  // This allows packages to check whether JsonRoutes package is used and if so,
  // to include a specific error status code with the errors they throw.
  if (error.sanitizedError && error.sanitizedError.statusCode) {
    return error.sanitizedError.statusCode;
  }
<commit_msg>Make error statusCode only used in the error catching<commit_after>/* global JsonRoutes:true */

var Fiber = Npm.require("fibers");
var connect = Npm.require('connect');
var connectRoute = Npm.require('connect-route');

JsonRoutes = {};

WebApp.rawConnectHandlers.use(connect.bodyParser());
WebApp.rawConnectHandlers.use(connect.query());

JsonRoutes.middleWare = connect();
WebApp.rawConnectHandlers.use(JsonRoutes.middleWare);

// List of all defined JSON API endpoints
JsonRoutes.routes = [];

// Save reference to router for later
var connectRouter;

// Register as a middleware
WebApp.rawConnectHandlers.use(connectRoute(function (router) {
  connectRouter = router;
}));

JsonRoutes.add = function (method, path, handler) {
  // Make sure path starts with a slash
  if (path[0] !== "/") {
    path = "/" + path;
  }

  // Add to list of known endpoints
  JsonRoutes.routes.push({
    method: method,
    path: path
  });

  connectRouter[method.toLowerCase()](path, function (req, res, next) {
    Fiber(function () {
      try {
        handler(req, res, next);
      } catch (err) {
        JsonRoutes.sendError(res, getStatusCodeFromError(err), err);
      }
    }).run();
  });
};

var responseHeaders = {
  "Cache-Control": "no-store",
  "Pragma": "no-cache"
};

JsonRoutes.setResponseHeaders = function (headers) {
  responseHeaders = headers;
};

/**
 * Convert `Error` objects to plain response objects suitable
 * for serialization.
 *
 * @param {Any} [data] Should be a Meteor.Error or Error object. If anything
 *   else is passed or this argument isn't provided, a generic
 *   "internal-server-error" object is returned
 */
JsonRoutes._errorToJson = function (data) {
  if (data instanceof Meteor.Error) {
    return buildErrorResponse(data);
  } else if (data && data.sanitizedError instanceof Meteor.Error) {
    return buildErrorResponse(data.sanitizedError);
  } else {
    return {
      error: 'internal-server-error',
      reason: 'Internal server error'
    };
  }
};

/**
 * Sets the response headers, status code, and body, and ends it.
 * The JSON response will be pretty printed if NODE_ENV is `development`.
 *
 * @param {Object} res Response object
 * @param {Number} code HTTP status code.
 * @param {Object|Array|null|undefined} data The object to stringify as
 *   the response. If `null`, the response will be "null". If
 *   `undefined`, there will be no response body.
 */
JsonRoutes.sendResult = function (res, code, data) {
  // Set headers on response
  setHeaders(res);

  // Set status code on response
  res.statusCode = code || 200;

  // Set response body
  writeJsonToBody(res, data);

  // Send the response
  res.end();
};

/**
 * Sets the response headers, status code, and body, and ends it.
 * The JSON response will be pretty printed if NODE_ENV is `development`.
 *
 * @param {Object} res Response object
 * @param {Number} code The status code to send. Default is 500.
 * @param {Error|Meteor.Error} error The error object to stringify as
 *   the response. A JSON representation of the error details will be
 *   sent. You can set `error.data` or `error.sanitizedError.data` to
 *   some extra data to be serialized and sent with the response.
 */
JsonRoutes.sendError = function (res, code, error) {
  // Set headers on response
  setHeaders(res);

  // If no error passed in, use the default empty error
  error = error || new Error();

  // Set status code on response
  res.statusCode = code || 500;

  // Convert `Error` objects to JSON representations
  var json = JsonRoutes._errorToJson(error);

  // Set response body
  writeJsonToBody(res, json);

  // Send the response
  res.end();
};

function setHeaders(res) {
  _.each(responseHeaders, function (value, key) {
    res.setHeader(key, value);
  });
}

function getStatusCodeFromError(error) {
  // So that we don't have to keep checking if error exists
  if (! error) {
    return 500;
  }

  // If an error or sanitizedError has a `statusCode` property, we use that.
  // This allows packages to check whether JsonRoutes package is used and if so,
  // to include a specific error status code with the errors they throw.
  if (error.sanitizedError && error.sanitizedError.statusCode) {
    return error.sanitizedError.statusCode;
  }

{'fraction_non_alphanumeric': 0.11615096108766995, 'fraction_numerical': 0.0026957337083919363, 'mean_word_length': 3.5364167995746945, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7131831', 'n_tokens_mistral': 2592, 'n_tokens_neox': 2532, 'n_words': 886}