import isNumber from 'lodash/isNumber';
import isString from 'lodash/isString';
import defaultsDeep from 'lodash/defaultsDeep';

const defaults = {
  indexType: 'gin',
  limit: 0,
  orderBy: 'updated_at',
  direction: 'desc'
};

const getQueryTextBtree = function ({table, key}) {
  const keys = Object.keys(key);
  const wheres = keys.map(k => {
    const v = key[k];
    if (isNumber(v)) {
      return `(val ->> '${k}')::int = '${v}'`;
    }
    return `val ->> '${k}' = '${v}'`;
  });

  return `SELECT * FROM ${table} WHERE ${wheres.join(' AND ')}`;
};

const mget = async function ({client, table, key, options}) {
  const settings = defaultsDeep({}, options, defaults);

  const {indexType, limit, orderBy, direction} = settings;

  try {
    let text;

    if (isString(key)) {
      text = `SELECT * FROM ${table} WHERE key LIKE '${key}'`;
    } else if (indexType === 'btree') {
      text = getQueryTextBtree({table, key});
    } else {
      text = `SELECT * FROM ${table} WHERE val @> '${JSON.stringify(key)}'`;
    }

    if (orderBy) {
      text += ` ORDER BY ${orderBy}`;
      if (direction) {
        text += ` ${direction}`;
      }
    }

    if (limit > 0) {
      text += ` LIMIT ${limit}`;
    }

    text += `;`;

    const results = await client.query({text});

    const rows = results.rows.map(r => ({
      key: r.key,
      val: r.val,
      createdAt: r.created_at,
      updatedAt: r.updated_at
    }));

    return {
      client,
      results,
      rows
    };
  } catch (error) {
    return {
      client,
      error
    };
  }
};

export default mget;

@@ -173,16 +173,29 @@
 mit: 0,%0A
+  offset: 0,%0A
   orderB
@@ -211,16 +211,16 @@
 ed_at',%0A
-
   direct
@@ -710,16 +710,24 @@
 , limit,
+ offset,
  orderBy
@@ -1155,24 +1155,24 @@
 irection%7D%60;%0A
-
       %7D%0A    
@@ -1166,32 +1166,96 @@
 %0A      %7D%0A    %7D%0A%0A
+    if (offset %3E 0) %7B%0A      text += %60 OFFSET $%7Boffset%7D%60;%0A    %7D%0A%0A
     if (limit %3E 

add limit as mget option, duh