typescript set parameter conditionally within a function

For my upcoming app, I am working on an API that will utilize Firebase FCM Admin to send messages. Below is the code snippet:

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

Do you have any suggestions for improving this implementation? I feel like there might be room for enhancement.

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

Answer №1

Instead of implementing a conditional assignment within a ternary expression, I prefer utilizing a function:

function replaceEmptyWithValue(value: string): string | null {
  return value === '' ? null : value;
}

This approach enhances the readability of your code when used in multiple instances:

topic = replaceEmptyWithValue(topic);
condition = replaceEmptyWithValue(condition);
token = replaceEmptyWithValue(token);

Answer №2

This code snippet contains a syntax error:

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

A corrected version could be:

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

However, the purpose of this block of code is not entirely clear.

If your intention is to assign null to variables with empty strings, you can simplify it like so:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble injecting $resource into my Jasmine unit test

I've encountered an issue while trying to test my self-written service that utilizes $resource. I'm facing difficulties when trying to inject $resource into my test spec. My setup includes Typescript with AngularJS 1.6.x, and here is a snippet o ...

Tips on how to perform a server-side redirection to a different page in a Nextjs application without refreshing the page while maintaining the URL

I am working on a [slug].js page where I need to fetch data from an API to display the destination page. export async function getServerSideProps({ query, res }) { const slug = query.slug; try { const destination = await RoutingAPI.matchSlu ...

Creating an array of strings using data from a separate array of objects in JavaScript/TypeScript

I want to generate a new array of strings based on an existing array of objects, with each object belonging to the Employee class and having a firstName field: assignees: Array<Employee>; options: string[]; I attempted to achieve this using the fol ...

Is it possible to preserve the numerical type of a percentage when applying number formatting?

After applying number formatting, I converted a numerical value of 150 to 150.00%. Although this is the desired display format with the percentage sign included, the data type remains as string instead of number. Is there a method to convert it back to a ...

An issue has occurred: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[NavbarComponent -> NavbarComponent

I've been working on implementing Google Auth login with Firebase, but I keep encountering an issue when trying to load another component or page after logging in. I've spent the entire day trying to debug this problem and it's really frustr ...

As I scroll past the top or bottom of the page, the body's background color transitions to a new shade

I am encountering an issue with my next.js app where the body background color is set to black. Here is the code in globals.css: body { background-color: black; padding: 0; margin: 0; font-family: 'Titillium Web', sans-serif; } However, ...

How should I structure my MySQL tables for efficiently storing a user's preferences in a map format?

My current project involves developing a web application that provides administrators with the ability to manage user information and access within the system. While most user details like name, email, and workID are straightforward, I am facing difficulty ...

Building a dropdown menu component in react native

Looking to implement a dropdown menu in React Native using TypeScript. Any suggestions on how to achieve this for both iOS and Android platforms? Check out this example of a dropdown menu ...

Mapping two objects of the same shape to each other recursively using TypeScript

I receive regular data from a specific source. This data consists of nested objects containing numerical values. For example: { a: 1, b: { c: 2, d: 3.1, }, } My objective is to organize this data into multiple TimeSeries objects of the same struct ...

Solve the issue of the __typename union

Imagine having the following union: export type IBookmarkItemFragment = | ({ __typename: "Story" } & { story: number; }) | ({ __typename: "Product" } & { product: number; }) | ({ __typename: "Project" } & { proj ...

The function of TypeScript map is not working properly

Encountering the error message "data.map is not a function" while trying to map data from a REST API request returning JSON data. It appears that the issue may stem from the data structure, as it seems like the returned data should be accessed with data.da ...

Having trouble retrieving data using a custom URL in Axios with ReactJs

My knowledge of Reactjs is still new and I am currently working on a project using nextjs. I have a component called Trending.js that successfully fetches data from the URL "https://jsonplaceholder.typicode.com/users". However, when I try to change the U ...

The union type cannot function effectively in a closed-off environment

Here is the code snippet I am working with: if (event.hasOwnProperty('body')) { Context.request = JSON.parse(event.body) as T; } else { Context.request = event; } The variable event is defined as follows: private static event: aws.IGateway ...

Ways to automatically adjust ideal camera position in R3F

I'm currently working on a model viewer and I've run into an issue where the camera position is consistently off when loading a 3D model (file type: GLB). While other online viewers seem to effortlessly adjust the camera angle regardless of the m ...

Angular 4 - Seeking clarification on the usage of *ngComponentOutlet

When using *ngComponentOutlet, the following code snippets are employed to handle the displaying: Below is a snippet of functional code: this.displayComponent({ 'objects':[ {component: ToDisplayAComponent, expanded: fals ...

Leverage React.JS to iterate through arrays and objects, rendering data seamlessly - even within nested objects

Development of Category's Filter component Implementing the rendering of data from a nested array using React Js Although I attempted to render it as seen below, it is not displaying anything The main focus is on the rendering part only var selecte ...

What is the correlation between single-page applications and server-side rendering?

My issue lies in grasping the concept of how server-side rendering single-page application frameworks like Next.js are able to receive pre-rendered full HTML on the front end without having to completely rewrite the entire page. The Next.js website explain ...

Structuring a TypeScript microservices repository on GitHub: Best practices to follow

Currently, I am in the process of designing a set of microservices. The structure I have been following involves each item having its own repository. my-project-logger my-project-numbers-service includes: my-project-logger type definitions + class obje ...

TypeScript - Converting into individual compiled files

Currently, I am working on a project that consists of lengthy source files. While this is advantageous for imports, it poses challenges in terms of maintenance. For instance: /main/core.ts export type Foo { ... } export interface Bar { ... } export cla ...

The Validator in Angular Formbuilder must have a specific character requirement

Can someone help me with a regex validator pattern in Angular Formbuilder to ensure that the field CityStateZip contains at least one comma as a special character? this.editAddressForm = this.formBuilder.group({ 'CustomerName': [null, ...