Last active
July 20, 2023 05:55
-
-
Save leosantosw/955f1f60094d8188fa486768b60d0356 to your computer and use it in GitHub Desktop.
example pusher with nestjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as Pusher from 'pusher' | |
import { Injectable } from '@nestjs/common' | |
@Injectable() | |
export class PusherService { | |
private pusher = new Pusher({ | |
appId: process.env.PUSHER_APP_ID, | |
key: process.env.PUSHER_APP_KEY, | |
secret: process.env.PUSHER_APP_SECRET, | |
cluster: process.env.PUSHER_APP_CLUSTER, | |
useTLS: true | |
}) | |
private isStringTooLong = (str: string): boolean => { | |
return str.length > 10240 // 10kb | |
} | |
public async authenticate( | |
socketId: string, | |
channel: string | |
): Promise<Pusher.AuthResponse> { | |
const presenceData = { | |
user_id: socketId, | |
user_info: {} | |
} | |
return this.pusher.authenticate(socketId, channel, presenceData) | |
} | |
public emitMessageToUser( | |
channelName: string, | |
eventName: string, | |
data: any | |
): Promise<Response> { | |
try { | |
if (this.isStringTooLong(data)) { | |
console.error(`The data content of events must be smaller than 10kB.`) | |
return | |
} | |
return this.pusher.trigger(channelName, eventName, data) | |
} catch (e) { | |
console.error(e) | |
} | |
} | |
public async getChannels(): Promise<string[]> { | |
try { | |
const response = await this.pusher.get({ path: '/channels' }) | |
if (response.status !== 200) { | |
throw new Error(`Unexpected response status: ${response.status}`) | |
} | |
const { channels } = await response.json() | |
if (channels) { | |
return Object.keys(channels) | |
} | |
} catch (e) { | |
console.error(`Error fetching channels: ${e.message}`) | |
throw e | |
} | |
return [] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment