Spaces:
Running
Running
File size: 23,053 Bytes
5c05829 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 | import { CHANNEL_EVENTS, CHANNEL_STATES } from './lib/constants'
import Push from './lib/push'
import type RealtimeClient from './RealtimeClient'
import Timer from './lib/timer'
import RealtimePresence, {
REALTIME_PRESENCE_LISTEN_EVENTS,
} from './RealtimePresence'
import type {
RealtimePresenceJoinPayload,
RealtimePresenceLeavePayload,
RealtimePresenceState,
} from './RealtimePresence'
import * as Transformers from './lib/transformers'
export type RealtimeChannelOptions = {
config: {
/**
* self option enables client to receive message it broadcast
* ack option instructs server to acknowledge that broadcast message was received
*/
broadcast?: { self?: boolean; ack?: boolean }
/**
* key option is used to track presence payload across clients
*/
presence?: { key?: string }
}
}
type RealtimePostgresChangesPayloadBase = {
schema: string
table: string
commit_timestamp: string
errors: string[]
}
export type RealtimePostgresInsertPayload<T extends { [key: string]: any }> =
RealtimePostgresChangesPayloadBase & {
eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`
new: T
old: {}
}
export type RealtimePostgresUpdatePayload<T extends { [key: string]: any }> =
RealtimePostgresChangesPayloadBase & {
eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`
new: T
old: Partial<T>
}
export type RealtimePostgresDeletePayload<T extends { [key: string]: any }> =
RealtimePostgresChangesPayloadBase & {
eventType: `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`
new: {}
old: Partial<T>
}
export type RealtimePostgresChangesPayload<T extends { [key: string]: any }> =
| RealtimePostgresInsertPayload<T>
| RealtimePostgresUpdatePayload<T>
| RealtimePostgresDeletePayload<T>
export type RealtimePostgresChangesFilter<
T extends `${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT}`
> = {
/**
* The type of database change to listen to.
*/
event: T
/**
* The database schema to listen to.
*/
schema: string
/**
* The database table to listen to.
*/
table?: string
/**
* Receive database changes when filter is matched.
*/
filter?: string
}
export type RealtimeChannelSendResponse = 'ok' | 'timed out' | 'error'
export enum REALTIME_POSTGRES_CHANGES_LISTEN_EVENT {
ALL = '*',
INSERT = 'INSERT',
UPDATE = 'UPDATE',
DELETE = 'DELETE',
}
export enum REALTIME_LISTEN_TYPES {
BROADCAST = 'broadcast',
PRESENCE = 'presence',
/**
* listen to Postgres changes.
*/
POSTGRES_CHANGES = 'postgres_changes',
}
export enum REALTIME_SUBSCRIBE_STATES {
SUBSCRIBED = 'SUBSCRIBED',
TIMED_OUT = 'TIMED_OUT',
CLOSED = 'CLOSED',
CHANNEL_ERROR = 'CHANNEL_ERROR',
}
export const REALTIME_CHANNEL_STATES = CHANNEL_STATES
/** A channel is the basic building block of Realtime
* and narrows the scope of data flow to subscribed clients.
* You can think of a channel as a chatroom where participants are able to see who's online
* and send and receive messages.
*/
export default class RealtimeChannel {
bindings: {
[key: string]: {
type: string
filter: { [key: string]: any }
callback: Function
id?: string
}[]
} = {}
timeout: number
state = CHANNEL_STATES.closed
joinedOnce = false
joinPush: Push
rejoinTimer: Timer
pushBuffer: Push[] = []
presence: RealtimePresence
broadcastEndpointURL: string
subTopic: string
constructor(
/** Topic name can be any string. */
public topic: string,
public params: RealtimeChannelOptions = { config: {} },
public socket: RealtimeClient
) {
this.subTopic = topic.replace(/^realtime:/i, '')
this.params.config = {
...{
broadcast: { ack: false, self: false },
presence: { key: '' },
},
...params.config,
}
this.timeout = this.socket.timeout
this.joinPush = new Push(
this,
CHANNEL_EVENTS.join,
this.params,
this.timeout
)
this.rejoinTimer = new Timer(
() => this._rejoinUntilConnected(),
this.socket.reconnectAfterMs
)
this.joinPush.receive('ok', () => {
this.state = CHANNEL_STATES.joined
this.rejoinTimer.reset()
this.pushBuffer.forEach((pushEvent: Push) => pushEvent.send())
this.pushBuffer = []
})
this._onClose(() => {
this.rejoinTimer.reset()
this.socket.log('channel', `close ${this.topic} ${this._joinRef()}`)
this.state = CHANNEL_STATES.closed
this.socket._remove(this)
})
this._onError((reason: string) => {
if (this._isLeaving() || this._isClosed()) {
return
}
this.socket.log('channel', `error ${this.topic}`, reason)
this.state = CHANNEL_STATES.errored
this.rejoinTimer.scheduleTimeout()
})
this.joinPush.receive('timeout', () => {
if (!this._isJoining()) {
return
}
this.socket.log('channel', `timeout ${this.topic}`, this.joinPush.timeout)
this.state = CHANNEL_STATES.errored
this.rejoinTimer.scheduleTimeout()
})
this._on(CHANNEL_EVENTS.reply, {}, (payload: any, ref: string) => {
this._trigger(this._replyEventName(ref), payload)
})
this.presence = new RealtimePresence(this)
this.broadcastEndpointURL = this._broadcastEndpointURL()
}
/** Subscribe registers your client with the server */
subscribe(
callback?: (status: `${REALTIME_SUBSCRIBE_STATES}`, err?: Error) => void,
timeout = this.timeout
): RealtimeChannel {
if (!this.socket.isConnected()) {
this.socket.connect()
}
if (this.joinedOnce) {
throw `tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance`
} else {
const {
config: { broadcast, presence },
} = this.params
this._onError((e: Error) => callback && callback('CHANNEL_ERROR', e))
this._onClose(() => callback && callback('CLOSED'))
const accessTokenPayload: { access_token?: string } = {}
const config = {
broadcast,
presence,
postgres_changes:
this.bindings.postgres_changes?.map((r) => r.filter) ?? [],
}
if (this.socket.accessToken) {
accessTokenPayload.access_token = this.socket.accessToken
}
this.updateJoinPayload({ ...{ config }, ...accessTokenPayload })
this.joinedOnce = true
this._rejoin(timeout)
this.joinPush
.receive(
'ok',
({
postgres_changes: serverPostgresFilters,
}: {
postgres_changes: {
id: string
event: string
schema?: string
table?: string
filter?: string
}[]
}) => {
this.socket.accessToken &&
this.socket.setAuth(this.socket.accessToken)
if (serverPostgresFilters === undefined) {
callback && callback('SUBSCRIBED')
return
} else {
const clientPostgresBindings = this.bindings.postgres_changes
const bindingsLen = clientPostgresBindings?.length ?? 0
const newPostgresBindings = []
for (let i = 0; i < bindingsLen; i++) {
const clientPostgresBinding = clientPostgresBindings[i]
const {
filter: { event, schema, table, filter },
} = clientPostgresBinding
const serverPostgresFilter =
serverPostgresFilters && serverPostgresFilters[i]
if (
serverPostgresFilter &&
serverPostgresFilter.event === event &&
serverPostgresFilter.schema === schema &&
serverPostgresFilter.table === table &&
serverPostgresFilter.filter === filter
) {
newPostgresBindings.push({
...clientPostgresBinding,
id: serverPostgresFilter.id,
})
} else {
this.unsubscribe()
callback &&
callback(
'CHANNEL_ERROR',
new Error(
'mismatch between server and client bindings for postgres changes'
)
)
return
}
}
this.bindings.postgres_changes = newPostgresBindings
callback && callback('SUBSCRIBED')
return
}
}
)
.receive('error', (error: { [key: string]: any }) => {
callback &&
callback(
'CHANNEL_ERROR',
new Error(
JSON.stringify(Object.values(error).join(', ') || 'error')
)
)
return
})
.receive('timeout', () => {
callback && callback('TIMED_OUT')
return
})
}
return this
}
presenceState<
T extends { [key: string]: any } = {}
>(): RealtimePresenceState<T> {
return this.presence.state as RealtimePresenceState<T>
}
async track(
payload: { [key: string]: any },
opts: { [key: string]: any } = {}
): Promise<RealtimeChannelSendResponse> {
return await this.send(
{
type: 'presence',
event: 'track',
payload,
},
opts.timeout || this.timeout
)
}
async untrack(
opts: { [key: string]: any } = {}
): Promise<RealtimeChannelSendResponse> {
return await this.send(
{
type: 'presence',
event: 'untrack',
},
opts
)
}
/**
* Creates an event handler that listens to changes.
*/
on(
type: `${REALTIME_LISTEN_TYPES.PRESENCE}`,
filter: { event: `${REALTIME_PRESENCE_LISTEN_EVENTS.SYNC}` },
callback: () => void
): RealtimeChannel
on<T extends { [key: string]: any }>(
type: `${REALTIME_LISTEN_TYPES.PRESENCE}`,
filter: { event: `${REALTIME_PRESENCE_LISTEN_EVENTS.JOIN}` },
callback: (payload: RealtimePresenceJoinPayload<T>) => void
): RealtimeChannel
on<T extends { [key: string]: any }>(
type: `${REALTIME_LISTEN_TYPES.PRESENCE}`,
filter: { event: `${REALTIME_PRESENCE_LISTEN_EVENTS.LEAVE}` },
callback: (payload: RealtimePresenceLeavePayload<T>) => void
): RealtimeChannel
on<T extends { [key: string]: any }>(
type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`,
filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.ALL}`>,
callback: (payload: RealtimePostgresChangesPayload<T>) => void
): RealtimeChannel
on<T extends { [key: string]: any }>(
type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`,
filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.INSERT}`>,
callback: (payload: RealtimePostgresInsertPayload<T>) => void
): RealtimeChannel
on<T extends { [key: string]: any }>(
type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`,
filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.UPDATE}`>,
callback: (payload: RealtimePostgresUpdatePayload<T>) => void
): RealtimeChannel
on<T extends { [key: string]: any }>(
type: `${REALTIME_LISTEN_TYPES.POSTGRES_CHANGES}`,
filter: RealtimePostgresChangesFilter<`${REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE}`>,
callback: (payload: RealtimePostgresDeletePayload<T>) => void
): RealtimeChannel
/**
* The following is placed here to display on supabase.com/docs/reference/javascript/subscribe.
* @param type One of "broadcast", "presence", or "postgres_changes".
* @param filter Custom object specific to the Realtime feature detailing which payloads to receive.
* @param callback Function to be invoked when event handler is triggered.
*/
on(
type: `${REALTIME_LISTEN_TYPES.BROADCAST}`,
filter: { event: string },
callback: (payload: {
type: `${REALTIME_LISTEN_TYPES.BROADCAST}`
event: string
[key: string]: any
}) => void
): RealtimeChannel
on<T extends { [key: string]: any }>(
type: `${REALTIME_LISTEN_TYPES.BROADCAST}`,
filter: { event: string },
callback: (payload: {
type: `${REALTIME_LISTEN_TYPES.BROADCAST}`
event: string
payload: T
}) => void
): RealtimeChannel
on(
type: `${REALTIME_LISTEN_TYPES}`,
filter: { event: string; [key: string]: string },
callback: (payload: any) => void
): RealtimeChannel {
return this._on(type, filter, callback)
}
/**
* Sends a message into the channel.
*
* @param args Arguments to send to channel
* @param args.type The type of event to send
* @param args.event The name of the event being sent
* @param args.payload Payload to be sent
* @param opts Options to be used during the send process
*/
async send(
args: {
type: 'broadcast' | 'presence' | 'postgres_changes'
event: string
payload?: any
[key: string]: any
},
opts: { [key: string]: any } = {}
): Promise<RealtimeChannelSendResponse> {
if (!this._canPush() && args.type === 'broadcast') {
const { event, payload: endpoint_payload } = args
const options = {
method: 'POST',
headers: {
apikey: this.socket.accessToken ?? '',
'Content-Type': 'application/json',
},
body: JSON.stringify({
messages: [
{ topic: this.subTopic, event, payload: endpoint_payload },
],
}),
}
try {
const response = await this._fetchWithTimeout(
this.broadcastEndpointURL,
options,
opts.timeout ?? this.timeout
)
if (response.ok) {
return 'ok'
} else {
return 'error'
}
} catch (error: any) {
if (error.name === 'AbortError') {
return 'timed out'
} else {
return 'error'
}
}
} else {
return new Promise((resolve) => {
const push = this._push(args.type, args, opts.timeout || this.timeout)
if (args.type === 'broadcast' && !this.params?.config?.broadcast?.ack) {
resolve('ok')
}
push.receive('ok', () => resolve('ok'))
push.receive('timeout', () => resolve('timed out'))
})
}
}
updateJoinPayload(payload: { [key: string]: any }): void {
this.joinPush.updatePayload(payload)
}
/**
* Leaves the channel.
*
* Unsubscribes from server events, and instructs channel to terminate on server.
* Triggers onClose() hooks.
*
* To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie:
* channel.unsubscribe().receive("ok", () => alert("left!") )
*/
unsubscribe(timeout = this.timeout): Promise<'ok' | 'timed out' | 'error'> {
this.state = CHANNEL_STATES.leaving
const onClose = () => {
this.socket.log('channel', `leave ${this.topic}`)
this._trigger(CHANNEL_EVENTS.close, 'leave', this._joinRef())
}
this.rejoinTimer.reset()
// Destroy joinPush to avoid connection timeouts during unscription phase
this.joinPush.destroy()
return new Promise((resolve) => {
const leavePush = new Push(this, CHANNEL_EVENTS.leave, {}, timeout)
leavePush
.receive('ok', () => {
onClose()
resolve('ok')
})
.receive('timeout', () => {
onClose()
resolve('timed out')
})
.receive('error', () => {
resolve('error')
})
leavePush.send()
if (!this._canPush()) {
leavePush.trigger('ok', {})
}
})
}
/** @internal */
_broadcastEndpointURL(): string {
let url = this.socket.endPoint
url = url.replace(/^ws/i, 'http')
url = url.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i, '')
return url.replace(/\/+$/, '') + '/api/broadcast'
}
async _fetchWithTimeout(
url: string,
options: { [key: string]: any },
timeout: number
) {
const controller = new AbortController()
const id = setTimeout(() => controller.abort(), timeout)
const response = await this.socket.fetch(url, {
...options,
signal: controller.signal,
})
clearTimeout(id)
return response
}
/** @internal */
_push(
event: string,
payload: { [key: string]: any },
timeout = this.timeout
) {
if (!this.joinedOnce) {
throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`
}
let pushEvent = new Push(this, event, payload, timeout)
if (this._canPush()) {
pushEvent.send()
} else {
pushEvent.startTimeout()
this.pushBuffer.push(pushEvent)
}
return pushEvent
}
/**
* Overridable message hook
*
* Receives all events for specialized message handling before dispatching to the channel callbacks.
* Must return the payload, modified or unmodified.
*
* @internal
*/
_onMessage(_event: string, payload: any, _ref?: string) {
return payload
}
/** @internal */
_isMember(topic: string): boolean {
return this.topic === topic
}
/** @internal */
_joinRef(): string {
return this.joinPush.ref
}
/** @internal */
_trigger(type: string, payload?: any, ref?: string) {
const typeLower = type.toLocaleLowerCase()
const { close, error, leave, join } = CHANNEL_EVENTS
const events: string[] = [close, error, leave, join]
if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) {
return
}
let handledPayload = this._onMessage(typeLower, payload, ref)
if (payload && !handledPayload) {
throw 'channel onMessage callbacks must return the payload, modified or unmodified'
}
if (['insert', 'update', 'delete'].includes(typeLower)) {
this.bindings.postgres_changes
?.filter((bind) => {
return (
bind.filter?.event === '*' ||
bind.filter?.event?.toLocaleLowerCase() === typeLower
)
})
.map((bind) => bind.callback(handledPayload, ref))
} else {
this.bindings[typeLower]
?.filter((bind) => {
if (
['broadcast', 'presence', 'postgres_changes'].includes(typeLower)
) {
if ('id' in bind) {
const bindId = bind.id
const bindEvent = bind.filter?.event
return (
bindId &&
payload.ids?.includes(bindId) &&
(bindEvent === '*' ||
bindEvent?.toLocaleLowerCase() ===
payload.data?.type.toLocaleLowerCase())
)
} else {
const bindEvent = bind?.filter?.event?.toLocaleLowerCase()
return (
bindEvent === '*' ||
bindEvent === payload?.event?.toLocaleLowerCase()
)
}
} else {
return bind.type.toLocaleLowerCase() === typeLower
}
})
.map((bind) => {
if (typeof handledPayload === 'object' && 'ids' in handledPayload) {
const postgresChanges = handledPayload.data
const { schema, table, commit_timestamp, type, errors } =
postgresChanges
const enrichedPayload = {
schema: schema,
table: table,
commit_timestamp: commit_timestamp,
eventType: type,
new: {},
old: {},
errors: errors,
}
handledPayload = {
...enrichedPayload,
...this._getPayloadRecords(postgresChanges),
}
}
bind.callback(handledPayload, ref)
})
}
}
/** @internal */
_isClosed(): boolean {
return this.state === CHANNEL_STATES.closed
}
/** @internal */
_isJoined(): boolean {
return this.state === CHANNEL_STATES.joined
}
/** @internal */
_isJoining(): boolean {
return this.state === CHANNEL_STATES.joining
}
/** @internal */
_isLeaving(): boolean {
return this.state === CHANNEL_STATES.leaving
}
/** @internal */
_replyEventName(ref: string): string {
return `chan_reply_${ref}`
}
/** @internal */
_on(type: string, filter: { [key: string]: any }, callback: Function) {
const typeLower = type.toLocaleLowerCase()
const binding = {
type: typeLower,
filter: filter,
callback: callback,
}
if (this.bindings[typeLower]) {
this.bindings[typeLower].push(binding)
} else {
this.bindings[typeLower] = [binding]
}
return this
}
/** @internal */
_off(type: string, filter: { [key: string]: any }) {
const typeLower = type.toLocaleLowerCase()
this.bindings[typeLower] = this.bindings[typeLower].filter((bind) => {
return !(
bind.type?.toLocaleLowerCase() === typeLower &&
RealtimeChannel.isEqual(bind.filter, filter)
)
})
return this
}
/** @internal */
private static isEqual(
obj1: { [key: string]: string },
obj2: { [key: string]: string }
) {
if (Object.keys(obj1).length !== Object.keys(obj2).length) {
return false
}
for (const k in obj1) {
if (obj1[k] !== obj2[k]) {
return false
}
}
return true
}
/** @internal */
private _rejoinUntilConnected() {
this.rejoinTimer.scheduleTimeout()
if (this.socket.isConnected()) {
this._rejoin()
}
}
/**
* Registers a callback that will be executed when the channel closes.
*
* @internal
*/
private _onClose(callback: Function) {
this._on(CHANNEL_EVENTS.close, {}, callback)
}
/**
* Registers a callback that will be executed when the channel encounteres an error.
*
* @internal
*/
private _onError(callback: Function) {
this._on(CHANNEL_EVENTS.error, {}, (reason: string) => callback(reason))
}
/**
* Returns `true` if the socket is connected and the channel has been joined.
*
* @internal
*/
private _canPush(): boolean {
return this.socket.isConnected() && this._isJoined()
}
/** @internal */
private _rejoin(timeout = this.timeout): void {
if (this._isLeaving()) {
return
}
this.socket._leaveOpenTopic(this.topic)
this.state = CHANNEL_STATES.joining
this.joinPush.resend(timeout)
}
/** @internal */
private _getPayloadRecords(payload: any) {
const records = {
new: {},
old: {},
}
if (payload.type === 'INSERT' || payload.type === 'UPDATE') {
records.new = Transformers.convertChangeData(
payload.columns,
payload.record
)
}
if (payload.type === 'UPDATE' || payload.type === 'DELETE') {
records.old = Transformers.convertChangeData(
payload.columns,
payload.old_record
)
}
return records
}
}
|