Home > Mobile >  typescript conditionaly set function parameter
typescript conditionaly set function parameter

Time:05-15

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) : "";

CodePudding user response:

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);

CodePudding user response:

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;
  • Related