export async function POST()

in src/app/api/v1/user/update-comm-option/route.ts [24:80]


export async function POST(req: NextRequest) {
  const token = await getToken({ req });

  if (typeof token?.subscriber?.fxa_uid === "string") {
    try {
      const {
        instantBreachAlerts,
        monthlyMonitorReport,
      }: EmailUpdateCommOptionRequest = await req.json();
      const subscriber = await getSubscriberByFxaUid(token.subscriber?.fxa_uid);

      if (!subscriber) {
        throw new Error("No subscriber found for current session.");
      }
      // "null"     = Do not send instant notifications. Newly added in MNTOR-1368
      // "affected" = Send breach alerts to the corresponding affected emails.
      // "primary"  = Send all breach alerts to user's primary email address.

      let allEmailsToPrimary;
      switch (instantBreachAlerts) {
        case "primary":
          allEmailsToPrimary = true;
          break;
        case "affected":
          allEmailsToPrimary = false;
          break;
        default:
          allEmailsToPrimary = null;
      }

      if (typeof instantBreachAlerts !== "undefined") {
        await setAllEmailsToPrimary(subscriber, allEmailsToPrimary);
      }
      if (typeof monthlyMonitorReport === "boolean") {
        const isFree = !(await isSubscriberPlus(subscriber.id));
        const preference = isFree
          ? { monthly_monitor_report_free: monthlyMonitorReport }
          : { monthly_monitor_report: monthlyMonitorReport };
        await updateEmailPreferenceForSubscriber(
          subscriber.id,
          isFree,
          preference,
        );
      }

      return NextResponse.json({
        success: true,
        message: "Communications options updated",
      });
    } catch (e) {
      logger.error(e);
      return NextResponse.json({ success: false }, { status: 500 });
    }
  } else {
    return NextResponse.json({ success: false }, { status: 401 });
  }
}