module.exports = {
    friendlyName: "Paginator",
  
    description: "Paginate something.",
  
    inputs: {
      model: {
        type: "ref",
      },
      cond: {
        type: "ref",
      },
      paginateOptions: {
        type: "ref",
        defaultsTo: null,
      },
      populates: {
        type: "ref",
        defaultsTo: {},
      },
    },
  
    exits: {
      paginateRequestError: {
        description: "xxx",
      },
    },
  
    fn: async function ({ model, cond, paginateOptions, populates }, exits) {
      if (["limit", "skip"].every((key) => _.has(paginateOptions, key))) {
        //console.log('cond', cond)
        let criteria = {
          where: cond,
          ..._.pick(paginateOptions, ["limit", "skip", "sort"]),
        };
        //console.log('criteria',criteria)
        // console.log('fixed cond', paginateOptions.fixCond)
        let data = await model
          .find(criteria, populates)
          .intercept((err) => {
            console.error("helper:paginator:paginateRequestError", err);
            return "paginateRequestError";
          })
          .meta({ skipRecordVerification: true });
  
        let recordsFiltered = await model.count({ where: cond });
        let recordsTotal = await model.count(paginateOptions.fixCond);
        return exits.success({
          data,
          recordsFiltered,
          recordsTotal,
        });
      } else {
        let result = await model
          .find({ where: cond, sort: paginateOptions.sort }, populates)
          .intercept((err) => {
            console.error("helper:paginator:paginateRequestError", err);
            return "paginateRequestError";
          });
        return exits.success(result);
      }
    },
  };
  