All files / src/firebase pushNotificationPayload.ts

84.61% Statements 11/13
50% Branches 3/6
100% Functions 5/5
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                      3x   3x 7x 7x 7x         23x 15x     2x     3x   3x                          
export interface PushRemoteMessageLike {
  messageId?: string;
  notification?: {
    title?: string;
    body?: string;
  };
  data?: Record<string, unknown>;
}
 
export interface NormalizedPushNotificationPayload {
  title: string;
  body: string | null;
  notification_id: string | null;
  event_id: string | null;
  deep_link: string | null;
  data: Record<string, string>;
}
 
function toStringData(data?: Record<string, unknown>): Record<string, string> {
  Iif (!data) return {};
 
  return Object.entries(data).reduce<Record<string, string>>((acc, [key, value]) => {
    Iif (value == null) return acc;
    acc[key] = String(value);
    return acc;
  }, {});
}
 
function firstString(...values: Array<string | undefined>): string | null {
  const value = values.find((candidate) => candidate?.trim());
  return value ? value.trim() : null;
}
 
export function normalizePushNotificationPayload(
  remoteMessage: PushRemoteMessageLike,
): NormalizedPushNotificationPayload {
  const data = toStringData(remoteMessage.data);
 
  return {
    title: firstString(remoteMessage.notification?.title, data.title) ?? 'Notification',
    body: firstString(remoteMessage.notification?.body, data.body),
    notification_id: firstString(
      data.notification_id,
      data.notificationId,
      remoteMessage.messageId,
    ),
    event_id: firstString(data.event_id, data.eventId),
    deep_link: firstString(data.deep_link, data.deepLink),
    data,
  };
}