typescript条件设置函数参数



我在我的下一个应用程序构建api,这个api将使用firebase fcm admin发送消息。这是我的代码

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

有什么我可以改进的吗?我认为这是不好的

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

在三元表达式中不使用条件赋值,而是使用函数:

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

这使得您的三个调用更具可读性:

topic = emptyToNull(topic);
condition = emptyToNull(condition);
token = emptyToNull(token);

语法错误:

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

可能应该是:

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

但即使这样,我也不完全确定您希望这段代码完成什么。

如果你想将空字符串映射为null,但保留值,我就这样做:

if (topic === "")     topic = null;
if (condition === "") condition = null;
if (token === "")     token = null;

最新更新