81 lines
2.2 KiB
TypeScript
81 lines
2.2 KiB
TypeScript
/**
|
|
* Relay management methods for ConfigStorage
|
|
*/
|
|
|
|
import type { RelayConfig, ConfigData } from './configStorageTypes'
|
|
import { DEFAULT_RELAYS } from './configStorageTypes'
|
|
|
|
export function getEnabledRelays(config: ConfigData): string[] {
|
|
return config.relays
|
|
.filter((relay) => relay.enabled)
|
|
.sort((a, b) => a.priority - b.priority)
|
|
.map((relay) => relay.url)
|
|
}
|
|
|
|
export function getPrimaryRelayFromConfig(config: ConfigData): string {
|
|
const relays = getEnabledRelays(config)
|
|
if (relays.length === 0) {
|
|
const defaultRelay = DEFAULT_RELAYS[0]
|
|
if (!defaultRelay) {
|
|
throw new Error('No default relay configured')
|
|
}
|
|
return defaultRelay.url
|
|
}
|
|
const primaryRelay = relays[0]
|
|
if (!primaryRelay) {
|
|
const defaultRelay = DEFAULT_RELAYS[0]
|
|
if (!defaultRelay) {
|
|
throw new Error('No default relay configured')
|
|
}
|
|
return defaultRelay.url
|
|
}
|
|
return primaryRelay
|
|
}
|
|
|
|
export function createRelayConfig(url: string, enabled: boolean, priority: number): RelayConfig {
|
|
return {
|
|
id: `relay_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
|
|
url,
|
|
enabled,
|
|
priority,
|
|
createdAt: Date.now(),
|
|
}
|
|
}
|
|
|
|
export function addRelayToConfig(config: ConfigData, url: string, enabled: boolean, priority?: number): ConfigData {
|
|
const maxPriority = Math.max(...config.relays.map((r) => r.priority), 0)
|
|
const newRelay = createRelayConfig(url, enabled, priority ?? maxPriority + 1)
|
|
return {
|
|
...config,
|
|
relays: [...config.relays, newRelay],
|
|
}
|
|
}
|
|
|
|
export function updateRelayInConfig(
|
|
config: ConfigData,
|
|
id: string,
|
|
updates: Partial<Omit<RelayConfig, 'id' | 'createdAt'>>
|
|
): ConfigData {
|
|
const relayIndex = config.relays.findIndex((r) => r.id === id)
|
|
if (relayIndex === -1) {
|
|
throw new Error(`Relay with id ${id} not found`)
|
|
}
|
|
const existingRelay = config.relays[relayIndex]
|
|
const updatedRelays = [...config.relays]
|
|
updatedRelays[relayIndex] = {
|
|
...existingRelay,
|
|
...updates,
|
|
} as RelayConfig
|
|
return {
|
|
...config,
|
|
relays: updatedRelays,
|
|
}
|
|
}
|
|
|
|
export function removeRelayFromConfig(config: ConfigData, id: string): ConfigData {
|
|
return {
|
|
...config,
|
|
relays: config.relays.filter((r) => r.id !== id),
|
|
}
|
|
}
|