Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

@supabase/supabase-js Update

Angelico536ea88f1c85
diff --git a/libraries/supabase-js/package.json b/libraries/supabase-js/package.json
index 485a632af38..9eb6c8a80dc 100644
--- a/libraries/supabase-js/package.json
+++ b/libraries/supabase-js/package.json
@@ -1,6 +1,6 @@
{
"name": "@supabase/supabase-js",
- "version": "0.1.11",
+ "version": "0.1.12",
"description": "Supabase Realtime API",
"main": "./lib/index.js",
"scripts": {
@@ -49,6 +49,7 @@
"rimraf": "^2.6.2"
},
"dependencies": {
+ "@supabase/postgrest-js": "file:../../../../../desktop/supabase/postgrest-js",
"@supabase/realtime-js": "^0.1.6",
"superagent": "^5.2.1"
}
diff --git a/libraries/supabase-js/src/BaseRequest.js b/libraries/supabase-js/src/BaseRequest.js
deleted file mode 100644
index 68d516a818a..00000000000
--- a/libraries/supabase-js/src/BaseRequest.js
+++ /dev/null
@@ -1,225 +0,0 @@
-/**
-* This files draws heavily from https://github.com/calebmer/postgrest-client
-* License: https://github.com/calebmer/postgrest-client/blob/master/LICENSE
-*/
-
-import { Request } from 'superagent'
-import * as Filters from './utils/Filters'
-
-const contentRangeStructure = /^(\d+)-(\d+)\/(\d+)$/
-
-/**
- * A request building object which contains convenience methods for
- * communicating with a PostgREST server.
- *
- * @class
- * @param {string} The HTTP method of the request.
- * @param {string} The path to the request.
- */
-
-class BaseRequest extends Request {
- constructor (method, path) {
- super(method, path)
- this.set('Accept', 'application/json')
-
- this.filterMap = {
- eq: (columnName, criteria) => Filters.Eq(columnName, criteria),
- gt: (columnName, criteria) => Filters.Gt(columnName, criteria),
- lt: (columnName, criteria) => Filters.Lt(columnName, criteria),
- gte: (columnName, criteria) => Filters.Gte(columnName, criteria),
- lte: (columnName, criteria) => Filters.Lte(columnName, criteria),
- like: (columnName, criteria) => Filters.Like(columnName, criteria),
- ilike: (columnName, criteria) => Filters.Ilike(columnName, criteria),
- is: (columnName, criteria) => Filters.Is(columnName, criteria),
- in: (columnName, criteria) => Filters.In(columnName, criteria),
- not: (columnName, criteria) => Filters.Not(columnName, criteria),
- }
-
- // Fix for superagent disconnect on client & server.
- if (!this.get) {
- this.get = this.getHeader
- }
- }
-
- /**
- * Set auth using special formats. If only one string parameter is passed, it
- * is interpreted as a bearer token. If an object and nothing else is passed,
- * `user` and `pass` keys are extracted from it and used for basic auth.
- *
- * @param {string|object} The user, bearer token, or user/pass object.
- * @param {string|void} The pass or undefined.
- * @returns {BaseRequest} The API request object.
- */
-
- auth (user, pass) {
- if (typeof user === 'string' && pass == null) {
- this.set('Authorization', `Bearer ${user}`)
- return this
- }
-
- if (typeof user === 'object' && pass == null) {
- pass = user.pass
- user = user.user
- }
-
- return super.auth(user, pass)
- }
-
- /**
- * All in one conveniencd function for all filters available.
- *
- * @param {string} Name of the database column.
- * @param {string} Name of filter operator be utilised.
- * @param { object | array | string | integer | boolean | null } Value to compare to. Exact data type of criteria would depend on the operator used.
- * @returns {BaseRequest} The API request object.
- */
-
- filter(columnName, operator, criteria){
- let newQuery = this.filterMap[operator.toLowerCase()](columnName, criteria)
- return this.query(newQuery)
- }
-
- /**
- * Takes a query object and translates it to a PostgREST filter query string.
- * All values are prefixed with `eq.`.
- *
- * @param {object} The object to match against.
- * @returns {BaseRequest} The API request object.
- */
-
- match (query) {
- const newQuery = {}
- Object.keys(query).forEach(key => newQuery[key] = `eq.${query[key]}`)
- return this.query(newQuery)
- }
-
- /**
- * Cleans up a select string by stripping all whitespace. Then the string is
- * set as a query string value. Also always forces a root @id column.
- *
- * @param {string} The unformatted select string.
- * @returns {BaseRequest} The API request object.
- */
-
- select (select) {
- if (select) {
- this.query({ select: select.replace(/\s/g, '') })
- }
-
- return this
- }
-
- /**
- * Tells PostgREST in what order the result should be returned.
- *
- * @param {string} The property name to order by.
- * @param {bool} True for descending results, false by default.
- * @param {bool} True for nulls first, false by default.
- * @returns {BaseRequest} The API request object.
- */
-
- order (property, ascending = false, nullsFirst = false) {
- this.query(`order=${property}.${ascending ? 'asc' : 'desc'}.${nullsFirst ? 'nullsfirst' : 'nullslast'}`)
- return this
- }
-
- /**
- * Specify a range of items for PostgREST to return. If the second value is
- * not defined, the rest of the collection will be sent back.
- *
- * @param {number} The first object to select.
- * @param {number|void} The last object to select.
- * @returns {BaseRequest} The API request object.
- */
-
- range (from, to) {
- this.set('Range-Unit', 'items')
- this.set('Range', `${from || 0}-${to || ''}`)
- return this
- }
-
- /**
- * Sets the header which signifies to PostgREST the response must be a single
- * object or 404.
- *
- * @returns {BaseRequest} The API request object.
- */
-
- single () {
- return this.set('Prefer', 'plurality=singular')
- }
-
- /**
- * Sends the request and returns a promise. The super class uses the errback
- * pattern, but this function overrides that preference to use a promise.
- *
- * @returns {Promise} Resolves when the request has completed.
- */
-
- end () {
- return new Promise((resolve, reject) =>
- super.end((error, response) => {
- if (error) {
- return reject(error)
- }
-
- const { body, headers, status, statusCode, statusText } = response
- const contentRange = headers['content-range']
-
- if (Array.isArray(body) && contentRange && contentRangeStructure.test(contentRange)) {
- body.fullLength = parseInt(contentRangeStructure.exec(contentRange)[3], 10)
- }
-
- const returnBody = { body, status, statusCode, statusText}
-
- return resolve(returnBody)
- })
- )
- }
-
- /**
- * Makes the BaseRequest object then-able. Allows for usage with
- * `Promise.resolve` and async/await contexts. Just a proxy for `.then()` on
- * the promise returned from `.end()`.
- *
- * @param {function} Called when the request resolves.
- * @param {function} Called when the request errors.
- * @returns {Promise} Resolves when the resolution resolves.
- */
-
- then (resolve, reject) {
- return this.end().then(resolve, reject)
- }
-
- /**
- * Just a proxy for `.catch()` on the promise returned from `.end()`.
- *
- * @param {function} Called when the request errors.
- * @returns {Promise} Resolves when there is an error.
- */
-
- catch (reject) {
- return this.end().catch(reject)
- }
-}
-
-/**
- * For all of the PostgREST filters add a shortcut method to use it.
- *
- * @param {string} The name of the column.
- * @param { object | array | string | integer | boolean | null } The value of the column to be filtered.
- * @returns {BaseRequest} The API request object.
- */
-
-const filters = ['eq', 'gt', 'lt', 'gte', 'lte', 'like', 'ilike', 'is', 'in', 'not']
-
-filters.forEach(filter =>
- BaseRequest.prototype[filter] = function filterValue (columnName, criteria) {
- return this.filter(columnName, filter, criteria)
- }
-)
-
-export default BaseRequest
-
-
-
diff --git a/libraries/supabase-js/src/Supabase.js b/libraries/supabase-js/src/Supabase.js
index 91e828c24b1..ae46dce92a3 100644
--- a/libraries/supabase-js/src/Supabase.js
+++ b/libraries/supabase-js/src/Supabase.js
@@ -1,5 +1,5 @@
-import BaseRequest from './BaseRequest'
import { Socket } from '@supabase/realtime-js'
+import { PostgrestClient } from '@supabase/postgrest-js'
import * as ChangeMapper from './utils/ChangeMapper'
class Supabase {
@@ -14,8 +14,6 @@ class Supabase {
this.socket = null
this.channel = null
this.listeners = {}
-
- this.queryFilters = []
}
/**
@@ -26,12 +24,7 @@ class Supabase {
let socketUrl = `${this.realtimeUrl}`
let channel = `realtime:${this.schema}:${this.tableName}`
this.socket = new Socket(socketUrl, { params: { apikey: this.apikey } })
- this.channel = this.socket.channel('realtime:*') // @TODO:
-
- // @TODO: remove
- // Example local config
- // this.socket = new Socket(`ws://localhost:80/socket`)
- // this.channel = this.socket.channel('realtime:*')
+ this.channel = this.socket.channel(channel)
this.socket.onOpen(() => {
console.log('REALTIME CONNECTED')
@@ -43,7 +36,6 @@ class Supabase {
on(eventType, callbackFunction) {
if (this.socket == null) this.createListener()
- // var ref = this.channel.on(eventType, callbackFunction)
var ref = this.channel.on(eventType, payload => {
let payloadEnriched = {
@@ -129,144 +121,56 @@ class Supabase {
* REST FUNCTIONALITIES
*/
- request(method) {
- let path = `${this.restUrl}/${this.tableName}?apikey=${this.apikey}`
- return new BaseRequest(method, path)
- }
-
- addFilters(request, options) {
- if (Object.keys(options).length != 0) {
- Object.keys(options).forEach(option => {
- let setting = options[option]
- request.set(option, setting)
- })
- }
-
- // loop through this.queryFilters
- this.queryFilters.forEach(queryFilter => {
- switch (queryFilter.filter) {
- case 'filter':
- request.filter(queryFilter.columnName, queryFilter.operator, queryFilter.criteria)
- break
+ initClient() {
+ let rest = new PostgrestClient(this.restUrl, { apikey: this.apikey })
+ let api = rest.from(this.tableName)
- case 'match':
- request.match(queryFilter.query)
- break
+ return api
+ }
- case 'order':
- request.order(queryFilter.property, queryFilter.ascending, queryFilter.nullsFirst)
- break
+ select(columnQuery = '*', options = {}) {
+ let api = this.initClient()
+ return api.select(columnQuery, options)
+ }
- case 'range':
- request.range(queryFilter.from, queryFilter.to)
- break
+ insert(data, options = {}) {
+ let api = this.initClient()
+ return api.insert(data, options)
+ }
- case 'single':
- request.single()
- break
+ update(data, options = {}) {
+ let api = this.initClient()
+ return api.update(data, options)
+ }
- default:
- break
- }
- })
+ delete(options = {}) {
+ let api = this.initClient()
+ return api.delete(options)
}
filter(columnName, operator, criteria) {
- this.queryFilters.push({
- filter: 'filter',
- columnName,
- operator,
- criteria,
- })
-
- return this
+ let api = this.initClient()
+ return api.filter(columnName, operator, criteria)
}
match(query) {
- this.queryFilters.push({
- filter: 'match',
- query,
- })
-
- return this
+ let api = this.initClient()
+ return api.match(query)
}
order(property, ascending = false, nullsFirst = false) {
- this.queryFilters.push({
- filter: 'order',
- property,
- ascending,
- nullsFirst,
- })
-
- return this
+ let api = this.initClient()
+ return api.order(property, ascending, nullsFirst)
}
range(from, to) {
- this.queryFilters.push({
- filter: 'range',
- from,
- to,
- })
-
- return this
+ let api = this.initClient()
+ return api.range(from, to)
}
single() {
- this.queryFilters.push({ filter: 'single' })
-
- return this
- }
-
- select(columnQuery = '*', options = {}) {
- let method = 'get'
- let request = this.request(method)
-
- request.select(columnQuery)
- this.addFilters(request, options)
-
- return request
- }
-
- insert(data, options = {}) {
- let method = 'post'
- let request = this.request(method)
-
- if (!Array.isArray(data)) {
- return {
- body: null,
- status: 400,
- statusCode: 400,
- statusText: 'Data type should be an array.',
- }
- }
-
- data.forEach(datum => {
- request.send(datum)
- })
-
- this.addFilters(request, options)
-
- return request
- }
-
- update(data, options = {}) {
- let method = 'patch'
- let request = this.request(method)
-
- request.send(data)
- this.addFilters(request, options)
-
- return request
- }
-
- delete(options = {}) {
- let method = 'delete'
- let request = this.request(method)
-
- this.addFilters(request, options)
-
- return request
+ let api = this.initClient()
+ return api.single()
}
}
@@ -276,8 +180,7 @@ const advancedFilters = ['eq', 'gt', 'lt', 'gte', 'lte', 'like', 'ilike', 'is',
advancedFilters.forEach(
operator =>
(Supabase.prototype[operator] = function filterValue(columnName, criteria) {
- this.filter(columnName, operator, criteria)
- return this
+ return this.filter(columnName, operator, criteria)
})
)
diff --git a/libraries/supabase-js/src/index.js b/libraries/supabase-js/src/index.js
index 8a09e640751..4a8ad0db459 100644
--- a/libraries/supabase-js/src/index.js
+++ b/libraries/supabase-js/src/index.js
@@ -1,6 +1,6 @@
import { uuid } from './utils/Helpers'
import Supabase from './Supabase'
-import BaseRequest from './BaseRequest'
+import { PostgrestClient } from '@supabase/postgrest-js'
class SupabaseClient {
constructor(supabaseUrl, supabaseKey, options = {}) {
@@ -14,16 +14,16 @@ class SupabaseClient {
this.authenticate(supabaseUrl, supabaseKey)
}
- authenticate(supabaseUrl, supabaseKey){
+ authenticate(supabaseUrl, supabaseKey) {
this.supabaseUrl = supabaseUrl
this.supabaseKey = supabaseKey
this.restUrl = `${supabaseUrl}/rest/v1`
this.realtimeUrl = `${supabaseUrl}/realtime/v1`.replace('http', 'ws')
}
- from(tableName){
+ from(tableName) {
let identifier = uuid()
-
+
this.subscriptions[identifier] = new Supabase(
tableName,
this.restUrl,
@@ -35,20 +35,15 @@ class SupabaseClient {
return this.subscriptions[identifier]
}
- rpc(functionName, functionParameters = null){
- let path =`${this.restUrl}/rpc/${functionName}?apikey=${this.supabaseKey}`
- let request = new BaseRequest('post', path)
-
- if(functionParameters != null) request.send(functionParameters)
-
- return request
+ rpc(functionName, functionParameters = null) {
+ let rest = new PostgrestClient(this.restUrl, { apikey: this.supabaseKey })
+ return rest.rpc(functionName, functionParameters)
}
- removeSubscription(mySubscription){
+ removeSubscription(mySubscription) {
mySubscription.unsubscribe()
delete this.subscriptions[mySubscription.uuid]
}
-
}
const createClient = (supabaseUrl, supabaseKey, options = {}) => {
diff --git a/libraries/supabase-js/src/utils/Filters.js b/libraries/supabase-js/src/utils/Filters.js
deleted file mode 100644
index 5a1caafba66..00000000000
--- a/libraries/supabase-js/src/utils/Filters.js
+++ /dev/null
@@ -1,43 +0,0 @@
-export function Eq(columnName, filterValue) {
- return `${columnName}=eq.${filterValue}`
-}
-
-export function Gt(columnName, filterValue) {
- return `${columnName}=gt.${filterValue}`
-}
-
-export function Lt(columnName, filterValue) {
- return `${columnName}=lt.${filterValue}`
-}
-
-export function Gte(columnName, filterValue) {
- return `${columnName}=gte.${filterValue}`
-}
-
-export function Lte(columnName, filterValue) {
- return `${columnName}=lte.${filterValue}`
-}
-
-export function Like(columnName, stringPattern) {
- let stringPatternEnriched = stringPattern.replace(/%/g, '*')
-
- return `${columnName}=like.${stringPatternEnriched}`
-}
-
-export function Ilike(columnName, stringPattern) {
- let stringPatternEnriched = stringPattern.replace(/%/g, '*')
-
- return `${columnName}=ilike.${stringPatternEnriched}`
-}
-
-export function Is(columnName, filterValue) {
- return `${columnName}=is.${filterValue}`
-}
-
-export function In(columnName, filterArray) {
- return `${columnName}=in.${filterArray.join(',')}`
-}
-
-export function Not(columnName, filterValue) {
- return `${columnName}=not.${filterValue}`
-}