'use strict';

const _ = require('lodash');

function buildSelector(model, args) {
  const selector = {
    where: args.where || {}
  };
  const begin = args.after;
  const end = args.before;

  selector.skip = args.first - args.last || 0;
  selector.limit = args.last || args.first;

  if (model.getIdName && model.getIdName()) {
    selector.order = model.getIdName() + (end ? ' DESC' : ' ASC');
    if (begin) {
      selector.where[model.getIdName()] = selector[model.getIdName()] || {};
      selector.where[model.getIdName()].gt = begin;
    }
    if (end) {
      selector.where[model.getIdName()] = selector[model.getIdName()] || {};
      selector.where[model.getIdName()].lt = end;
    }
  }
  return selector;
}

function findOne(model, obj, args, context) {
  const id = obj ? obj[model.getIdName()] : args.id;
  return model.findById(id);
}

function getList(model, obj, args, context) {
  return new Promise((resolve, reject) => {
    // check if the user the required permissions to access this model / method.
    model.checkAccess(context.req.accessToken, '', model.sharedClass.sharedCtor, context, (err, allowed) => {
      if (allowed) {
        resolve(model.find(buildSelector(model, args)));
      } else {
        reject(new Error('Authorization required'));
      }
    });
  });
}

function findAll(model, obj, args, context) {
  return getList(model, obj, args, context);
}

function findRelated(rel, obj, args, context) {
  if (_.isArray(obj[rel.keyFrom])) {
    return Promise.resolve([]);
  }
  args.where = {
    [rel.keyTo]: obj[rel.keyFrom]
  };
  return findAll(rel.modelTo, obj, args, context);

}

module.exports = {
  findAll,
  findOne,
  findRelated
};

@@ -877,33 +877,24 @@
 l, obj, args
-, context
 ) %7B%0A  return
@@ -898,399 +898,45 @@
 urn 
-new Promise((resolve, reject) =%3E %7B%0A    // check if the user the required permissions to access this model / method.%0A    model.checkAccess(context.req.accessToken, '', model.sharedClass.sharedCtor, context, (err, allowed) =%3E %7B%0A      if (allowed) %7B%0A        resolve(model.find(buildSelector(model, args)));%0A      %7D else %7B%0A        reject(new Error('Authorization required'));%0A      %7D%0A    %7D);%0A  %7D
+model.find(buildSelector(model, args)
 );%0A%7D
@@ -979,24 +979,24 @@
  context) %7B%0A
+
   return get
@@ -1016,25 +1016,16 @@
 bj, args
-, context
 );%0A%7D%0A%0Afu

Revert "Added ACL check for queries"