Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use with a database subscription? #16

Closed
mcavaciocchi opened this issue Dec 8, 2023 · 2 comments
Closed

How to use with a database subscription? #16

mcavaciocchi opened this issue Dec 8, 2023 · 2 comments

Comments

@mcavaciocchi
Copy link

mcavaciocchi commented Dec 8, 2023

It's possible to return events when they happen in a database subscription?
I'm using postgres js library.

export async function GET() {
    const { unsubscribe } = await sql.subscribe(
        '*:msg',
        (row, { command }) => {
            console.log(command)
        },
        () => {
            console.log('connect')
        }
    )
    return event(async function run(emit) {
        emit(`${Date.now()}`)
    }).toResponse()
}
@razshare
Copy link
Owner

razshare commented Dec 8, 2023

I'm not very familiar with db subscriptions, but this should work

import { event } from 'sveltekit-sse'

export async function GET() {
  /**
   * @type {Array<function(...any):any>}
   */
  let unsubscribes = []
  /**
   * @type {false|function(any):void}
   */
  let stop = false

  function release() {
    for (const unsubscribe of unsubscribes) {
      unsubscribe()
    }
    if (!stop) {
      return
    }
    stop(false)
  }

  function lock() {
    return new Promise(function run(stopLocal) {
      stop = stopLocal
      // when you invoke "stop", the promise will resolve,
      // releasing the lock at line 50 and ending the stream.
    })
  }

  /**
   * @param {import("sveltekit-sse").EmitterOfOneEvent} emit
   */
  async function provide(emit) {
    const { unsubscribe } = await sql.subscribe(
      '*:msg',
      function message(row, { command }) {
        console.log(command)
        emit('...')
      },
      function connect() {
        console.log('connect')
      },
    )
    unsubscribes.push(unsubscribe)
  }

  return event(async function run(emit) {
    await provide(emit)
    await lock()
  })
    .onCancel(release)
    .toResponse()
}

This code will probably not work for you right out of the gate because I'm not familiar with the api of whatever library you're using.

So you'll need to make some adjustments yourself.

The idea is that you only invoke release() whenever you want to end the stream.
As long as you don't invoke release() or there's some error, the stream will stay online.

@mcavaciocchi
Copy link
Author

This was exactly what I needed!! Thx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants