All files / lib/postProcessing sort.js

10.53% Statements 2/19
0% Branches 0/12
0% Functions 0/2
11.11% Lines 2/18
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  1x   1x                                                                
'use strict'
const sort = module.exports = { }
 
sort.action = (request, response, callback) => {
  let attribute = request.params.sort
  let ascending = 1
  if (!attribute) return callback()
  attribute = (`${attribute}`)
  if (attribute[0] === '-') {
    ascending = -1
    attribute = attribute.substring(1, attribute.length)
  }
 
  if (!request.resourceConfig.attributes[attribute]) {
    return callback({ // eslint-disable-line standard/no-callback-literal
      status: '403',
      code: 'EFORBIDDEN',
      title: 'Invalid sort',
      detail: `${request.resourceConfig.resource} do not have property ${attribute}`
    })
  }
 
  // todo: consider using a stable sort algerith (e.g. lodash.sortBy)
  response.data = response.data.sort((a, b) => {
    if (typeof a.attributes[attribute] === 'string') {
      return a.attributes[attribute].localeCompare(b.attributes[attribute]) * ascending
    } else if (typeof a.attributes[attribute] === 'number' || a.attributes[attribute] instanceof Date) {
      return (a.attributes[attribute] - b.attributes[attribute]) * ascending
    } else {
      return 0
    }
  })
 
  return callback()
}