import PubNub from 'pubnub' /** * Provider method holder * We always reference this object so * we don't have to hardcode provider specific * methods for doing chat things. * * This gets overloaded later in the program */ const providerMethods = { publish: () => console.error('no provider publish method set'), subscribe: () => console.error('no provider subscribe method set'), listen: () => console.error('no provider listen method set') } /** * Breaking out as much pubnub specific flavor */ const setupPubnub = async uuid => { if(!uuid) return console.error('no pubnub uuid set') const pubnubClient = await new PubNub({ publishKey: import.meta.env.VITE_PUBNUB_PUBLISH_KEY, subscribeKey: import.meta.env.VITE_PUBNUB_SUBSCRIBE_KEY, uuid }) // Pass pubnub specific methods to our placeholder obj providerMethods['publish'] = pubnubClient.publish providerMethods['subscribe'] = pubnubClient.subscribe providerMethods['listen'] = pubnubClient.addListener return pubnubClient } class ChatMessage { constructor({ title, description }) { this.title = title, this.description = description } } const testMessage = new ChatMessage({ title: "testing", description: "hello world!", }) const MAIN_CHANNEL = 'hello_world' /** Singleton that holds all our chat information */ class Chatter { /** * Create our chatter instance * @return {Chatter} our chatter instance object */ constructor() { // Map of each active chat this.groupings = {} // Our pubnub instance this.provider = null // UUID used to identify unique users this.uuid = null // Setup the main channel this.subscriptions = [MAIN_CHANNEL] this.listeners = { status: async e => { if (e.category !== "PNConnectedCategory") return await this.publish(this.subscriptions[0], testMessage) }, message: this._onMessage, presence: this._onPresence } } /** * Callback that fires on every message * @param {event} e */ async _onMessage(e) { console.log(e.message.title) console.log(e.message.description) } async _onPresence(e) { return } async setup(uuid) { this.uuid = uuid this.provider = await setupPubnub(this.uuid) this._listenFor({ listeners: this.listeners }) this._subscribe(this.subscriptions) } /** * Send a message to a channel * example = new ChatMessage({ title: 'example', description: 'ni' }) * Facade so we can hide provider specific methods * @param {string} channel * @param {ChatMessage} message * @return {object} timestamp */ async publish(channel, message) { return await providerMethods['publish']({ channel, message }) } /** * Subscribe to a channels * Facade so we can hide provider specific methods * @param {array} channels */ _subscribe(channels) { providerMethods['subscribe']({ channels }) } /** * Listen to events and set callbacks * Facade so we can hide provider specific methods */ _listenFor({ listeners }) { providerMethods['listen'](listeners) } } export { Chatter }