Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(session): extract the message-row mapper
Yudhi Armyndharis844561336309
diff --git a/src/modules/session/message-row.mapper.spec.ts b/src/modules/session/message-row.mapper.spec.tsnew file mode 100644index 000000000..c521ecf64--- /dev/null+++ b/src/modules/session/message-row.mapper.spec.ts@@ -0,0 +1,89 @@+import { buildMessageMetadata, storableWaMessageId, MEDIA_MESSAGE_TYPES } from './message-row.mapper';+import type { IncomingMessage, MessageType } from '../../engine/interfaces/whatsapp-engine.interface';++const msg = (over: Partial<IncomingMessage> = {}): IncomingMessage => ({ type: 'chat', ...over }) as IncomingMessage;++describe('buildMessageMetadata', () => {+ it('returns undefined when there is nothing to store (the column is nullable)', () => {+ expect(buildMessageMetadata(msg())).toBeUndefined();+ });++ it('stores the engine-supplied media as-is', () => {+ const media = { mimetype: 'image/png', data: 'x' };++ expect(buildMessageMetadata(msg({ type: 'image', media }))).toEqual({ media });+ });++ it('stores a quoted message', () => {+ const quotedMessage = { id: 'q1' };++ expect(buildMessageMetadata(msg({ quotedMessage } as Partial<IncomingMessage>))).toEqual({ quotedMessage });+ });++ it('stores call metadata', () => {+ const call = { video: false, missed: false };++ expect(buildMessageMetadata(msg({ call }))).toEqual({ call });+ });++ it('stores every present field together', () => {+ const built = buildMessageMetadata(+ msg({+ type: 'image',+ media: { mimetype: 'image/png' },+ quotedMessage: { id: 'q' },+ call: { video: false, missed: false },+ } as Partial<IncomingMessage>),+ );++ expect(Object.keys(built!).sort()).toEqual(['call', 'media', 'quotedMessage']);+ });++ describe('omitted-media synthesis', () => {+ // The wwjs own-send echo and the history backfill both lose the media payload; without a marker+ // the row renders as an empty bubble and drops out of the by-type stats.+ it.each([...MEDIA_MESSAGE_TYPES])('synthesizes a placeholder for a media-typed %s when asked', type => {+ expect(buildMessageMetadata(msg({ type: type as MessageType }), true)).toEqual({+ media: { mimetype: '', omitted: true },+ });+ });++ it('does NOT synthesize for the live inbound path, where absent media means no media', () => {+ // This is the one deliberate difference between the three persist paths.+ expect(buildMessageMetadata(msg({ type: 'image' }))).toBeUndefined();+ });++ it('does not synthesize for a non-media type', () => {+ expect(buildMessageMetadata(msg({ type: 'chat' as MessageType }), true)).toBeUndefined();+ });++ it('prefers real media over the placeholder', () => {+ const media = { mimetype: 'image/png' };++ expect(buildMessageMetadata(msg({ type: 'image', media }), true)).toEqual({ media });+ });++ it('returns a fresh placeholder each time, so callers cannot mutate a shared object', () => {+ const a = buildMessageMetadata(msg({ type: 'image' }), true)!;+ const b = buildMessageMetadata(msg({ type: 'image' }), true)!;++ expect(a.media).not.toBe(b.media);+ });+ });+});++describe('storableWaMessageId', () => {+ it('passes a real id through', () => {+ expect(storableWaMessageId('wa-1')).toBe('wa-1');+ });++ it('maps the empty sentinel to undefined so the row stores NULL', () => {+ // `''` would collide the second unreadable-id message on the (sessionId, waMessageId) unique+ // index and lose the row; NULL is what that index exempts.+ expect(storableWaMessageId('')).toBeUndefined();+ });++ it('maps undefined to undefined', () => {+ expect(storableWaMessageId(undefined)).toBeUndefined();+ });+});diff --git a/src/modules/session/message-row.mapper.ts b/src/modules/session/message-row.mapper.tsnew file mode 100644index 000000000..92bd5c6c9--- /dev/null+++ b/src/modules/session/message-row.mapper.ts@@ -0,0 +1,59 @@+import type { IncomingMessage } from '../../engine/interfaces/whatsapp-engine.interface';++/**+ * Message types whose rows must show a media placeholder even when the payload carried none.+ *+ * The wwjs own-send echo carries no media field at all (Baileys emits an omitted marker), and the+ * history sync maps messages media-free to keep its footprint down. Without the marker such a row+ * renders as an empty bubble — the DB copy wins over the engine-history placeholder in the dashboard+ * merge — and the by-type stats filter would skip it.+ */+export const MEDIA_MESSAGE_TYPES = new Set(['image', 'video', 'audio', 'voice', 'sticker', 'document']);++/** The synthesized stand-in for a media payload the engine did not deliver. */+export const OMITTED_MEDIA = { mimetype: '', omitted: true } as const;++/**+ * Builds the `metadata` JSON column for a persisted message row.+ *+ * The three persist paths (live inbound `onMessage`, own-send echo `onMessageCreate`, and the+ * pre-connection history backfill) each assembled this inline, with one deliberate difference:+ * inbound trusts the engine's media field as-is, while the two paths that are known to lose media+ * synthesize a placeholder. Keeping both rules in one function makes that difference explicit+ * instead of something to re-derive at each site.+ *+ * @param synthesizeOmittedMedia When true, a media-typed message with no media payload gets the+ * omitted marker. False for live inbound, where absent media genuinely means "no media".+ * @returns The metadata object, or undefined when there is nothing to store (the column is nullable+ * and an empty object would be noise).+ */+export function buildMessageMetadata(+ message: Pick<IncomingMessage, 'media' | 'quotedMessage' | 'call' | 'type'>,+ synthesizeOmittedMedia = false,+): Record<string, unknown> | undefined {+ const metadata: Record<string, unknown> = {};+ if (message.media) {+ metadata.media = message.media;+ } else if (synthesizeOmittedMedia && MEDIA_MESSAGE_TYPES.has(message.type)) {+ metadata.media = { ...OMITTED_MEDIA };+ }+ if (message.quotedMessage) {+ metadata.quotedMessage = message.quotedMessage;+ }+ if (message.call) {+ metadata.call = message.call;+ }+ return Object.keys(metadata).length > 0 ? metadata : undefined;+}++/**+ * The `waMessageId` to store for a message.+ *+ * An engine that received a message but could not read its id back reports the empty sentinel, and+ * NULL is what the non-partial `(sessionId, waMessageId)` unique index exempts — storing `''` would+ * collide the second such message and lose the row. Every persist path funnels through here so that+ * chokepoint cannot be forgotten at a new one.+ */+export function storableWaMessageId(id: string | undefined): string | undefined {+ return id || undefined;+}diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 6be3ff59b..fb49b58cc 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -27,6 +27,7 @@ import { EngineRegistry } from '../../engine/engine-registry.service';import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';import { decideReconnect, clampReconnectDelay, type ReconnectAttemptState } from './reconnect-policy';import { SessionLidResolver } from './session-lid-resolver.service';+import { buildMessageMetadata, storableWaMessageId } from './message-row.mapper';import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';import { resolveAuthTimeoutMs } from '../../engine/adapters/whatsapp-web-js.adapter';import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';@@ -66,7 +67,6 @@ import {// marker in metadata — never NULL — or the dashboard renders an empty bubble (no placeholder) and the// by-type stats filter skips the row. Sources that lack the payload (wwjs own-send echo, media-free// history sync) get the omitted marker synthesized at the persistence chokepoints.-const MEDIA_MESSAGE_TYPES = new Set(['image', 'video', 'audio', 'voice', 'sticker', 'document']);// How many recent status-broadcast messages the connect-time seed pulls (each with its media).// ponytail: fixed ceiling — the most-recent 50 cover a normal account's 24h of stories; anything@@ -1008,17 +1008,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat.filter(x => !seen.has(x)).map(x => {const m = byId.get(x)!;- const metadata: Record<string, unknown> = {};- if (m.media) {- metadata.media = m.media;- } else if (MEDIA_MESSAGE_TYPES.has(m.type)) {- // History sync maps messages media-free (footprint). Without the marker the row renders- // as an empty bubble — the DB copy wins over the engine-history placeholder in the- // dashboard merge — and the by-type stats filter would skip it.- metadata.media = { mimetype: '', omitted: true };- }- if (m.quotedMessage) metadata.quotedMessage = m.quotedMessage;- if (m.call) metadata.call = m.call;+ const metadata = buildMessageMetadata(m, true);const row = this.messageRepository.create({sessionId: id,waMessageId: m.id,@@ -1033,7 +1023,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatdirection: m.fromMe ? MessageDirection.OUTGOING : MessageDirection.INCOMING,timestamp: m.timestamp,status: MessageStatus.SENT,- metadata: Object.keys(metadata).length > 0 ? metadata : undefined,+ metadata,});// The chat panel orders by createdAt; stamp the real time so history sorts correctly.if (m.timestamp) {@@ -1291,26 +1281,13 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatincoming.senderPhone = await this.lidResolver.resolveSenderPhone(id, incoming.author ?? incoming.from);}- const metadata: Record<string, unknown> = {};- if (incoming.media) {- metadata.media = incoming.media;- }- if (incoming.quotedMessage) {- metadata.quotedMessage = incoming.quotedMessage;- }- if (incoming.call) {- metadata.call = incoming.call;- }+ const metadata = buildMessageMetadata(incoming);const chatName = incoming.contact?.pushName ?? incoming.contact?.name ?? undefined;const dbMessage = this.messageRepository.create({sessionId: id,- // Mirror saveOutgoingMessage's chokepoint: an engine that received a message but could- // not read its id back reports the empty sentinel, and NULL is what the non-partial- // (sessionId, waMessageId) unique index exempts — `''` would collide the second such- // message and lose the row.- waMessageId: incoming.id || undefined,+ waMessageId: storableWaMessageId(incoming.id),chatId: incoming.chatId,chatName,// Group poster (participant JID) — `from` is the group JID, so this is the stable@@ -1323,7 +1300,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatdirection: incoming.fromMe ? MessageDirection.OUTGOING : MessageDirection.INCOMING,timestamp: incoming.timestamp,status: MessageStatus.SENT,- metadata: Object.keys(metadata).length > 0 ? metadata : undefined,+ metadata,});// The hook chain above is async; a delete()/teardown can retire this engine while it@@ -1441,21 +1418,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// webhook/WS dispatch below is identical whether the insert won, lost, or failed — the// message.sent contract is unchanged.const outgoing: IncomingMessage = finalMessage;- const metadata: Record<string, unknown> = {};- if (outgoing.media) {- metadata.media = outgoing.media;- } else if (MEDIA_MESSAGE_TYPES.has(outgoing.type)) {- // The wwjs own-send echo carries no media field at all (Baileys emits an omitted- // marker); synthesize it so the dashboard renders the 📎 placeholder instead of an- // empty bubble, and the row stays countable in the by-type stats.- metadata.media = { mimetype: '', omitted: true };- }- if (outgoing.quotedMessage) {- metadata.quotedMessage = outgoing.quotedMessage;- }- if (outgoing.call) {- metadata.call = outgoing.call;- }+ const metadata = buildMessageMetadata(outgoing, true);// The ephemeral opt-out gates STORAGE only (mirrors onMessage); the live dispatch below// is today's contract and stays.@@ -1466,9 +1429,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatif (mayPersist) {const dbMessage = this.messageRepository.create({sessionId: id,- // Mirror onMessage's chokepoint: an unreadable id is the empty sentinel, stored as- // NULL — `''` would collide on the second such message.- waMessageId: outgoing.id || undefined,+ waMessageId: storableWaMessageId(outgoing.id),chatId: outgoing.chatId,from: outgoing.from,to: outgoing.to,@@ -1477,7 +1438,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatdirection: MessageDirection.OUTGOING,timestamp: outgoing.timestamp,status: MessageStatus.SENT,- metadata: Object.keys(metadata).length > 0 ? metadata : undefined,+ metadata,});// The hook chain above is async; a delete()/teardown can retire this engine while it// awaits. Re-check liveness so a late continuation can't persist an orphan row