const PostgREST = require('postgrest-client')
const keys = require('lodash/keys')

const postgrestHost = process.env.POSTGREST_HOST
const db = new PostgREST(postgrestHost)

module.exports = {
  getTables () {
    return db.get('/')
      .set('Accept', '*/*') // https://github.com/begriffs/postgrest/issues/860
      .then((data) => keys(data.definitions).map((table) => ({name: table})))
      .then((tables) => {
        return tables
      })
  },

  getRows (table, limit = 0, offset = 0) {
    const from = offset
    const to = offset + limit
    return db.get(`/${table}`)
      .range(from, to)
      .order('id', true) // ascending
      .set('Accept', '*/*') // https://github.com/begriffs/postgrest/issues/860
  },

  getSchema (table) {
    return db.get('/')
      .set('Accept', '*/*') // https://github.com/begriffs/postgrest/issues/860
      .then((data) => {
        const keys = data.definitions[table].properties
        const fields = []
        for (let key in keys) {
          fields.push({
            name: key,
            type: keys[key].type
          })
        }
        return fields
      })
  },

  update (table, updates, conditions) {
    return db.patch(`/${table}`)
      .set('Prefer', 'return=representation') // include row in response
      .set('Accept', 'application/vnd.pgrst.object+json') // return obj not array
      .match(conditions)
      .send(updates)
  }
}

@@ -326,16 +326,33 @@
 data) =%3E
+ %7B%0A        return
  keys(da
@@ -370,89 +370,108 @@
 ons)
-.map((table) =%3E (%7Bname: table%7D)))%0A
+%0A          .filter((table) =%3E !table.startsWith('(rpc)'))%0A    
       .
-then
+map
 ((table
-s
 ) =%3E 
-%7B%0A        return
+(%7Bname:
  table
-s
+%7D))
 %0A   
@@ -785,39 +785,95 @@
 %7B%0A    return db.
-ge
+pos
 t('/
-'
+rpc/get_schema')%0A      .send(%7B table_name_param: table %7D
 )%0A      .set('Ac
@@ -942,280 +942,8 @@
 860%0A
-      .then((data) =%3E %7B%0A        const keys = data.definitions%5Btable%5D.properties%0A        const fields = %5B%5D%0A        for (let key in keys) %7B%0A          fields.push(%7B%0A            name: key,%0A            type: keys%5Bkey%5D.type%0A          %7D)%0A        %7D%0A        return fields%0A      %7D)%0A
   %7D,

use get_schema rpc in client