stateFieldsToQuery = ({
  state,
  stateHash,
  fields,
  prefix = "",
  noSortAndPaging,
}) => {
  let q = {};
  if (!noSortAndPaging) {
    const sortbyName = `_${stateHash}_sortby`;
    const sortDescName = `_${stateHash}_sortdesc`;
    if (state[sortbyName]) {
      if (typeof state[sortbyName] === "string")
        q.orderBy = db.sqlsanitize(state[sortbyName]);
      if (state[sortDescName]) q.orderDesc = true;
    } else if (state._orderBy) {
      if (typeof state._orderBy === "string") {
        q.orderBy = db.sqlsanitize(state._orderBy);
        if (state._orderDesc) q.orderDesc = true;
      } else if (typeof state._orderBy === "object") {
        const { operator, field, target } = state._orderBy;
        const fld = fields.find((f) => f.name == field);

        if (!fld) return;
        const oper = fld.type?.distance_operators?.[operator];

        if (!oper) return;
        q.orderBy = { operator: oper, field, target };
      }
    }
    Object.keys(state).forEach((k) => {
      if (!k.startsWith("_op_")) return;
      const [_blank, _op, fieldName, opName] = k.split("_");
      const field = fields.find((f) => f.name == fieldName);

      if (!field) return;
      const operator = field.type?.distance_operators?.[opName];

      if (!operator) return;
      q.orderBy = { operator, field: fieldName, target: state[k] };
    });

    const pagesize =
      stateHash && state[`_${stateHash}_pagesize`]
        ? parseInt(state[`_${stateHash}_pagesize`])
        : undefined;
    if (pagesize) {
      q.limit = parseInt(pagesize);
      const page =
        stateHash && state[`_${stateHash}_page`]
          ? parseInt(state[`_${stateHash}_page`])
          : undefined;
      if (page) {
        q.offset = (page - 1) * pagesize;
      }
    }
  }
  const stateKeys = Object.keys(state);
  const latNear = stateKeys.find((k) => k.startsWith("_near_lat_"));
  const longNear = stateKeys.find((k) => k.startsWith("_near_long_"));
  if (latNear && longNear) {
    const latField = prefix + db.sqlsanitize(latNear.replace("_near_lat_", ""));
    const longField =
      prefix + db.sqlsanitize(longNear.replace("_near_long_", ""));
    const lat = parseFloat(state[latNear]);
    const long = parseFloat(state[longNear]);
    q.orderBy = { distance: { lat, long, latField, longField } };
  }
  return q;
}
State fields to Query
@function
@param {object}
@returns {object}