supabase

package module
v0.6.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 3, 2025 License: MIT Imports: 21 Imported by: 0

README

supabase-go

This fork adds Realtime support to the original repository. The original project was looking for a new home.

Unofficial Supabase client for Go. It is an amalgamation of all the libraries similar to the official Supabase client.

Installation

go get github.com/the-muppet/supabase-go

Usage

Replace the <SUPABASE-URL> and <SUPABASE-KEY> placeholders with values from https://supabase.com/dashboard/project/YOUR_PROJECT/settings/api

Authenticate
package main
import (
    "fmt"
    "context"
    
    supa "github.com/the-muppet/supabase-go"
)

func main() {
  supabaseUrl := "<SUPABASE-URL>"
  supabaseKey := "<SUPABASE-KEY>"
  supabase := supa.CreateClient(supabaseUrl, supabaseKey)

  ctx := context.Background()
  user, err := supabase.Auth.SignUp(ctx, supa.UserCredentials{
    Email:    "example@example.com",
    Password: "password",
  })
  if err != nil {
    panic(err)
  }

  fmt.Println(user)
}
Sign-In
package main
import (
    "fmt"
    "context"
    
    supa "github.com/the-muppet/supabase-go"
)

func main() {
  supabaseUrl := "<SUPABASE-URL>"
  supabaseKey := "<SUPABASE-KEY>"
  supabase := supa.CreateClient(supabaseUrl, supabaseKey)

  ctx := context.Background()
  user, err := supabase.Auth.SignIn(ctx, supa.UserCredentials{
    Email:    "example@example.com",
    Password: "password",
  })
  if err != nil {
    panic(err)
  }

  fmt.Println(user)
}
Insert
package main
import (
    "fmt"
    
    supa "github.com/the-muppet/supabase-go"
)

type Country struct {
  ID      int    `json:"id"`
  Name    string `json:"name"`
  Capital string `json:"capital"`
}

func main() {
  supabaseUrl := "<SUPABASE-URL>"
  supabaseKey := "<SUPABASE-KEY>"
  supabase := supa.CreateClient(supabaseUrl, supabaseKey)

  row := Country{
    ID:      5,
    Name:    "Germany",
    Capital: "Berlin",
  }

  var results []Country
  err := supabase.DB.From("countries").Insert(row).Execute(&results)
  if err != nil {
    panic(err)
  }

  fmt.Println(results) // Inserted rows
}
Select
package main
import (
    "fmt"
    
    supa "github.com/the-muppet/supabase-go"
)

func main() {
  supabaseUrl := "<SUPABASE-URL>"
  supabaseKey := "<SUPABASE-KEY>"
  supabase := supa.CreateClient(supabaseUrl, supabaseKey)

  var results map[string]interface{}
  err := supabase.DB.From("countries").Select("*").Single().Execute(&results)
  if err != nil {
    panic(err)
  }

  fmt.Println(results) // Selected rows
}
Update
package main
import (
    "fmt"
    
    supa "github.com/the-muppet/supabase-go"
)

type Country struct {
  Name    string `json:"name"`
  Capital string `json:"capital"`
}

func main() {
  supabaseUrl := "<SUPABASE-URL>"
  supabaseKey := "<SUPABASE-KEY>"
  supabase := supa.CreateClient(supabaseUrl, supabaseKey)

  row := Country{
    Name:    "France",
    Capital: "Paris",
  }

  var results map[string]interface{}
  err := supabase.DB.From("countries").Update(row).Eq("id", "5").Execute(&results)
  if err != nil {
    panic(err)
  }

  fmt.Println(results) // Updated rows
}
Delete
package main
import (
    
    "fmt"

    supa "github.com/the-muppet/supabase-go"
)

func main() {
  supabaseUrl := "<SUPABASE-URL>"
  supabaseKey := "<SUPABASE-KEY>"
  supabase := supa.CreateClient(supabaseUrl, supabaseKey)

  var results map[string]interface{}
  err := supabase.DB.From("countries").Delete().Eq("name", "France").Execute(&results)
  if err != nil {
    panic(err)
  }

  fmt.Println(results) // Empty - nothing returned from delete
}
Invite user by email
package main
import (
    
    "fmt"
    "context"

    supa "github.com/the-muppet/supabase-go"
)

func main() {
  supabaseUrl := "<SUPABASE-URL>"
  supabaseKey := "<SUPABASE-KEY>"
  supabase := supa.CreateClient(supabaseUrl, supabaseKey)

  ctx := context.Background()
  user, err := supabase.Auth.InviteUserByEmail(ctx, email)
  if err != nil {
    panic(err)
  }

  // or if you want to setup some metadata
  data := map[string]interface{}{ "invitedBy": "someone" }
  redirectTo := "https://your_very_successful_app.com/signup"
  user, err = supabase.Auth.InviteUserByEmailWithData(ctx, email, data, redirectTo)
  if err != nil {
    panic(err)
  }

  fmt.Println(user)
}
Subscribing to Database Changes
package main

import (
   
    "fmt"

    supa "github.com/the-muppet/supabase-go"
)

func main() {
    supabaseUrl := "<SUPABASE-URL>"
    supabaseKey := "<SUPABASE-KEY>"
    supabase := supa.CreateClient(supabaseUrl, supabaseKey)

    channel := supabase.Channel("db-changes")
    
    channel.SubscribeToPostgresChanges([]supa.PostgresChange{
        {
            Event:  "*",       // Listen to all events (INSERT, UPDATE, DELETE)
            Schema: "public",  // Schema name
            Table:  "todos",   // Table name
        },
    })

    // Listen for changes
    err := channel.Subscribe(func(message supa.Message) {
        fmt.Println("Received message:", message)
        
        // Extract data from the payload
        payload, ok := message.Payload["record"].(map[string]interface{})
        if ok {
            fmt.Println("Changed record:", payload)
        }
    })
    
    if err != nil {
        panic(err)
    }
    
    // Connect to the Realtime server
    err = supabase.ConnectRealtime()
    if err != nil {
        panic(err)
    }
    
    // Join the channel
    err = channel.Join()
    if err != nil {
        panic(err)
    }
    
    // Wait for changes
    select {}
}
Using Presence to Track Online Users
package main

import (
    "fmt"

    supa "github.com/the-muppet/supabase-go"
)

func main() {
    supabaseUrl := "<SUPABASE-URL>"
    supabaseKey := "<SUPABASE-KEY>"
    supabase := supa.CreateClient(supabaseUrl, supabaseKey)
    
    channel := supabase.Channel("room:lobby")
    
    // Subscribe to presence
    channel.SubscribeToPresence("user-123")
    
    // Subscribe to presence changes
    err := channel.SubscribeToEvent("presence_state", func(message supa.Message) {
        fmt.Println("Presence state:", message.Payload)
        
        // Get the current presence state
        state := channel.GetPresenceState()
        fmt.Println("Current users:", state)
    })
    
    if err != nil {
        panic(err)
    }
    
    err = channel.SubscribeToEvent("presence_diff", func(message supa.Message) {
        fmt.Println("Presence diff:", message.Payload)
    })
    
    if err != nil {
        panic(err)
    }
    
    // Connect to the Realtime server
    err = supabase.ConnectRealtime()
    if err != nil {
        panic(err)
    }
    
    // Join the channel
    err = channel.Join()
    if err != nil {
        panic(err)
    }
    
    // Track the user's presence
    err = channel.Track(map[string]interface{}{
        "user_id": "user-123",
        "status": "online",
        "username": "johndoe",
    })
    
    if err != nil {
        panic(err)
    }
    
    // Wait for changes
    select {}
}
Broadcasting Messages Between Clients
package main

import (
  "fmt"

  supa "github.com/the-muppet/supabase-go"
)

func main() {
    supabaseUrl := "<SUPABASE-URL>"
    supabaseKey := "<SUPABASE-KEY>"
    supabase := supa.CreateClient(supabaseUrl, supabaseKey)
    
    // Create a channel
    channel := supabase.Channel("room:lobby")
    
    // Subscribe to broadcast
    channel.SubscribeToBroadcast([]string{"message"}, supa.BroadcastConfig{
        Self: true, // Receive your own messages
    })
    
    // Subscribe to messages
    err := channel.SubscribeToEvent("message", func(message supa.Message) {
        fmt.Println("Received message:", message.Payload)
    })
    
    if err != nil {
        panic(err)
    }
    
    // Connect to the Realtime server
    err = supabase.ConnectRealtime()
    if err != nil {
        panic(err)
    }
    
    // Join the channel
    err = channel.Join()
    if err != nil {
        panic(err)
    }
    
    // Broadcast a message
    err = channel.Broadcast("message", map[string]interface{}{
        "text": "Hello, world!",
        "user": "user-123",
    })
    
    if err != nil {
        panic(err)
    }
    
    // Wait for changes
    select {}
}

API Reference

Client Methods
  • client.Channel(name string) - Creates a new Realtime channel
  • client.ChannelWithOptions(name string, options *supa.ChannelOptions) - Creates a new channel with custom options
  • client.ConnectRealtime() - Establishes the WebSocket connection
  • client.DisconnectRealtime() - Closes the WebSocket connection
  • client.SetRealtimeAuth(token string) - Sets the authentication token
  • client.GetRealtimeStatus() - Returns the current connection status
Channel Methods
  • channel.Subscribe(callback supa.EventHandler) - Subscribes to all events on the channel
  • channel.SubscribeToEvent(event string, callback supa.EventHandler) - Subscribes to a specific event
  • channel.Unsubscribe() - Unsubscribes from the channel
  • channel.Join() - Joins the channel
  • channel.Broadcast(event string, payload interface{}) - Broadcasts a message
  • channel.Track(payload interface{}) - Tracks presence
  • channel.Untrack() - Untracks presence
  • channel.GetPresenceState() - Returns the current presence state
  • channel.SubscribeToPostgresChanges(changes []supa.PostgresChange) - Subscribes to PostgreSQL changes
  • channel.SubscribeToBroadcast(events []string, opts supa.BroadcastConfig) - Subscribes to broadcast events
  • channel.SubscribeToPresence(key string) - Subscribes to presence events
  • channel.Status() - Returns the current status of the channel

Roadmap

  • Auth support (1)
  • DB support (2)
  • Realtime
  • Storage
  • Testing

(1) - Thin API wrapper. Does not rely on the GoTrue library for simplicity (2) - Through postgrest-go

Design Goals

It tries to mimick as much as possible the official Javascript client library in terms of ease-of-use and in setup process.

Contributing

Submitting a pull request
  • Fork it (https://github.com/the-muppet/supabase-go/fork)
  • Create your feature branch (git checkout -b my-new-feature)
  • Commit your changes (git commit -am 'Add some feature')
  • Push to the branch (git push origin my-new-feature)
  • Create a new Pull Request

Contributors

  • nedpals - creator and maintainer of the original repository
  • the-muppet - realtime fork implementation

Documentation

Index

Constants

View Source
const (
	AuthEndpoint     = "auth/v1"
	AdminEndpoint    = "auth/v1/admin"
	RestEndpoint     = "rest/v1"
	StorageEndpoint  = "storage/v1"
	RealtimeEndpoint = "realtime/v1"
)

Variables

View Source
var ErrNotFound = errors.New("file not found")

Functions

func MarshalVerifyOtpCredentials

func MarshalVerifyOtpCredentials(c VerifyOtpCredentials) ([]byte, error)

MarshalVerifyOtpCredentials marshals the VerifyOtpCredentials into a JSON byte slice.

Types

type Admin

type Admin struct {
	// contains filtered or unexported fields
}

func (*Admin) CreateUser

func (a *Admin) CreateUser(ctx context.Context, params AdminUserParams) (*AdminUser, error)

Create a user

func (a *Admin) GenerateLink(ctx context.Context, params GenerateLinkParams) (*GenerateLinkResponse, error)

Update a user

func (*Admin) GetUser

func (a *Admin) GetUser(ctx context.Context, userID string) (*AdminUser, error)

Retrieve the user

func (*Admin) UpdateUser

func (a *Admin) UpdateUser(ctx context.Context, userID string, params AdminUserParams) (*AdminUser, error)

Update a user

type AdminUser

type AdminUser struct {
	ID string `json:"id" db:"id"`

	Aud   string `json:"aud" db:"aud"`
	Role  string `json:"role" db:"role"`
	Email string `json:"email" db:"email"`

	EmailConfirmedAt *time.Time `json:"email_confirmed_at,omitempty" db:"email_confirmed_at"`
	InvitedAt        *time.Time `json:"invited_at,omitempty" db:"invited_at"`

	Phone            string     `json:"phone" db:"phone"`
	PhoneConfirmedAt *time.Time `json:"phone_confirmed_at,omitempty" db:"phone_confirmed_at"`

	ConfirmationSentAt *time.Time `json:"confirmation_sent_at,omitempty" db:"confirmation_sent_at"`

	RecoverySentAt *time.Time `json:"recovery_sent_at,omitempty" db:"recovery_sent_at"`

	EmailChange       string     `json:"new_email,omitempty" db:"email_change"`
	EmailChangeSentAt *time.Time `json:"email_change_sent_at,omitempty" db:"email_change_sent_at"`

	PhoneChange       string     `json:"new_phone,omitempty" db:"phone_change"`
	PhoneChangeSentAt *time.Time `json:"phone_change_sent_at,omitempty" db:"phone_change_sent_at"`

	ReauthenticationSentAt *time.Time `json:"reauthentication_sent_at,omitempty" db:"reauthentication_sent_at"`

	LastSignInAt *time.Time `json:"last_sign_in_at,omitempty" db:"last_sign_in_at"`

	AppMetaData  JSONMap `json:"app_metadata" db:"raw_app_meta_data"`
	UserMetaData JSONMap `json:"user_metadata" db:"raw_user_meta_data"`

	Factors    []Factor   `json:"factors,omitempty" has_many:"factors"`
	Identities []Identity `json:"identities" has_many:"identities"`

	CreatedAt   time.Time  `json:"created_at" db:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at" db:"updated_at"`
	BannedUntil *time.Time `json:"banned_until,omitempty" db:"banned_until"`
	DeletedAt   *time.Time `json:"deleted_at,omitempty" db:"deleted_at"`
}

type AdminUserParams

type AdminUserParams struct {
	Role         string  `json:"role"`
	Email        string  `json:"email"`
	Phone        string  `json:"phone"`
	Password     *string `json:"password"`
	EmailConfirm bool    `json:"email_confirm"`
	PhoneConfirm bool    `json:"phone_confirm"`
	UserMetadata JSONMap `json:"user_metadata"`
	AppMetadata  JSONMap `json:"app_metadata"`
	BanDuration  string  `json:"ban_duration"`
}

type AppMetadata added in v0.6.3

type AppMetadata struct {
	Provider  string   `json:"provider,omitempty"`
	Providers []string `json:"providers,omitempty"`
	Sig       string   `json:"sig,omitempty"`
}

type Auth

type Auth struct {
	// contains filtered or unexported fields
}

func (*Auth) ExchangeCode

func (a *Auth) ExchangeCode(ctx context.Context, opts ExchangeCodeOpts) (*AuthenticatedDetails, error)

ExchangeCode takes an auth code and PCKE verifier and returns the current user if succeeded.

func (*Auth) InviteUserByEmail

func (a *Auth) InviteUserByEmail(ctx context.Context, email string) (*User, error)

InviteUserByEmail sends an invite link to the given email. Returns a user.

func (*Auth) InviteUserByEmailWithData

func (a *Auth) InviteUserByEmailWithData(ctx context.Context, email string, data map[string]interface{}, redirectTo string) (*User, error)

InviteUserByEmailWithOpts sends an invite link to the given email with metadata. Returns a user.

func (*Auth) RefreshUser

func (a *Auth) RefreshUser(ctx context.Context, userToken string, refreshToken string) (*AuthenticatedDetails, error)

RefreshUser refreshes the user's token and session.

func (*Auth) ResetPasswordForEmail

func (a *Auth) ResetPasswordForEmail(ctx context.Context, email string, redirectTo string) error

ResetPasswordForEmail sends a password recovery link to the given e-mail address.

func (a *Auth) SendMagicLink(ctx context.Context, email string) error

SendMagicLink sends a link to a specific e-mail address for passwordless auth.

func (*Auth) SignIn

func (a *Auth) SignIn(ctx context.Context, credentials UserCredentials) (*AuthenticatedDetails, error)

SignIn enters the user credentials and returns the current user if succeeded.

func (*Auth) SignInWithProvider

func (a *Auth) SignInWithProvider(opts ProviderSignInOptions) (*ProviderSignInDetails, error)

SignInWithProvider returns a URL for signing in via OAuth

func (*Auth) SignOut

func (a *Auth) SignOut(ctx context.Context, userToken string) error

SignOut revokes the users token and session.

func (*Auth) SignUp

func (a *Auth) SignUp(ctx context.Context, credentials UserCredentials) (*User, error)

SignUp registers the user's email and password to the database.

func (*Auth) UpdateUser

func (a *Auth) UpdateUser(ctx context.Context, userToken string, updateData map[string]interface{}) (*User, error)

UpdateUser updates the user information

func (*Auth) User

func (a *Auth) User(ctx context.Context, userToken string) (*User, error)

User retrieves the user information based on the given token

func (*Auth) VerifyOtp

func (a *Auth) VerifyOtp(ctx context.Context, credentials VerifyOtpCredentials) (*AuthenticatedDetails, error)

verify otp takes in a token hash and verify type, verifies the user and returns the the user if succeeded.

type AuthenticatedDetails

type AuthenticatedDetails struct {
	AccessToken          string `json:"access_token"`
	TokenType            string `json:"token_type"`
	ExpiresIn            int    `json:"expires_in"`
	RefreshToken         string `json:"refresh_token"`
	User                 User   `json:"user"`
	ProviderToken        string `json:"provider_token"`
	ProviderRefreshToken string `json:"provider_refresh_token"`
}

type BroadcastConfig

type BroadcastConfig struct {
	Self   bool     `json:"self"`
	Ack    bool     `json:"ack"`
	Events []string `json:"events"`
}

BroadcastConfig settings

type BroadcastParams

type BroadcastParams struct {
	Type    string      `json:"type"`
	Event   string      `json:"event"`
	Payload interface{} `json:"payload"`
}

BroadcastParams for message broadcasting

type BucketOption

type BucketOption struct {
	Id     string `json:"id"`
	Name   string `json:"name"`
	Public bool   `json:"public"`
}

type Channel

type Channel struct {
	// contains filtered or unexported fields
}

Channel represents a Realtime channel.

func NewChannel

func NewChannel(name string, client *RealtimeClient, options *ChannelOptions) *Channel

NewChannel creates a new channel.

func (*Channel) Broadcast

func (c *Channel) Broadcast(event string, payload interface{}) error

Broadcast sends a broadcast message on the channel.

func (*Channel) GetPresenceState

func (c *Channel) GetPresenceState() PresenceState

GetPresenceState returns the current presence state.

func (*Channel) Join

func (c *Channel) Join() error

Join joins the channel.

func (*Channel) Name

func (c *Channel) Name() string

Name returns the name of the channel.

func (*Channel) Status

func (c *Channel) Status() ChannelStatus

Status returns the current status of the channel.

func (*Channel) Subscribe

func (c *Channel) Subscribe(callback EventHandler) error

Subscribe subscribes to all events on the channel.

func (*Channel) SubscribeToBroadcast

func (c *Channel) SubscribeToBroadcast(events []string, opts BroadcastConfig) *Channel

SubscribeToBroadcast subscribes to broadcast events.

func (*Channel) SubscribeToEvent

func (c *Channel) SubscribeToEvent(event string, callback EventHandler) error

SubscribeToEvent subscribes to a specific event on the channel.

func (*Channel) SubscribeToPostgresChanges

func (c *Channel) SubscribeToPostgresChanges(changes []PostgresChange) *Channel

SubscribeToPostgresChanges subscribes to PostgreSQL changes.

func (*Channel) SubscribeToPresence

func (c *Channel) SubscribeToPresence(key string) *Channel

SubscribeToPresence subscribes to presence events.

func (*Channel) Track

func (c *Channel) Track(payload interface{}) error

Track sends a presence tracking message on the channel.

func (*Channel) Unsubscribe

func (c *Channel) Unsubscribe() error

Unsubscribe unsubscribes from the channel.

func (*Channel) Untrack

func (c *Channel) Untrack() error

Untrack sends a presence untracking message on the channel.

type ChannelOptions

type ChannelOptions struct {
	Config               map[string]interface{}
	Params               map[string]string
	RetryAfterMs         func(tries int) time.Duration
	RetryJoinUntil       time.Duration
	BroadcastEndpointURL string
	PresenceEndpointURL  string
}

ChannelOptions for channel configuration

type ChannelStatus

type ChannelStatus string

ChannelStatus for realtime channels

const (
	ChannelStatusClosed  ChannelStatus = "CLOSED"
	ChannelStatusJoining ChannelStatus = "JOINING"
	ChannelStatusJoined  ChannelStatus = "JOINED"
	ChannelStatusLeaving ChannelStatus = "LEAVING"
	ChannelStatusError   ChannelStatus = "ERROR"
)

type Client

type Client struct {
	BaseURL string

	HTTPClient *http.Client
	Admin      *Admin
	Auth       *Auth
	Storage    *Storage
	DB         *postgrest.Client
	Realtime   *Realtime
	// contains filtered or unexported fields
}

func CreateClient

func CreateClient(baseURL string, supabaseKey string, debug ...bool) *Client

CreateClient creates a new Supabase client

type ClientOptions

type ClientOptions struct {
	ConnectionTimeout  time.Duration
	HeartbeatInterval  time.Duration
	Headers            map[string]string
	Params             map[string]string
	AccessToken        GetAccessToken
	Transport          WebSocketTransport
	Logger             Logger
	ReconnectAfterMs   func(tries int) time.Duration
	HeartbeatTimeoutMs int
}

ClientOptions for Realtime client configuration

type ColumnData

type ColumnData struct {
	Name     string `json:"name"`
	Type     string `json:"type"`
	DataType string `json:"data_type"`
}

ColumnData for PostgreSQL column information

type ConnectionStatus

type ConnectionStatus string

ConnectionStatus for WebSocket connection

const (
	StatusClosed     ConnectionStatus = "CLOSED"
	StatusConnecting ConnectionStatus = "CONNECTING"
	StatusOpen       ConnectionStatus = "OPEN"
)

type EmailOtpType

type EmailOtpType string

EmailOtpType is the type of email OTP.

const (
	EmailOtpTypeEmail       EmailOtpType = "email"
	EmailOtpTypeReceovery   EmailOtpType = "recovery"
	EmailOtpTypeInvite      EmailOtpType = "invite"
	EmailOtpTypeEmailChange EmailOtpType = "email_change"
)

type ErrorResponse

type ErrorResponse struct {
	Code    int    `json:"code"`
	Message string `json:"msg"`
}

func (*ErrorResponse) Error

func (err *ErrorResponse) Error() string

type EventHandler

type EventHandler func(message Message)

EventHandler function type

type ExchangeCodeOpts

type ExchangeCodeOpts struct {
	AuthCode     string `json:"auth_code"`
	CodeVerifier string `json:"code_verifier"`
}

type Factor

type Factor struct {
	ID           string    `json:"id" db:"id"`
	CreatedAt    time.Time `json:"created_at" db:"created_at"`
	UpdatedAt    time.Time `json:"updated_at" db:"updated_at"`
	Status       string    `json:"status" db:"status"`
	FriendlyName string    `json:"friendly_name,omitempty" db:"friendly_name"`
	FactorType   string    `json:"factor_type" db:"factor_type"`
}

type FileErrorResponse

type FileErrorResponse struct {
	Status     string `json:"statusCode"`
	ShortError string `json:"error"`
	Message    string `json:"message"`
}

func (*FileErrorResponse) Error

func (err *FileErrorResponse) Error() string

type FileObject

type FileObject struct {
	Name           string      `json:"name"`
	BucketId       string      `json:"bucket_id"`
	Owner          string      `json:"owner"`
	Id             string      `json:"id"`
	UpdatedAt      string      `json:"updated_at"`
	CreatedAt      string      `json:"created_at"`
	LastAccessedAt string      `json:"last_accessed_at"`
	Metadata       interface{} `json:"metadata"`
	Buckets        bucket      `json:"buckets"`
}

type FileResponse

type FileResponse struct {
	Key     string `json:"key"`
	Message string `json:"message"`
}

type FileSearchOptions

type FileSearchOptions struct {
	Limit  int    `json:"limit"`
	Offset int    `json:"offset"`
	SortBy SortBy `json:"sortBy"`
}

type FileUploadOptions

type FileUploadOptions struct {
	CacheControl string
	ContentType  string
	MimeType     string
	Upsert       bool
}

type FlowType

type FlowType string
const (
	Implicit FlowType = "implicit"
	PKCE     FlowType = "pkce"
)

type GenerateLinkParams

type GenerateLinkParams struct {
	Type       string                 `json:"type"`
	Email      string                 `json:"email"`
	NewEmail   string                 `json:"new_email"`
	Password   string                 `json:"password"`
	Data       map[string]interface{} `json:"data"`
	RedirectTo string                 `json:"redirect_to"`
}

type GenerateLinkResponse

type GenerateLinkResponse struct {
	AdminUser
	ActionLink       string `json:"action_link"`
	EmailOtp         string `json:"email_otp"`
	HashedToken      string `json:"hashed_token"`
	VerificationType string `json:"verification_type"`
	RedirectTo       string `json:"redirect_to"`
}

type GetAccessToken

type GetAccessToken func() (string, error)

GetAccessToken function type

type GorillaWebSocketTransport

type GorillaWebSocketTransport struct {
	// contains filtered or unexported fields
}

GorillaWebSocketTransport implements WebSocketTransport using gorilla/websocket

func NewGorillaWebSocketTransport

func NewGorillaWebSocketTransport() *GorillaWebSocketTransport

func (*GorillaWebSocketTransport) Connect

func (t *GorillaWebSocketTransport) Connect(wsURL string, params map[string]string, headers map[string]string) error

Connect establishes a WebSocket connection

func (*GorillaWebSocketTransport) Disconnect

func (t *GorillaWebSocketTransport) Disconnect(code int, reason string) error

Disconnect closes the WebSocket connection

func (*GorillaWebSocketTransport) OnClose

func (t *GorillaWebSocketTransport) OnClose(callback func(code int, reason string)) error

func (*GorillaWebSocketTransport) OnError

func (t *GorillaWebSocketTransport) OnError(callback func(err error)) error

func (*GorillaWebSocketTransport) OnMessage

func (t *GorillaWebSocketTransport) OnMessage(callback func(data []byte)) error

func (*GorillaWebSocketTransport) OnOpen

func (t *GorillaWebSocketTransport) OnOpen(callback func()) error

Callbacks

func (*GorillaWebSocketTransport) Send

func (t *GorillaWebSocketTransport) Send(data []byte) error

Send sends a message over the WebSocket connection

type Identity

type Identity struct {
	ID           string     `json:"id" db:"id"`
	UserID       string     `json:"user_id" db:"user_id"`
	IdentityData JSONMap    `json:"identity_data,omitempty" db:"identity_data"`
	Provider     string     `json:"provider" db:"provider"`
	LastSignInAt *time.Time `json:"last_sign_in_at,omitempty" db:"last_sign_in_at"`
	CreatedAt    time.Time  `json:"created_at" db:"created_at"`
	UpdatedAt    time.Time  `json:"updated_at" db:"updated_at"`
}

type JSONMap

type JSONMap map[string]interface{}

type ListFileRequest

type ListFileRequest struct {
	Limit  int    `json:"limit"`
	Offset int    `json:"offset"`
	SortBy SortBy `json:"sortBy"`
	Prefix string `json:"prefix"`
}

type Logger

type Logger interface {
	Debug(args ...interface{})
	Info(args ...interface{})
	Warn(args ...interface{})
	Error(args ...interface{})
}

Logger interface

type Message

type Message struct {
	Event   string                 `json:"event"`
	Topic   string                 `json:"topic"`
	Payload map[string]interface{} `json:"payload"`
	Ref     string                 `json:"ref,omitempty"`
	JoinRef string                 `json:"join_ref,omitempty"`
}

Message from a channel

type PKCEParams

type PKCEParams struct {
	Challenge       string
	ChallengeMethod string
	Verifier        string
}

adapted from https://go-review.googlesource.com/c/oauth2/+/463979/9/pkce.go#64

type PhoneOtpType

type PhoneOtpType string

PhoneOtpType is the type of phone OTP.

const (
	PhoneOtpTypeSMS         PhoneOtpType = "sms"
	PhoneOtpTypePhoneChange PhoneOtpType = "phone_change"
)

type PostgresChange

type PostgresChange struct {
	Event   string   `json:"event"`
	Schema  string   `json:"schema"`
	Table   string   `json:"table"`
	Filter  string   `json:"filter,omitempty"`
	Columns []string `json:"columns,omitempty"`
}

PostgresChange subscription

type PresenceConfig

type PresenceConfig struct {
	Key string `json:"key"`
}

PresenceConfig settings

type PresenceDiff

type PresenceDiff struct {
	Joins  map[string]map[string]interface{} `json:"joins"`
	Leaves map[string]map[string]interface{} `json:"leaves"`
}

PresenceDiff for presence changes

type PresenceState

type PresenceState map[string]map[string]interface{}

PresenceState map

type ProviderSignInDetails

type ProviderSignInDetails struct {
	URL          string `json:"url"`
	Provider     string `json:"provider"`
	CodeVerifier string `json:"code_verifier"`
}

type ProviderSignInOptions

type ProviderSignInOptions struct {
	Provider   string   `url:"provider"`
	RedirectTo string   `url:"redirect_to"`
	Scopes     []string `url:"scopes"`
	FlowType   FlowType
}

type Push

type Push struct {
	Event   string
	Topic   string
	Payload map[string]interface{}
	Ref     string
	JoinRef string
}

Push message for WebSocket

type PusherEvent

type PusherEvent struct {
	Channel string      `json:"channel"`
	Event   string      `json:"event"`
	Data    interface{} `json:"data"`
}

PusherEvent for Pusher compatibility

type Realtime

type Realtime struct {
	// contains filtered or unexported fields
}

func (*Realtime) Channel

func (r *Realtime) Channel(name string) (*Channel, error)

Channel creates a new Realtime channel

func (*Realtime) Connect

func (r *Realtime) Connect() error

Connect establishes a WebSocket connection

func (*Realtime) Initialize

func (r *Realtime) Initialize() error

Initialize sets up the Realtime client with the base URL and API key

type RealtimeClient

type RealtimeClient struct {
	// contains filtered or unexported fields
}

RealtimeClient for realtime communication

func NewRealtimeClient

func NewRealtimeClient(url string, params map[string]string, headers map[string]string) *RealtimeClient

type RealtimePostgresChangesPayload

type RealtimePostgresChangesPayload struct {
	Commit  string                 `json:"commit_timestamp"`
	Errors  []string               `json:"errors"`
	Schema  string                 `json:"schema"`
	Table   string                 `json:"table"`
	Type    string                 `json:"type"`
	Old     map[string]interface{} `json:"old,omitempty"`
	New     map[string]interface{} `json:"new,omitempty"`
	Columns []ColumnData           `json:"columns,omitempty"`
}

RealtimePostgresChangesPayload for PostgreSQL changes

type SignedUrlResponse

type SignedUrlResponse struct {
	SignedUrl string `json:"signedURL"`
}

type SortBy

type SortBy struct {
	Column string `json:"column"`
	Order  string `json:"order"`
}

type Storage

type Storage struct {
	// contains filtered or unexported fields
}

func (*Storage) CreateBucket

func (s *Storage) CreateBucket(ctx context.Context, option BucketOption) (*bucket, error)

CreateBucket creates a new storage bucket @param: option: a bucketOption with the name and id of the bucket you want to create @returns: bucket: a response with the details of the bucket of the bucket created

func (*Storage) DeleteBucket

func (s *Storage) DeleteBucket(ctx context.Context, id string) (*bucketResponse, error)

DeleteBucket deletes a bucket by its id, a bucket can't be deleted except emptied @param: id: the id of the bucket @returns bucketMessage: a successful response message or failed

func (*Storage) EmptyBucket

func (s *Storage) EmptyBucket(ctx context.Context, id string) (*bucketMessage, error)

EmptyBucket empties the object of a bucket by id @param: id: the id of the bucket @returns bucketMessage: a successful response message or failed

func (*Storage) From

func (s *Storage) From(bucketId string) *file

func (*Storage) GetBucket

func (s *Storage) GetBucket(ctx context.Context, id string) (*bucketResponse, error)

GetBucket retrieves a bucket by its id @param: id: the id of the bucket @returns: bucketResponse: a response with the details of the bucket

func (*Storage) ListBuckets

func (s *Storage) ListBuckets(ctx context.Context) (*[]bucketResponse, error)

ListBucket retrieves all buckets ina supabase storage @returns: []bucketResponse: a response with the details of all the bucket

func (*Storage) UpdateBucket

func (s *Storage) UpdateBucket(ctx context.Context, id string, option BucketOption) (*bucketMessage, error)

UpdateBucket updates a bucket by its id @param: id: the id of the bucket @param: option: the options to be updated @returns bucketMessage: a successful response message or failed

type SubscribeParams

type SubscribeParams struct {
	PostgresChanges []PostgresChange `json:"postgres_changes,omitempty"`
	Broadcast       BroadcastConfig  `json:"broadcast,omitempty"`
	Presence        PresenceConfig   `json:"presence,omitempty"`
}

SubscribeParams for topic subscription

type User

type User struct {
	ID                 string                 `json:"id"`
	Aud                string                 `json:"aud"`
	Role               string                 `json:"role"`
	Email              string                 `json:"email"`
	InvitedAt          time.Time              `json:"invited_at"`
	ConfirmedAt        time.Time              `json:"confirmed_at"`
	ConfirmationSentAt time.Time              `json:"confirmation_sent_at"`
	AppMetadata        *AppMetadata           `json:"app_metadata,omitempty"`
	UserMetadata       map[string]interface{} `json:"user_metadata"`
	CreatedAt          time.Time              `json:"created_at"`
	UpdatedAt          time.Time              `json:"updated_at"`
}

type UserCredentials

type UserCredentials struct {
	Email    string
	Password string
	Data     interface{}
}

type VerifyEmailOtpCredentials

type VerifyEmailOtpCredentials struct {
	Email      string       `mapstructure:"email"`
	Token      string       `mapstructure:"token"`
	TokenHash  string       `mapstructure:"token_hash"`
	Type       EmailOtpType `mapstructure:"type"`
	RedirectTo string       `mapstructure:"redirect_to,omitempty"`
}

VerifyEmailOtpCredentials is the struct for verifying OTPs sent to an email address.

func (VerifyEmailOtpCredentials) OtpType

func (c VerifyEmailOtpCredentials) OtpType() string

OtpType returns the type of OTP.

type VerifyOtpCredentials

type VerifyOtpCredentials interface {
	OtpType() string
}

VerifyOtpCredentials is the interface for verifying OTPs.

type VerifyPhoneOtpCredentials

type VerifyPhoneOtpCredentials struct {
	Phone      string       `mapstructure:"phone"`
	Type       PhoneOtpType `mapstructure:"type"`
	TokenHash  string       `mapstructure:"token_hash"`
	Token      string       `mapstructure:"token"`
	RedirectTo string       `mapstructure:"redirect_to,omitempty"`
}

VerifyPhoneOtpCredentials is the struct for verifying OTPs sent to a phone number.

func (VerifyPhoneOtpCredentials) OtpType

func (c VerifyPhoneOtpCredentials) OtpType() string

type VerifyTokenHashOtpCredentials

type VerifyTokenHashOtpCredentials struct {
	TokenHash  string `mapstructure:"token_hash"`
	Type       string `mapstructure:"type"`
	RedirectTo string `mapstructure:"redirect_to,omitempty"`
}

VerifyTokenHashOtpCredentials is the struct for verifying OTPs sent other than email or phone.

func (VerifyTokenHashOtpCredentials) OtpType

OtpType returns the type of OTP.

type WebSocketTransport

type WebSocketTransport interface {
	Connect(url string, params map[string]string, headers map[string]string) error
	Disconnect(code int, reason string) error
	Send(data []byte) error
	OnOpen(callback func()) error
	OnClose(callback func(code int, reason string)) error
	OnError(callback func(err error)) error
	OnMessage(callback func(data []byte)) error
}

WebSocketTransport interface

Directories

Path Synopsis
postgrest
pkg

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL