Coder Social home page Coder Social logo

functions-js's Introduction

Supabase

Supabase is an open source Firebase alternative. We're building the features of Firebase using enterprise-grade open source tools.

  • Hosted Postgres Database. Docs
  • Authentication and Authorization. Docs
  • Auto-generated APIs.
  • Functions.
    • Database Functions. Docs
    • Edge Functions Docs
  • File Storage. Docs
  • AI + Vector/Embeddings Toolkit. Docs
  • Dashboard

Supabase Dashboard

Watch "releases" of this repo to get notified of major updates.

Watch this repo

Documentation

For full documentation, visit supabase.com/docs

To see how to Contribute, visit Getting Started

Community & Support

  • Community Forum. Best for: help with building, discussion about database best practices.
  • GitHub Issues. Best for: bugs and errors you encounter using Supabase.
  • Email Support. Best for: problems with your database or infrastructure.
  • Discord. Best for: sharing your applications and hanging out with the community.

How it works

Supabase is a combination of open source tools. We’re building the features of Firebase using enterprise-grade, open source products. If the tools and communities exist, with an MIT, Apache 2, or equivalent open license, we will use and support that tool. If the tool doesn't exist, we build and open source it ourselves. Supabase is not a 1-to-1 mapping of Firebase. Our aim is to give developers a Firebase-like developer experience using open source tools.

Architecture

Supabase is a hosted platform. You can sign up and start using Supabase without installing anything. You can also self-host and develop locally.

Architecture

  • Postgres is an object-relational database system with over 30 years of active development that has earned it a strong reputation for reliability, feature robustness, and performance.
  • Realtime is an Elixir server that allows you to listen to PostgreSQL inserts, updates, and deletes using websockets. Realtime polls Postgres' built-in replication functionality for database changes, converts changes to JSON, then broadcasts the JSON over websockets to authorized clients.
  • PostgREST is a web server that turns your PostgreSQL database directly into a RESTful API
  • GoTrue is a JWT based API for managing users and issuing JWT tokens.
  • Storage provides a RESTful interface for managing Files stored in S3, using Postgres to manage permissions.
  • pg_graphql a PostgreSQL extension that exposes a GraphQL API
  • postgres-meta is a RESTful API for managing your Postgres, allowing you to fetch tables, add roles, and run queries, etc.
  • Kong is a cloud-native API gateway.

Client libraries

Our approach for client libraries is modular. Each sub-library is a standalone implementation for a single external system. This is one of the ways we support existing tools.

Language Client Feature-Clients (bundled in Supabase client)
Supabase PostgREST GoTrue Realtime Storage Functions
⚡️ Official ⚡️
JavaScript (TypeScript) supabase-js postgrest-js gotrue-js realtime-js storage-js functions-js
Flutter supabase-flutter postgrest-dart gotrue-dart realtime-dart storage-dart functions-dart
Swift supabase-swift postgrest-swift auth-swift realtime-swift storage-swift functions-swift
Python supabase-py postgrest-py gotrue-py realtime-py storage-py functions-py
💚 Community 💚
C# supabase-csharp postgrest-csharp gotrue-csharp realtime-csharp storage-csharp functions-csharp
Go - postgrest-go gotrue-go - storage-go functions-go
Java - - gotrue-java - storage-java -
Kotlin supabase-kt postgrest-kt gotrue-kt realtime-kt storage-kt functions-kt
Ruby supabase-rb postgrest-rb - - - -
Rust - postgrest-rs - - - -
Godot Engine (GDScript) supabase-gdscript postgrest-gdscript gotrue-gdscript realtime-gdscript storage-gdscript functions-gdscript

Badges

Made with Supabase

[![Made with Supabase](https://supabase.com/badge-made-with-supabase.svg)](https://supabase.com)
<a href="https://supabase.com">
  <img
    width="168"
    height="30"
    src="https://supabase.com/badge-made-with-supabase.svg"
    alt="Made with Supabase"
  />
</a>

Made with Supabase (dark)

[![Made with Supabase](https://supabase.com/badge-made-with-supabase-dark.svg)](https://supabase.com)
<a href="https://supabase.com">
  <img
    width="168"
    height="30"
    src="https://supabase.com/badge-made-with-supabase-dark.svg"
    alt="Made with Supabase"
  />
</a>

Translations

functions-js's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

functions-js's Issues

Unable to upload 10MB files using Functions

Bug report

  • I confirm this is a bug with Supabase, not with my own application.
  • I confirm I have searched the Docs, GitHub Discussions, and Discord.

Describe the bug

Getting error while trying to upload heavy File using Edge Functions. It works fine with files <=5 MB and it fails with files of around 9/10+ MBs.

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Create a function that expects a Files
  2. run it and pass in a File (you can use Postman)
  3. See error

Expected behavior

File is received

Current behavior: crash

[Info] PARSING FILE...

CPU time limit reached. isolate: 3328699061268672774
event loop error: Uncaught Error: execution terminated
Error in worker connection: error writing a body to connection: Broken pipe (os error 32)
failed to send request to user worker: connection error: Connection reset by peer (os error 104)
InvalidWorkerResponse: user worker failed to respond
    at async UserWorker.fetch (ext:sb_user_workers/user_workers.js:52:15)
    at async Server.<anonymous> (file:///home/deno/main/index.ts:123:12)
    at async Server.#respond (https://deno.land/[email protected]/http/server.ts:220:18) {
  name: "InvalidWorkerResponse"
}
event loop error: TypeError: request body receiver not connected (request closed)
    at async Object.write (ext:deno_web/06_streams.js:954:9)
Error in worker connection: error writing a body to connection: Broken pipe (os error 32)
request failed (uri: "/create_chat" reason: hyper::Error(Io, Os { code: 104, kind: ConnectionReset, message: "Connection reset by peer" }))

System information

  • OS: [macOS]
  • Version of supabase-js: [2.4.0]

Piece of code to extract file from formData:

  console.log('PARSING FILE...')
  const body = ctx.request.body({ type: "form-data" });
  const maxFileSizeForFreeVersion = 15;

  const formData = await body.value.read({
    // Need to set the maxSize so files will be stored in memory.
    // This is necessary as Edge Functions don't have disk write access.
    // We are setting the max size as 10MB (an Edge Function has a max memory limit of 150MB)
    // For more config options, check: https://deno.land/x/[email protected]/mod.ts?s=FormDataReadOptions
    maxSize: maxFileSizeForFreeVersion * MB,
    maxFileSize: maxFileSizeForFreeVersion * MB,
    bufferSize: maxFileSizeForFreeVersion * MB
  });
  console.log('PARSING FILE - ERROR')

Modification proposal for the invoke() prototype

Feature request

Is your feature request related to a problem? Please describe.

This feature request is to propose a breaking change to the prototype of invoke() that would:

  • reduce boilerplate for newer folks
  • be opinionated by default but still provide full-powered low-level access on option
  • be syntactically consistent with the from, rpc, storage, and auth APIs

Describe the solution you'd like

The invoke() prototype would look like:

const { data: any, error: FunctionsError } = await invoke(functionName: string, input: any, options?: {requestTransform, responseTransform})

Describe alternatives you've considered

The alternatives are described in greater detail in the conversation of PR #21, but in summary:

  1. The first option would be to move the behavior of invoke closer to that of fetch, but the issue would then be to increase the amount of boilerplate necessary to use the function.
  2. The second option would be to move the behavior of invoke closer to that of Firebase's httpsCallable, but the issue would then be to limit the type of data that can be sent and received to only JSON objects (therefore excluding Files and Blobs for instance).

This proposal is a tentative for a best of both worlds approach, where common data types can be automatically serialized and de-serialized by invoke and therefore reduces the boilerplate for the most common use cases, while also allowing to have full low-level access to the underlying Fetch API if required, via the options parameter callbacks.

Additional context

An implementation proposal is linked to this feature as PR #23
A detailed explanation of the new behavior of invoke is provided in the README.md file of the PR.

Docker build failed with Type Error

Bug report

  • I confirm this is a bug with Supabase, not with my own application.
  • I confirm I have searched the Docs, GitHub Discussions, and Discord.

Describe the bug

It is a Typescript syntax error with isolatedModules on

To Reproduce

I was building a docker image for my application using this template on NextJS docs

Building a NextJS app with supabase should raise this error
This is my code My Code.

Expected behavior

Expected it to build when the Dockerfile ran next build

Screenshots

This is the error I got from docker build
https://drive.google.com/file/d/1HRU_2bOrK5zQPGKvxAIPZ52_TPAv9NO9/view?usp=sharing

System information

  • OS: Linux 18.04
  • Version of supabase-js: ^2.24.0
  • Version of Node.js: 18.16.0

Additional context

I am using NextJS with TypeScript+SWC.
I tried setting isolatedModules to false, but when I ran npm run build it set it back to true

Non-200 status Responses do not expose message

Bug report

  • I confirm this is a bug with Supabase, not with my own application.
  • I confirm I have searched the Docs, GitHub Discussions, and Discord.

Describe the bug

When returning responses from Edge Functions, Documentation suggests new Response('..', {status: 200}). This works fine as one can see the success message in the data var. When returning a Response with a non-200 status code, the message is not available to the client.

edge func:

    return new Response(
      JSON.stringify({ success: `all went through smoothly!` }),
      {
        status: 200, // 200 or 400
      },
    );

client:

    const { data, error } = await supabase.from('table').select('*').eq('id', id);

When it is a 200 response, data will display the message but when it is non-200 (eg 400), the error var does not show the message - it only returns a generic message:

FunctionsHttpError: Edge Function returned a non-2xx status code

To Reproduce

Explained above.

Expected behavior

error to contain whatever message is added to the Response object.

System information

  • OS: macOS
  • Version of supabase-js: "@supabase/supabase-js": "^2.20.0"
  • Version of Node.js: v16.17.1

Support multiple content types or allow custom response handling

Bug report

  • I confirm this is a bug with Supabase, not with my own application.
  • I confirm I have searched the Docs, GitHub Discussions, and Discord.

Describe the bug

Currently, @supabase/functions-js package automatically handles JSON/text/multipart-form/blob parsing. However, this is done simply by checking if Content-Type if one of three predefined options (see functions-js source code). In all other cases, response is converted to text.

Example

Supabase has defined following edge function:

// read-pdf-file
serve(async (req) => {
  // read pdf file from S3 storage and return it as a response
  const pdfFile: Blob = ...
  return new Response(
    pdfFile,
    {
      headers: {
        // set correct content type
        "Content-Type": "application/pdf",
      },
    },
  );
});

When this function is invoked via Supabase client:

const { data } = await client.functions.invoke(f, { method: 'GET' });
// data is of type string, but should be Blob

As application/pdf is not one of three predefined content types, response is converted to text (in this line).

I know it is impossible to handle all possible content types, but defaulting to text might not be the best idea. Maybe you could add something like customResponseParser, which could be handled in a similar way to customFetch option already provided.

Does this make sense or am I missing something?

Negative tests for edge functions with Deno

Bug report

  • I confirm this is a bug with Supabase, not with my own application.
  • I confirm I have searched the Docs, GitHub Discussions, and Discord.

Describe the bug

I am trying to write some negative tests for my edge functions, for example:

const testSomeFunction = async () => {
  const { data, error } = await supabaseUser.functions.invoke('some-function', {
    body: {
      userId: 'invalid-id'
    }
  })

  assertEquals(error.message, 'Edge Function returned a non-2xx status code')
  assertEquals(data, null)
}

But when running deno test, the test fails with:

error: Leaking resources:
  - A fetch response body (rid 18) was created during the test, but not consumed during the test. Consume or close the response body `ReadableStream`, e.g `await resp.text()` or `await resp.body.cancel()`.

But I cannot access the response to consume/close/cancel/... it.

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Create edge function
  2. Create negative test for edge function
  3. Run deno test

Expected behavior

I expect the test to pass, without any leaking resources.

System information

  • OS: Windows 11
  • Version of supabase-js: 2.26.0
  • Version of Node.js: 18.15.0
  • Version of Deno: 1.36.2

Support for Invoking Edge Functions Returning a server-sent events in client library.

Is your feature request related to a problem? Please describe.
Yes. Currently, there seems to be no possibility to invoke an Edge Function that returns a server-sent events using the client library.

Describe the solution you'd like
I would like to see the implementation of an additional function, which could return a Stream of server-sent events instead of standard promise.

Describe alternatives you've considered
One alternative I considered was to simply await the full result. However, this would leave the user waiting for a long period, which is not an ideal user experience.

Additional context
The motivation is a project, where we are looking to implement a ChatGPT interface within our Flutter application, and we need to stream the response of the API call to OpenAI to the user in real-time.

Implementing this functionality on the backend as an Edge Function was straightforward enough - I followed the tutorial on Streaming Data in Edge Functions by Supabase (https://www.youtube.com/watch?v=9N66JBRLNYU).

The automated release is failing 🚨

🚨 The automated release from the main branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot 📦🚀

shouldThrowOnError does not apply to functions.invoke()

Bug report

Describe the bug

When shouldThrowOnError is set on supabaseClient, errors raised from functions.invoke() do not throw.

Additional context

@supabase/functions uses the standard fetch API, which does not throw on HTTP status codes other than 2xx; in addition the wrapper does not return the HTTP status code in the response object which is always in the form { data, error }.

For instance, if the Edge Function was written to reject some unauthorized request by returning a 403 Forbidden response, it is impossible to catch this condition.
In other words, supabaseClient always returns { data, error: null }, even when the HTTP status code indicates an error (unless of course if fetch itself threw in the first place).

This forces the user to provide an additional 'httpError' key in the 'data' object, which feels convoluted and obliges to check errors at two different levels (in error and in data.httpError).

Proposed improvement

Modify the code of @supabase/functions:
1- Detect http status codes other than 2xx, and populate the error property in that case together with the status code, instead of populating the data property
2- Add an option to the invoke() function parameters to pass a shouldThrowOnError boolean flag. If set, throw rather than returning the { data, error } object

I can submit a PR if the above makes sense.

Body does not seem properly formated and cors error

Bug report

The documentation shows calling a function as:

const { data: user, error } = await supabase.functions.invoke('hello', {
  responseType: 'text',
  body: { foo: 'bar' }
})

The function.js code has

const response = await this.fetch(`${this.url}/${functionName}`, {
        method: 'POST',
        headers: Object.assign({}, this.headers, headers),
        body,
      })

I would think at a minimum body should be body:body.
Very strange results occur, but basically content length is string length if {body:'string'} is used in call.
If an object is used {body:{k:'v'}, length is always 15 probably an error message for invalid object or something...

Not sure if it is related. But all calls generate cors errors:

image

To Reproduce

Follow the instructions for functions invoke in api reference.

Expected behavior

Body should be formatted correctly and no cors error (if not related)

System information

Latest supabase.js

supabase.functions.invoke returns null data when response is non-2xxx

Bug report

Describe the bug

When calling supabase.functions.invoke to a function that responds with non-2xx status code following error is returned with null data:

FunctionsHttpError: Edge Function returned a non-2xx status code

Supabase gives full freedom on how Edge Functions are implemented without enforcing any schema. However, supabase-js is enforcing some response schema because it discards response body when status is non-2xx.

To Reproduce

  1. Deploy Edge functions that returns
return new Response("Malformed request", { headers: { status: Status.BadRequest } })
  1. Call supabase.functions.invoke to it and see that data is null.

Expected behavior

data is available when Edge Functions responds with non-2xx response.

Calling `invoke` via Android OS without specifying `content-type` header results in a failed request

Bug report

Describe the bug

If calling invoke using the example syntax from Android context, it results in a in a "Network Request Failed" from fetch. The actual error within fetch is { "isTrusted": false } (note: the request was https with valid certs)

I happened to be using supabase-js within a React-Native application and only encountered the problem on Android (not iOS)

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Create an edge function
  2. Create an Android application using supabase-js
  3. Call supabase.functions.invoke(<functionname>, { body: JSON.stringify({foo: 'bar' })); (per the docs)
  4. Notice the error

Expected behavior

The request is sent properly

Screenshots

If applicable, add screenshots to help explain your problem.

System information

  • OS: [e.g. macOS, Windows]: Android 10
  • Browser (if applies) [e.g. chrome, safari]
  • Version of supabase-js: 1.33.3
  • Version of Node.js: 16.4.2

Additional context

Manually defining the "Content-Type": "application/json" header solves the problem. However, maybe the FunctionInvokeOptions could have a default value for Content-Type header. Or maybe the docs could hint at the issue. Just looking out for any future developer who may run into this same issue. If you think that's alright, let me know and I'd be happy to make a PR for either.

Thanks!

Edge functions/Deno not supporting scheme 'postgres'

Bug report

  • [ ✅ ] I confirm this is a bug with Supabase, not with my own application.
  • [ ✅ ] I confirm I have searched the Docs, GitHub Discussions, and Discord.

Describe the bug

I'm unable to use the supabase-js client to access my database in an edge function using Deno.

To Reproduce

To reproduce, create a new Edge function, this is the function I was using below:

import { Configuration, OpenAIApi } from "openai";
import { createClient } from "@supabase/supabase-js";

const supabaseUrl = Deno.env.get("SUPABASE_DB_URL");
const supabaseKey = Deno.env.get("SUPABASE_ANON_KEY");
export const supabaseClient = createClient(supabaseUrl, supabaseKey);


const configuration = new Configuration({ apiKey:  Deno.env.get("OPEN_AI_KEY" });
const openAi = new OpenAIApi(configuration);

const documents = [
  "Zach loves long walks on the beach",
  "Zach loves ice cream, especially vanilla ice cream",
  "In Zach's free time he likes to rock climb, the highest grade he can do is around a V5, he's still learning!",
];

// Assuming each document is a string
for (const document of documents) {
  // OpenAI recommends replacing newlines with spaces for best results
  const input = document.replace(/\n/g, " ");

  const embeddingResponse = await openAi.createEmbedding({
    model: "text-embedding-ada-002",
    input,
  });

  const [{ embedding }] = embeddingResponse.data.data;

  // In production we should handle possible errors
  await supabaseClient.from("documents").insert({
    content: document,
    embedding,
  });
}

You can use this function or some other function that just inserts data into any table, but I'm not able to add any data through the edge functions.

Try deploying this as a Supabase edge function and invoking it. When I invoke it I get this error:

{
  message: "TypeError: scheme 'postgres' not supported",
  details: "TypeError: scheme 'postgres' not supported\n" +
    "    at opFetch (ext:deno_fetch/26_fetch.js:73:14)\n" +
    "    at "... 504 more characters,
  hint: "",
  code: ""
} error

Expected behavior

I expected the edge function to insert the data correctly, but no data was inserted into the DB, and the function errored out on the first document. I'm not sure if I'm doing this correctly, but this was following a guide to create embeddings in a normal Typescript file, I wanted to extend that to making an Edge function to do that. If that isn't possible then I was unaware and I can work with it some other way.

Screenshots

If applicable, add screenshots to help explain your problem.

System information

  • OS: MacOS
  • Browser (if applies) N/A
  • Version of supabase-js: 2.25.0
  • Version of Deno: 1.34.3

Additional context

Add any other context about the problem here.

Edge function with non 200 response doesn't include response body

Bug report

Describe the bug

When I try to return an error response I get this error:

FunctionsHttpError: Edge Function returned a non-2xx status code

but the response body that I sent from the function is not included.

I try to return the error like this:

...
} catch (error) {
    return new Response(JSON.stringify({
      error: error.message
    }), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      status: 500,
    })
  }

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Setup a new edge function with a non 200 response
  2. Start function local
  3. try to call the function via the supabase sdk
  4. See the error

Expected behavior

I expected to get the error message back that I set in the response body.

Screenshots

If applicable, add screenshots to help explain your problem.

System information

  • OS: macOS
  • Browser: chrome
  • Version of supabase-js: 2.8.0
  • Version of Node.js: 19.6.0

Additional context

Add any other context about the problem here.

`super` keyword type error

Bug report

  • I confirm this is a bug with Supabase, not with my own application.
  • I confirm I have searched the Docs, GitHub Discussions, and Discord.

Describe the bug

When trying to compile our Next.js app which uses the supabase client, we are getting the following build/lint error:

./node_modules/@supabase/functions-js/src/types.ts:21:11
Type error: Only public and protected base class methods are accessible via the 'super' keyword.

  19 |   constructor(message: string, name = 'FunctionsError', context?: any) {
  20 |     super(message)
> 21 |     super.name = name
     |           ^
  22 |     this.context = context
  23 |   }
  24 | }

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. N/A

Expected behavior

No type errors occur.

Im sure the fix is:

//replace 
super.name = name 

// with
this.name = name

Screenshots

If applicable, add screenshots to help explain your problem.

System information

  • Version of supabase-js: 2.24.0

Additional context

Add any other context about the problem here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.