Skip to content

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

Rewrite Client Library

Angelicoe316b65791ee
diff --git a/libraries/supabase-js/package.json b/libraries/supabase-js/package.json
index 2662b39d3c0..aa027d4e575 100644
--- a/libraries/supabase-js/package.json
+++ b/libraries/supabase-js/package.json
@@ -46,5 +46,9 @@
"mocha": "^6.1.3",
"nyc": "^13.3.0",
"rimraf": "^2.6.2"
+ },
+ "dependencies": {
+ "phoenix-channels": "^1.0.0",
+ "superagent": "^5.2.1"
}
}
diff --git a/libraries/supabase-js/src/BaseChannel.js b/libraries/supabase-js/src/BaseChannel.js
new file mode 100644
index 00000000000..40e55f48f5a
--- /dev/null
+++ b/libraries/supabase-js/src/BaseChannel.js
@@ -0,0 +1,59 @@
+import { Socket } from 'phoenix-channels'
+
+export default class BaseChannel {
+ constructor(tableName, apiSocket){
+ this.socket = new Socket(apiSocket)
+ this.channel = this.socket.channel(tableName)
+ this.listeners = {}
+
+ this.start()
+
+ this.socket.onOpen(() => {
+ console.log('Socket connected')
+ })
+ this.socket.onClose(() => {
+ console.log('Socket disconnected')
+ })
+ }
+
+ on(eventName, callbackFunction){
+ let ref = this.channel.on(eventName, callbackFunction)
+ this.listeners[ref] = eventName
+ return ref
+ }
+
+ off(eventName, ref = null){
+ // if ref is null, we just want to remove everything that has the eventName
+ if(typeof ref === 'null'){
+ for (var ref in this.listeners){
+ let eventNameValue = this.listeners[ref]
+ if(eventName === eventNameValue){
+ this.off(eventName, ref)
+ }
+ }
+ }
+
+ this.channel.off(eventName, ref)
+ }
+
+ start(){
+ this.socket.connect()
+
+ if(this.channel.state !== 'joined'){
+ this.channel
+ .join()
+ .receive('ok', resp => console.log('Joined Realtime successfully ', resp))
+ .receive('error', resp => console.log('Unable to join ', resp))
+ .receive('timeout', () => console.log('Networking issue. Still waiting...'))
+ }
+ }
+
+ stop(){
+ for (var ref in this.listeners){
+ let eventName = this.listeners[ref]
+ this.off(eventName, ref)
+ }
+
+ this.socket.disconnect()
+ }
+}
\ No newline at end of file
diff --git a/libraries/supabase-js/src/BaseRequest.js b/libraries/supabase-js/src/BaseRequest.js
new file mode 100644
index 00000000000..4ef6860aa28
--- /dev/null
+++ b/libraries/supabase-js/src/BaseRequest.js
@@ -0,0 +1,195 @@
+/**
+* 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'
+
+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')
+
+ // Fix for superagent disconnect on client & server.
+ if (!this.get) {
+ this.get = this.getHeader
+ }
+ }
+
+ /**
+ * Set auth using special formats. If only one string paramter 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 {ApiRequest} 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)
+ }
+
+ /**
+ * 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 {ApiRequest} 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 {ApiRequest} 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 {ApiRequest} 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 {ApiRequest} 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 {ApiRequest} 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 } = response
+ const contentRange = headers['content-range']
+
+ if (Array.isArray(body) && contentRange && contentRangeStructure.test(contentRange)) {
+ body.fullLength = parseInt(contentRangeStructure.exec(contentRange)[3], 10)
+ }
+
+ return resolve(body)
+ })
+ )
+ }
+
+ /**
+ * Makes the ApiRequest 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 {any} The value of the column to be filtered.
+ * @returns {ApiRequest} The API request object.
+ */
+
+const filters = ['eq', 'gt', 'lt', 'gte', 'lte', 'like', 'ilike', 'is', 'in', 'not']
+
+filters.forEach(filter =>
+ ApiRequest.prototype[filter] = function filterValue (name, value) {
+ return this.query(`${name}=${filter}.${Array.isArray(value) ? value.join(',') : value}`)
+ }
+)
+
+export default BaseRequest
+
+
+
diff --git a/libraries/supabase-js/src/index.js b/libraries/supabase-js/src/index.js
index 65428c0e94e..f6c877dcd8d 100644
--- a/libraries/supabase-js/src/index.js
+++ b/libraries/supabase-js/src/index.js
@@ -1,53 +1,69 @@
-
+import BaseRequest from './BaseRequest'
class SupabaseClient {
constructor(supbaseUrl, supabaseKey, options) {
- this.listeners = []
- this.supbaseUrl = supbaseUrl
+ this.supabaseUrl = supabaseUrl
this.supabaseKey = supabaseKey
+
+ // this will be the case for now
+ this.restUrl = supabaseUrl
+ this.apiSocket = ''
}
/**
* @todo
*/
- subscribe () {
- this.listeners.push()
+ subscribe (tableName) {
+ return new BaseChannel(tableName, this.apiSocket)
+ }
+
+ /**
+ * Convenience wrapper for starting a PostgREST request builder. Adds the
+ * API URL to the provided path.
+ *
+ * @param {string} The HTTP method of the request.
+ * @param {string} The path of the request.
+ * @returns {BaseRequest} The API request object.
+ */
+
+ request (method, path) {
+ return new BaseRequest(method, this.restUrl + path)
}
}
/**
- * Instantiate a new Supabase Client
- * @param supbaseUrl
- * @param supabaseKey
- * @param options
+ * Basic HTTP method functions for quick chaining.
+ *
+ * @param {string} The path of the request.
+ * @returns {BaseRequest} The API request object.
*/
-const createClient = (supbaseUrl, supabaseKey, options = {}) => {
- return new SupabaseClient(supbaseUrl, supabaseKey, options)
-}
-export { createClient }
+const methods = ['POST', 'GET', 'PATCH', 'PUT', 'DELETE']
+
+methods.forEach(method =>
+ SupabaseClient.prototype[method.toLowerCase()] = tableName => {
+ path = `/${tableName}`
+ return this.request(method, path)
+ }
+)
+const createClient = (supabaseUrl, supabaseKey, options = {}) => {
+ return new SupabaseClient(supabseUrl, supabaseKey, options)
+}
+export { createClient }
/**
- *
- *
- *
- *
- * REMOVE BELOW
- *
- *
- *
- *
- *
+ * TO BE REMOVED SOON
*/
-const defaultAwesomeFunction = (name) => {
- const returnStr = `I am the Default Awesome Function, fellow comrade! - ${name}`;
- return returnStr;
-};
-const awesomeFunction = () => 'I am just an Awesome Function';
+// const defaultAwesomeFunction = (name) => {
+// const returnStr = `I am the Default Awesome Function, fellow comrade! - ${name}`;
+// return returnStr;
+// };
+
+// const awesomeFunction = () => 'I am just an Awesome Function';
-export default defaultAwesomeFunction;
+// export default defaultAwesomeFunction;
-export { awesomeFunction };
+// export { awesomeFunction };