All files / server/api index.js

87.1% Statements 27/31
60% Branches 6/10
50% Functions 2/4
86.67% Lines 26/30
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 691x 1x 1x   1x 1x 1x 1x   1x 1x     1x 2x     1x 1x 1x 1x     1x             1x         1x   26x     26x         26x   8x 18x   18x                       26x         1x  
const _ = require('lodash');
const express = require('express');
const glob = require('glob');
 
const config = require('../../config');
const pkg = require('../../package');
const errors = require('./utils/errors');
const validation = require('./utils/validation');
 
const logger = config.logger('api');
const router = express.Router();
 
// Make sure all models are loaded.
const modelFiles = _.without(glob.sync('*', { cwd: config.path('server', 'models') }), 'abstract.js');
modelFiles.forEach(modelFile => require(`../models/${modelFile}`));
 
// Plug in API routes.
router.use('/auth', require('./auth/auth.routes'));
router.use('/locations', require('./locations/locations.routes'));
router.use('/me', require('./users/users.me.routes'));
router.use('/users', require('./users/users.routes'));
 
// Return API metadata on the main API route.
router.get('/', function(req, res) {
  res.send({
    version: pkg.version
  });
});
 
// Catch unknown API routes.
router.all('/*', function(req, res, next) {
  next(errors.notFound());
});
 
// Return a JSON error response for API calls.
router.use(function(err, req, res, next) {
 
  const status = err.status || 500;
 
  // Log the error if unexpected
  Iif (status >= 500 && status <= 599) {
    logger.error(err);
  }
 
  let errors;
  if (err instanceof validation.dsl.ValidationErrorBundle) {
    // If the error contains a list of errors, send it in the response.
    errors = err.errors;
  } else Eif (err.code) {
    // If it's a known error, build a one-element array with the error's properties.
    errors = [
      _.pick(err, 'code', 'message')
    ];
  } else {
    // Otherwise, respond with an unexpected error.
    errors = [
      {
        message: 'An unexpected error occurred'
      }
    ];
  }
 
  res.status(status).json({
    errors: errors
  });
});
 
module.exports = router;