| 6 | } from "@electric-sql/client" |
| 7 | |
| 8 | export async function matchStream<T extends Row<unknown>>({ |
| 9 | stream, |
| 10 | operations, |
| 11 | matchFn, |
| 12 | timeout = 10000, |
| 13 | }: { |
| 14 | stream: ShapeStream<T> |
| 15 | operations: Array<`insert` | `update` | `delete`> |
| 16 | matchFn: ({ |
| 17 | operationType, |
| 18 | message, |
| 19 | }: { |
| 20 | operationType: string |
| 21 | message: ChangeMessage<T> |
| 22 | }) => boolean |
| 23 | timeout?: number |
| 24 | }): Promise<ChangeMessage<T>> { |
| 25 | return new Promise<ChangeMessage<T>>((resolve, reject) => { |
| 26 | const unsubscribe = stream.subscribe((messages) => { |
| 27 | const message = messages.filter(isChangeMessage).find( |
| 28 | (message) => |
| 29 | operations.includes(message.headers.operation) && |
| 30 | matchFn({ |
| 31 | operationType: message.headers.operation, |
| 32 | message: message, |
| 33 | }) |
| 34 | ) |
| 35 | if (message) return finish(message) |
| 36 | }) |
| 37 | |
| 38 | const timeoutId = setTimeout(() => { |
| 39 | console.error(`matchStream timed out after ${timeout}ms`) |
| 40 | reject(`matchStream timed out after ${timeout}ms`) |
| 41 | }, timeout) |
| 42 | |
| 43 | function finish(message: ChangeMessage<T>) { |
| 44 | clearTimeout(timeoutId) |
| 45 | unsubscribe() |
| 46 | return resolve(message) |
| 47 | } |
| 48 | }) |
| 49 | } |