Skip to content

Instantly share code, notes, and snippets.

@harrisrobin
Created September 29, 2024 19:06
Show Gist options
  • Select an option

  • Save harrisrobin/25bd0ed360033309bc8fafead7350fd1 to your computer and use it in GitHub Desktop.

Select an option

Save harrisrobin/25bd0ed360033309bc8fafead7350fd1 to your computer and use it in GitHub Desktop.
ably-providers.tsx
"use client"
import { ChatClient, LogLevel } from "@ably/chat"
import { ChatClientProvider } from "@ably/chat/react"
import type { User } from "@supabase/supabase-js"
import * as Ably from "ably"
import { AblyProvider } from "ably/react"
enum AblyLogLevel {
Silent = 0,
Error = 1,
All = 2,
}
// biome-ignore lint/complexity/noStaticOnlyClass: <explanation>
class AblyClientSingleton {
static instance: Ably.Realtime | null = null
static getInstance() {
if (typeof window === "undefined") return null
if (!AblyClientSingleton.instance) {
AblyClientSingleton.instance = new Ably.Realtime({
authUrl: "/api/ably",
key: process.env.NEXT_PUBLIC_ABLY_API_KEY,
logHandler: console.log,
logLevel: AblyLogLevel.Silent,
})
AblyClientSingleton.instance.connection.on("connected", () => {
console.log("Connected to Ably")
})
}
return AblyClientSingleton.instance
}
}
// biome-ignore lint/complexity/noStaticOnlyClass: <explanation>
class ChatClientSingleton {
static instance: ChatClient | null = null
static getInstance() {
if (typeof window === "undefined") return null
if (!ChatClientSingleton.instance) {
ChatClientSingleton.instance = new ChatClient(
AblyClientSingleton.getInstance()!,
{
logLevel: LogLevel.Silent,
logHandler: console.log,
},
)
}
return ChatClientSingleton.instance
}
}
interface AblyProvidersProps {
children: React.ReactNode
initialUser: User | null
}
export function AblyProviders({ children }: AblyProvidersProps) {
const client = AblyClientSingleton.getInstance()
const chatClient = ChatClientSingleton.getInstance()
return (
<AblyProvider client={client!}>
<ChatClientProvider client={chatClient!}>{children}</ChatClientProvider>
</AblyProvider>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment