Skip to content

Commit

Permalink
chore(docs): cleanup SlackClone example (#559)
Browse files Browse the repository at this point in the history
* chore(docs): cleanup SlackClone example

fix(realtime): allow to nullify access token

fix(realtime): deprecate `updateAuth` from channel
  • Loading branch information
grdsdev authored Oct 9, 2024
1 parent bfb6620 commit 45273e5
Show file tree
Hide file tree
Showing 14 changed files with 95 additions and 148 deletions.
31 changes: 8 additions & 23 deletions Examples/SlackClone/AppView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// Created by Guilherme Souza on 27/12/23.
//

import OSLog
import Supabase
import SwiftUI

Expand All @@ -17,58 +18,42 @@ final class AppViewModel {
var realtimeConnectionStatus: RealtimeClientV2.Status?

init() {
Task { [weak self] in
for await (event, session) in await supabase.auth.authStateChanges {
guard [.signedIn, .signedOut, .initialSession].contains(event) else { return }
self?.session = session
Task {
for await (event, session) in supabase.auth.authStateChanges {
Logger.main.debug("AuthStateChange: \(event.rawValue)")
guard [.signedIn, .signedOut, .initialSession, .tokenRefreshed].contains(event) else { return }
self.session = session

if session == nil {
for subscription in await supabase.realtimeV2.subscriptions.values {
for subscription in supabase.channels {
await subscription.unsubscribe()
}
}
}
}

Task {
for await status in await supabase.realtimeV2.statusChange {
for await status in supabase.realtimeV2.statusChange {
realtimeConnectionStatus = status
}
}
}
}

@MainActor
struct AppView: View {
@Bindable var model: AppViewModel
let log = LogStore.shared

@State var logPresented = false

@ViewBuilder
var body: some View {
if model.session != nil {
NavigationSplitView {
ChannelListView(channel: $model.selectedChannel)
.toolbar {
ToolbarItem {
Button("Log") {
logPresented = true
}
}
}
} detail: {
if let channel = model.selectedChannel {
MessagesView(channel: channel).id(channel.id)
}
}
.sheet(isPresented: $logPresented) {
List {
ForEach(0 ..< log.messages.count, id: \.self) { i in
Text(log.messages[i].description)
}
}
}
} else {
AuthView()
}
Expand Down
1 change: 0 additions & 1 deletion Examples/SlackClone/AuthView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ final class AuthViewModel {
}
}

@MainActor
struct AuthView: View {
@Bindable var model = AuthViewModel()

Expand Down
1 change: 0 additions & 1 deletion Examples/SlackClone/ChannelListView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

import SwiftUI

@MainActor
struct ChannelListView: View {
@Bindable var store = Dependencies.shared.channel
@Binding var channel: Channel?
Expand Down
12 changes: 6 additions & 6 deletions Examples/SlackClone/ChannelStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ final class ChannelStore {
Task {
channels = await fetchChannels()

let channel = await supabase.realtimeV2.channel("public:channels")
let channel = supabase.channel("public:channels")

let insertions = await channel.postgresChange(InsertAction.self, table: "channels")
let deletions = await channel.postgresChange(DeleteAction.self, table: "channels")
let insertions = channel.postgresChange(InsertAction.self, table: "channels")
let deletions = channel.postgresChange(DeleteAction.self, table: "channels")

await channel.subscribe()

Expand All @@ -47,7 +47,7 @@ final class ChannelStore {
do {
let userId = try await supabase.auth.session.user.id
let channel = AddChannel(slug: name, createdBy: userId)
try await supabase.database
try await supabase
.from("channels")
.insert(channel)
.execute()
Expand All @@ -62,7 +62,7 @@ final class ChannelStore {
return channel
}

let channel: Channel = try await supabase.database
let channel: Channel = try await supabase
.from("channels")
.select()
.eq("id", value: id)
Expand Down Expand Up @@ -90,7 +90,7 @@ final class ChannelStore {

private func fetchChannels() async -> [Channel] {
do {
return try await supabase.database.from("channels").select().execute().value
return try await supabase.from("channels").select().execute().value
} catch {
dump(error)
toast = .init(status: .error, title: "Error", description: error.localizedDescription)
Expand Down
1 change: 1 addition & 0 deletions Examples/SlackClone/Dependencies.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import Foundation
import Supabase

@MainActor
class Dependencies {
static let shared = Dependencies()

Expand Down
44 changes: 9 additions & 35 deletions Examples/SlackClone/Logger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,45 +10,19 @@ import OSLog
import Supabase

extension Logger {
static let main = Self(subsystem: "com.supabase.SlackClone", category: "app")
static let main = Self(subsystem: "com.supabase.slack-clone", category: "app")
static let supabase = Self(subsystem: "com.supabase.slack-clone", category: "supabase")
}

@Observable
final class LogStore: SupabaseLogger {
private let lock = NSLock()
private var loggers: [String: Logger] = [:]

static let shared = LogStore()

@MainActor
var messages: [SupabaseLogMessage] = []

struct SupaLogger: SupabaseLogger {
func log(message: SupabaseLogMessage) {
Task {
await add(message: message)
}
let logger = Logger.supabase

lock.withLock {
if loggers[message.system] == nil {
loggers[message.system] = Logger(
subsystem: "com.supabase.SlackClone.supabase-swift",
category: message.system
)
}

let logger = loggers[message.system]!

switch message.level {
case .debug: logger.debug("\(message, privacy: .public)")
case .error: logger.error("\(message, privacy: .public)")
case .verbose: logger.info("\(message, privacy: .public)")
case .warning: logger.notice("\(message, privacy: .public)")
}
switch message.level {
case .debug: logger.debug("\(message, privacy: .public)")
case .error: logger.error("\(message, privacy: .public)")
case .verbose: logger.info("\(message, privacy: .public)")
case .warning: logger.notice("\(message, privacy: .public)")
}
}

@MainActor
private func add(message: SupabaseLogMessage) {
messages.insert(message, at: 0)
}
}
10 changes: 5 additions & 5 deletions Examples/SlackClone/MessageStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,11 @@ final class MessageStore {

private init() {
Task {
let channel = await supabase.realtimeV2.channel("public:messages")
let channel = supabase.channel("public:messages")

let insertions = await channel.postgresChange(InsertAction.self, table: "messages")
let updates = await channel.postgresChange(UpdateAction.self, table: "messages")
let deletions = await channel.postgresChange(DeleteAction.self, table: "messages")
let insertions = channel.postgresChange(InsertAction.self, table: "messages")
let updates = channel.postgresChange(UpdateAction.self, table: "messages")
let deletions = channel.postgresChange(DeleteAction.self, table: "messages")

await channel.subscribe()

Expand Down Expand Up @@ -176,7 +176,7 @@ final class MessageStore {

/// Fetch all messages and their authors.
private func fetchMessages(_ channelId: Channel.ID) async throws -> [Message] {
try await supabase.database
try await supabase
.from("messages")
.select("*,user:user_id(*),channel:channel_id(*)")
.eq("channel_id", value: channelId)
Expand Down
3 changes: 1 addition & 2 deletions Examples/SlackClone/MessagesView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import Realtime
import Supabase
import SwiftUI

@MainActor
struct MessagesView: View {
let store = Dependencies.shared.messages
let userStore = Dependencies.shared.users
Expand Down Expand Up @@ -74,7 +73,7 @@ struct MessagesView: View {
channelId: channel.id
)

try await supabase.database.from("messages").insert(message).execute()
try await supabase.from("messages").insert(message).execute()
newMessage = ""
} catch {
dump(error)
Expand Down
4 changes: 2 additions & 2 deletions Examples/SlackClone/Supabase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ let supabase = SupabaseClient(
supabaseKey: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0",
options: SupabaseClientOptions(
db: .init(encoder: encoder, decoder: decoder),
auth: .init(redirectToURL: URL(string: "com.supabase.slack-clone://")),
global: SupabaseClientOptions.GlobalOptions(logger: LogStore.shared)
auth: .init(redirectToURL: URL(string: "com.supabase.slack-clone://login-callback")),
global: SupabaseClientOptions.GlobalOptions(logger: SupaLogger())
)
)
20 changes: 10 additions & 10 deletions Examples/SlackClone/UserStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ final class UserStore {

private init() {
Task {
let channel = await supabase.realtimeV2.channel("public:users")
let changes = await channel.postgresChange(AnyAction.self, table: "users")
let channel = supabase.channel("public:users")
let changes = channel.postgresChange(AnyAction.self, table: "users")

let presences = await channel.presenceChange()
let presences = channel.presenceChange()

await channel.subscribe()

Task {
let statusChange = await channel.statusChange
let statusChange = channel.statusChange
for await _ in statusChange.filter({ $0 == .subscribed }) {
let userId = try await supabase.auth.session.user.id
try await channel.track(UserPresence(userId: userId, onlineAt: Date()))
Expand All @@ -45,15 +45,15 @@ final class UserStore {
let joins = try presence.decodeJoins(as: UserPresence.self)
let leaves = try presence.decodeLeaves(as: UserPresence.self)

for join in joins {
self.presences[join.userId] = join
Logger.main.debug("User \(join.userId) joined")
}

for leave in leaves {
self.presences[leave.userId] = nil
Logger.main.debug("User \(leave.userId) leaved")
}

for join in joins {
self.presences[join.userId] = join
Logger.main.debug("User \(join.userId) joined")
}
}
}
}
Expand All @@ -64,7 +64,7 @@ final class UserStore {
return user
}

let user: User = try await supabase.database
let user: User = try await supabase
.from("users")
.select()
.eq("id", value: id)
Expand Down
2 changes: 1 addition & 1 deletion Examples/SlackClone/supabase/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ enabled = true
# in emails.
site_url = "http://127.0.0.1:3000"
# A list of *exact* URLs that auth providers are permitted to redirect to post authentication.
additional_redirect_urls = ["https://127.0.0.1:3000", "com.supabase.slack-clone://"]
additional_redirect_urls = ["https://127.0.0.1:3000", "com.supabase.slack-clone://*"]
# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week).
jwt_expiry = 3600
# If disabled, the refresh token will never expire.
Expand Down
Loading

0 comments on commit 45273e5

Please sign in to comment.