<commit_before>const { Types } = require('mongoose');
const HTTPStatus = require('http-status');

const { ObjectId } = Types;

/**
 * Check an parameter is a string or throw an error.
 */
function checkString(chars, { method, message } = {}) {
  if (typeof chars !== 'string') {
    throw new Error(message || `String parameter must be given to the ${method || 'unknown'} method.`);
  }
}
module.exports.checkString = checkString;

/**
 * Check that the resource is compiled before proceeding.
 */
function checkCompile(compile) {
  if (compile) {
    throw new Error('Resource can not be change once it has been compiled.');
  }
}
module.exports.checkCompile = checkCompile;

/**
 * Check if the id of an item is a valid.
 */
function checkObjectId(id, { message } = {}) {
  if (!id || !ObjectId.isValid(id)) {
    const error = new Error(message || 'Request did not contain a valid id.');
    error.code = HTTPStatus.BAD_REQUEST;
    throw error;
  }
}
module.exports.checkObjectId = checkObjectId;

/**
 * Check that an item exists.
 */
function checkExists(value, { message } = {}) {
  if (!value) {
    const error = new Error(message || 'No items were found for the given request.');
    error.code = HTTPStatus.NOT_FOUND;
    throw error;
  }
}
module.exports.checkExists = checkExists;

/**
 * Format response.
 */
function formatResponse(data) {
  if (data instanceof Error) {
    const error = {
      status: 'error',
      code: data.code || 500,
      message: data.message || 'There was an error on the server.',
    };
    if (data.data) {
      error.data = data.data;
    }
    return error;
  }
  return {
    status: 'success',
    code: 200,
    data,
  };
}
module.exports.formatResponse = formatResponse;

/**
 * Format middleware to match express infrastructure.
 */
function middlify(middleware, resources, end = false) {
  return (req, res, next) => (async () => middleware({
    req,
    res,
    next,
    params: req.params,
    body: req.body,
    query: req.query,
    ...resources,
  }))()
    .then(data => end ? res.status(200).json(formatResponse(data)) : next())
    .catch(error => res.status(error.code || 500).json(formatResponse(error)));
}
module.exports.middlify = middlify;

/**
 * Format hooks and execute work.
 */
function hookify(key, handler, preHooks, postHooks) {
  return async (...args) => {
    if (preHooks.has(key)) {
      const tasks = preHooks.get(key).map(hook => hook(...args));
      await Promise.all(tasks);
    }
    let data;
    try {
      data = await handler(...args);
    } catch (e) {
      if (e && e.name === 'ValidationError') {
        const error = new Error(e._message || 'Request validation failed');
        error.code = HTTPStatus.BAD_REQUEST;
        error.data = e.errors;
        throw error;
      }
      throw e;
    }
    if (postHooks.has(key)) {
      const tasks = postHooks.get(key).map(hook => hook({ ...args[0], data }, ...args.slice(1)));
      await Promise.all(tasks);
    }
    return data;
  };
}
module.exports.hookify = hookify;<commit_msg>add fail error status<commit_after>const { Types } = require('mongoose');
const HTTPStatus = require('http-status');

const { ObjectId } = Types;

/**
 * Check an parameter is a string or throw an error.
 */
function checkString(chars, { method, message } = {}) {
  if (typeof chars !== 'string') {
    throw new Error(message || `String parameter must be given to the ${method || 'unknown'} method.`);
  }
}
module.exports.checkString = checkString;

/**
 * Check that the resource is compiled before proceeding.
 */
function checkCompile(compile) {
  if (compile) {
    throw new Error('Resource can not be change once it has been compiled.');
  }
}
module.exports.checkCompile = checkCompile;

/**
 * Check if the id of an item is a valid.
 */
function checkObjectId(id, { message } = {}) {
  if (!id || !ObjectId.isValid(id)) {
    const error = new Error(message || 'Request did not contain a valid id.');
    error.code = HTTPStatus.BAD_REQUEST;
    throw error;
  }
}
module.exports.checkObjectId = checkObjectId;

/**
 * Check that an item exists.
 */
function checkExists(value, { message } = {}) {
  if (!value) {
    const error = new Error(message || 'No items were found for the given request.');
    error.code = HTTPStatus.NOT_FOUND;
    throw error;
  }
}
module.exports.checkExists = checkExists;

/**
 * Format response.
 */
function formatResponse(data) {
  if (data instanceof Error) {
    const error = {
      status: data.status || 'error',
      code: data.code || HTTPStatus.INTERNAL_SERVER_ERROR,
      message: data.message || 'There was an error on the server.',
    };
    if (data.data) {
      error.data = data.data;
    }
    return error;
  }
  return {
    status: 'success',
    code: 200,
    data,
  };
}
module.exports.formatResponse = formatResponse;

/**
 * Format middleware to match express infrastructure.
 */
function middlify(middleware, resources, end = false) {
  return (req, res, next) => (async () => middleware({
    req,
    res,
    next,
    params: req.params,
    body: req.body,
    query: req.query,
    ...resources,
  }))()
    .then(data => end ? res.status(200).json(formatResponse(data)) : next())
    .catch(error => res.status(error.code || 500).json(formatResponse(error)));
}
module.exports.middlify = middlify;

/**
 * Format hooks and execute work.
 */
function hookify(key, handler, preHooks, postHooks) {
  return async (...args) => {
    if (preHooks.has(key)) {
      const tasks = preHooks.get(key).map(hook => hook(...args));
      await Promise.all(tasks);
    }
    let data;
    try {
      data = await handler(...args);
    } catch (e) {
      if (e && e.name === 'ValidationError') {
        const error = new Error(e._message || 'Request validation failed');
        error.code = HTTPStatus.BAD_REQUEST;
        error.data = e.errors;
        error.status = 'fail';
        throw error;
      }
      throw e;
    }
    if (postHooks.has(key)) {
      const tasks = postHooks.get(key).map(hook => hook({ ...args[0], data }, ...args.slice(1)));
      await Promise.all(tasks);
    }
    return data;
  };
}
module.exports.hookify = hookify;
{'fraction_non_alphanumeric': 0.15176107774711897, 'fraction_numerical': 0.004057782827463074, 'mean_word_length': 2.9049429657794676, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 17, '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': '1162849', 'n_tokens_mistral': 1938, 'n_tokens_neox': 1927, 'n_words': 537}