0

Im building api in my next app, this api will send message using firebase fcm admin. This is my code

import type { NextApiRequest, NextApiResponse } from "next";
import { getMessaging } from "firebase-admin/messaging";

export default async function handler(req,res) {
  try{
    let { title, text, topic, condition, token } = req.body;
    topic === "" ? (topic = null) : "";
    condition === "" ? (condition = null) : "";
    token === "" ? (token = null) : "";
    const result = await getMessaging().send({
      notification: {
        title: title,
        body: text,
      },
      topic: topic,
      condition: condition,
      token: token,
    });
    res.status(200).send(result);
  } catch (err) {
    res.status(500).send(err);
  }
}

is there any improvement I can do? i think this is bad

    topic === "" ? (topic = null) : "";
    condition === "" ? (condition = null) : "";
    token === "" ? (token = null) : "";
Kin Kurnia
  • 23
  • 1
  • 6
  • this is sdk documentation: https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.messaging.md#messaging_class – Kin Kurnia May 14 '22 at 03:26

2 Answers2

0

Instead of a conditional assignment inside of a ternary expression I would use a function:

const emptyToNull(value: string): string | null {
  return value === '' ? null : value;
}

That makes your three invocations much more readable:

topic = emptyToNull(topic);
condition = emptyToNull(condition);
token = emptyToNull(token);
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
0

This is syntactically wrong:

topic === "" ? (topic = null) : "";
condition === "" ? (condition = null) : "";
token === "" ? (token = null) : "";

Likely it should be:

topic = (topic === "") ? null : "";
condition = (condition === "") ? null : "";
token = (token === "") ? null) : "";

But even with that, I'm not entirely sure what you expect this block of code to accomplish.

If you want to map empty strings to null, but otherwise keep the value, I'd just do:

if (topic === "")     topic = null;
if (condition === "") condition = null;
if (token === "")     token = null;
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807