|
| 1 | +import { |
| 2 | + formatSocketMessage, |
| 3 | + getStatusMessageAndConnectionStatus, |
| 4 | +} from "../../../server/helpers/websocket"; |
| 5 | +import { subscriptionsData } from "../../../server/schemas/websocket"; |
| 6 | +import { sendTxWebhook } from "../../../server/utilities/webhook"; |
| 7 | +import { knex } from "../../db/client"; |
| 8 | +import { getTxById } from "../../db/transactions/getTxById"; |
| 9 | +import { logger } from "../../utils/logger"; |
| 10 | + |
| 11 | +export const updateTxListener = async (): Promise<void> => { |
| 12 | + logger.worker.info(`Listening for updated transactions`); |
| 13 | + |
| 14 | + const connection = await knex.client.acquireConnection(); |
| 15 | + connection.query(`LISTEN updated_transaction_data`); |
| 16 | + |
| 17 | + connection.on( |
| 18 | + "notification", |
| 19 | + async (msg: { channel: string; payload: string }) => { |
| 20 | + const parsedPayload = JSON.parse(msg.payload); |
| 21 | + |
| 22 | + // Send webhook |
| 23 | + await sendTxWebhook(parsedPayload); |
| 24 | + |
| 25 | + // Send websocket message |
| 26 | + const index = subscriptionsData.findIndex( |
| 27 | + (sub) => sub.requestId === parsedPayload.identifier, |
| 28 | + ); |
| 29 | + |
| 30 | + if (index == -1) { |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + const userSubscription = subscriptionsData[index]; |
| 35 | + const returnData = await getTxById({ |
| 36 | + queueId: parsedPayload.identifier, |
| 37 | + }); |
| 38 | + const { message, closeConnection } = |
| 39 | + await getStatusMessageAndConnectionStatus(returnData); |
| 40 | + userSubscription.socket.send( |
| 41 | + await formatSocketMessage(returnData, message), |
| 42 | + ); |
| 43 | + closeConnection ? userSubscription.socket.close() : null; |
| 44 | + }, |
| 45 | + ); |
| 46 | + |
| 47 | + connection.on("end", async () => { |
| 48 | + logger.server.info(`Connection database ended`); |
| 49 | + knex.client.releaseConnection(connection); |
| 50 | + await knex.destroy(); |
| 51 | + logger.server.info(`Released sql connection : on end`); |
| 52 | + }); |
| 53 | + |
| 54 | + connection.on("error", async (err: any) => { |
| 55 | + logger.server.error(err); |
| 56 | + knex.client.releaseConnection(connection); |
| 57 | + await knex.destroy(); |
| 58 | + logger.server.info(`Released sql connection: on error`); |
| 59 | + }); |
| 60 | +}; |
0 commit comments