<commit_before>/*!
 * Copyright(c) 2014 <NAME> (pofider)
 *
 * ODataServer class - main facade
 */

/* eslint no-useless-escape: 0 */

var Emitter = require('events').EventEmitter
var util = require('util')
var url = require('url')
var metadata = require('./metadata.js')
var collections = require('./collections.js')
var query = require('./query.js')
var insert = require('./insert.js')
var update = require('./update.js')
var remove = require('./remove.js')
var Router = require('./router.js')
var prune = require('./prune.js')

function ODataServer (serviceUrl) {
  this.serviceUrl = serviceUrl

  this.cfg = {
    serviceUrl: serviceUrl,
    afterRead: function () {},
    beforeQuery: function (col, query, req, cb) { cb() },
    executeQuery: ODataServer.prototype.executeQuery.bind(this),
    beforeInsert: function (col, query, req, cb) { cb() },
    executeInsert: ODataServer.prototype.executeInsert.bind(this),
    beforeUpdate: function (col, query, update, req, cb) { cb() },
    executeUpdate: ODataServer.prototype.executeUpdate.bind(this),
    beforeRemove: function (col, query, req, cb) { cb() },
    executeRemove: ODataServer.prototype.executeRemove.bind(this),
    base64ToBuffer: ODataServer.prototype.base64ToBuffer.bind(this),
    bufferToBase64: ODataServer.prototype.bufferToBase64.bind(this),
    pruneResults: ODataServer.prototype.pruneResults.bind(this)
  }
}

util.inherits(ODataServer, Emitter)

ODataServer.prototype.handle = function (req, res) {
  if (!this.cfg.serviceUrl && !req.protocol) {
    throw new Error('Unable to determine service url from the express request or value provided in the ODataServer constructor.')
  }

  function escapeRegExp (str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&')
  }

    // If mounted in express, trim off the subpath (req.url) giving us just the base path
  var path = (req.originalUrl || '/').replace(new RegExp(escapeRegExp(req.url) + '$'), '')
  this.cfg.serviceUrl = this.serviceUrl ? this.serviceUrl : (req.protocol + '://' + req.get('host') + path)

  var prefix = url.parse(this.cfg.serviceUrl).pathname
  if (!this.router || (prefix !== this.router.prefix)) {
    this.router = new Router(prefix)
    this._initializeRoutes()
  }

  this.router.dispatch(req, res)
}

ODataServer.prototype._initializeRoutes = function () {
  var self = this
  this.router.get('/\$metadata', function (req, res) {
    var result = metadata(self.cfg)
    res.writeHead(200, {'Content-Type': 'application/xml', 'DataServiceVersion': '4.0', 'OData-Version': '4.0'})
    return res.end(result)
  })
  this.router.get('/:collection/\$count/', function (req, res) {
    req.params.$count = true
    query(self.cfg, req, res)
  })
  this.router.get('/:collection\\(:id\\)', function (req, res) {
    query(self.cfg, req, res)
  })
  this.router.get('/:collection', function (req, res) {
    query(self.cfg, req, res)
  })
  this.router.get('/', function (req, res) {
    var result = collections(self.cfg)
    res.writeHead(200, {'Content-Type': 'application/json'})
    return res.end(result)
  })
  this.router.post('/:collection', function (req, res) {
    insert(self.cfg, req, res)
  })
  this.router.patch('/:collection\\(:id\\)', function (req, res) {
    update(self.cfg, req, res)
  })
  this.router.delete('/:collection\\(:id\\)', function (req, res) {
    remove(self.cfg, req, res)
  })

  if (this.cfg.cors) {
    this.router.options('/*', function (req, res) {
      res.writeHead(200, {'Access-Control-Allow-Origin': self.cfg.cors})
      res.end()
    })
  }

  this.router.error(function (req, res, error) {
    function def (e) {
      self.emit('odata-error', e)
      res.writeHead(error.code || 500, {'Content-Type': 'application/json'})
      res.end(JSON.stringify({
        'error': {
          'code': error.code || 500,
          'message': e.message,
          stack: e.stack,
          'target': req.url,
          'details': []
        },
        'innererror': { }
      }))
    }
    if (self.cfg.error) {
      self.cfg.error(req, res, error, def)
    } else {
      def(error)
    }
  })
}

ODataServer.prototype.error = function (fn) {
  this.cfg.error = fn.bind(this)
  return this
}
<commit_msg>#25 avoid setting invalid error status code<commit_after>/*!
 * Copyright(c) 2014 <NAME> (pofider)
 *
 * ODataServer class - main facade
 */

/* eslint no-useless-escape: 0 */

var Emitter = require('events').EventEmitter
var util = require('util')
var url = require('url')
var metadata = require('./metadata.js')
var collections = require('./collections.js')
var query = require('./query.js')
var insert = require('./insert.js')
var update = require('./update.js')
var remove = require('./remove.js')
var Router = require('./router.js')
var prune = require('./prune.js')

function ODataServer (serviceUrl) {
  this.serviceUrl = serviceUrl

  this.cfg = {
    serviceUrl: serviceUrl,
    afterRead: function () {},
    beforeQuery: function (col, query, req, cb) { cb() },
    executeQuery: ODataServer.prototype.executeQuery.bind(this),
    beforeInsert: function (col, query, req, cb) { cb() },
    executeInsert: ODataServer.prototype.executeInsert.bind(this),
    beforeUpdate: function (col, query, update, req, cb) { cb() },
    executeUpdate: ODataServer.prototype.executeUpdate.bind(this),
    beforeRemove: function (col, query, req, cb) { cb() },
    executeRemove: ODataServer.prototype.executeRemove.bind(this),
    base64ToBuffer: ODataServer.prototype.base64ToBuffer.bind(this),
    bufferToBase64: ODataServer.prototype.bufferToBase64.bind(this),
    pruneResults: ODataServer.prototype.pruneResults.bind(this)
  }
}

util.inherits(ODataServer, Emitter)

ODataServer.prototype.handle = function (req, res) {
  if (!this.cfg.serviceUrl && !req.protocol) {
    throw new Error('Unable to determine service url from the express request or value provided in the ODataServer constructor.')
  }

  function escapeRegExp (str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&')
  }

    // If mounted in express, trim off the subpath (req.url) giving us just the base path
  var path = (req.originalUrl || '/').replace(new RegExp(escapeRegExp(req.url) + '$'), '')
  this.cfg.serviceUrl = this.serviceUrl ? this.serviceUrl : (req.protocol + '://' + req.get('host') + path)

  var prefix = url.parse(this.cfg.serviceUrl).pathname
  if (!this.router || (prefix !== this.router.prefix)) {
    this.router = new Router(prefix)
    this._initializeRoutes()
  }

  this.router.dispatch(req, res)
}

ODataServer.prototype._initializeRoutes = function () {
  var self = this
  this.router.get('/\$metadata', function (req, res) {
    var result = metadata(self.cfg)
    res.writeHead(200, {'Content-Type': 'application/xml', 'DataServiceVersion': '4.0', 'OData-Version': '4.0'})
    return res.end(result)
  })
  this.router.get('/:collection/\$count/', function (req, res) {
    req.params.$count = true
    query(self.cfg, req, res)
  })
  this.router.get('/:collection\\(:id\\)', function (req, res) {
    query(self.cfg, req, res)
  })
  this.router.get('/:collection', function (req, res) {
    query(self.cfg, req, res)
  })
  this.router.get('/', function (req, res) {
    var result = collections(self.cfg)
    res.writeHead(200, {'Content-Type': 'application/json'})
    return res.end(result)
  })
  this.router.post('/:collection', function (req, res) {
    insert(self.cfg, req, res)
  })
  this.router.patch('/:collection\\(:id\\)', function (req, res) {
    update(self.cfg, req, res)
  })
  this.router.delete('/:collection\\(:id\\)', function (req, res) {
    remove(self.cfg, req, res)
  })

  if (this.cfg.cors) {
    this.router.options('/*', function (req, res) {
      res.writeHead(200, {'Access-Control-Allow-Origin': self.cfg.cors})
      res.end()
    })
  }

  this.router.error(function (req, res, error) {
    function def (e) {
      self.emit('odata-error', e)
      res.writeHead((error.code && error.code >= 100 && error.code < 600) ? error.code : 500, {'Content-Type': 'application/json'})
      res.end(JSON.stringify({
        'error': {
          'code': error.code || 500,
          'message': e.message,
          stack: e.stack,
          'target': req.url,
          'details': []
        },
        'innererror': { }
      }))
    }
    if (self.cfg.error) {
      self.cfg.error(req, res, error, def)
    } else {
      def(error)
    }
  })
}

ODataServer.prototype.error = function (fn) {
  this.cfg.error = fn.bind(this)
  return this
}

{'fraction_non_alphanumeric': 0.1806550064561568, 'fraction_numerical': 0.008451696208475173, 'mean_word_length': 3.2943548387096775, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, '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': '464880', 'n_tokens_mistral': 2868, 'n_tokens_neox': 2804, 'n_words': 605}