Tips for implementing conditional app.use() in nestJS backend strategies?

Trying to incorporate helmet into my nestJS application. I also require the inclusion of graphqlUploadExpress. How can I properly utilize the usesUpload condition to implement either helmet alone or along with upload?

import { NestFactory } from '@nestjs/core'
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.js'
import helmet from 'helmet'

const upload = graphqlUploadExpress()

export const main = async (
  AppModule: unknown,
  usesUpload = false
) => {
  const app = await NestFactory.create(AppModule, options)
  app.use(usesUpload ? helm : helm, upload) // <-- Appears incorrectly formatted.
  await app.listen(3000)
}

Answer №1

It appears that there may be a mistake in your ternary statement. The correct syntax can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator

If I were to rewrite the code personally, it would look like this:

import { NestFactory } from '@nestjs/core'
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.js'
import helmet from 'helmet'

const upload = graphqlUploadExpress()

export const main = async (
  AppModule: unknown,
  usesUpload = false
) => {
  const app = await NestFactory.create(AppModule, options)
  usesUpload && app.use(helm, upload)
  await app.listen(3000)
}

Instead of using a ternary operator, I am employing the Logical AND operator &&, which will execute conditionally based on the truthiness of the usesUpload argument.

You can find more information on the Logical AND operator here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND

------ EDIT ------

Upon further review of your request, it seems you are looking for a different logic, where you either use helm and upload OR just upload. While the previous explanation is still relevant, the following adjustment should meet your requirements:

usesUpload ? app.use(helm, upload) : app.use(upload)

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

The styled-components seem to be having trouble injecting the necessary CSS to handle all the various props

I am curious to understand the potential reasons for styled-components not injecting all the necessary CSS into a page's header. In an existing project, I have defined a simple button like this: const Button = styled.button` background-color: ...

Difficulty encountered in assigning a value to a variable when utilizing an async function in Node.js

While attempting to retrieve the jwtauthtoken from the user and passing it to a function called getUserId() in the imported JavaScript file, I encountered an issue where the returned value was undefined instead of the decoded ID. The getUserId() function ...

The Angular directive alters the scope, however, the template continues to display the unchanged value

I am working with a directive that looks like this: .directive('myDirective', function() { return { restrict: 'AE', replace: true, templateUrl: '/myDirective.html?v=' + window.buildNumber, ...

Ways to implement a setTimeout function to return to the initial div element?

I have a unique setup on my webpage with three divs. The first div features an html5 video, the second div contains buttons for interaction, and the third div acts as a thank you page that loops back to the beginning like a photo slide. I have shared my co ...

Querying a record in MongoDB with the "$" selector is not possible

Encountering a strange issue when working with NodeJS and Mongoose for querying records in MongoDB. I have defined my Product model as follows: const mongoose = require("mongoose"); const productSchema = new mongoose.Schema({ name: String, b ...

What could be the reason behind the failure of $cookieStore.get() in retrieving the value?

I am currently testing the cookie functionality in AngularJS. I'm encountering an issue where the console is returning 'undefined' when trying to retrieve a saved value from the cookie using $cookieStore.put(). It seems to work fine when set ...

What could be causing my MongoDB Node.js driver's $lookup aggregation query to not produce the expected results?

In my database, I have two collections: users and roles Each user has an array of roles assigned to them: { _id : 61582a79fd033339c73ee290 roles:[615825966bc7d715021ce8fc, 615825966bc7d715021ce8fd] } The roles are defined as follows: [ { ...

Dealt with and dismissed commitments in a personalized Jasmine Matcher

The Tale: A unique jasmine matcher has been crafted by us, with the ability to perform 2 key tasks: hover over a specified element verify the presence of a tooltip displaying the expected text Execution: toHaveTooltip: function() { return { ...

Parallel Execution Issue with RxJS Observable forkJoin

Struggling to understand why my requests aren't executing concurrently with the following code. As a newcomer to RxJS and observables, I would greatly appreciate any guidance on improving this snippet below. Essentially, I am fetching data from a REST ...

Determining the optimal location to execute external API calls within a NodeJS Rest API

I am currently developing a Rest API in Node.JS that utilizes a MySQL database as well as an external API to fetch data. I am using the Express framework with an architecture consisting of "Router, Middleware, Controller, Model." Howev ...

Rendering EJS templates and smoothly scrolling to a specific section on a webpage

I need to display my index page and automatically scroll down to the form section. One way I thought of doing this is by: app.post('/rsvp', (req, res) => { res.render('index/#rsvp', { errors: { email: 'Your email has already ...

Is there a way to restore the face's original orientation after it has been rotated

Just to note, I am aware that this question has been asked before. However, the previous answers did not address my specific situation and requirements. Currently, I am developing a Rubik's cube using three.js. To achieve lifelike rotations, I am rot ...

Tips on adjusting a JavaScript animation function

I'm currently working on adjusting the animation function within the "popup" class that controls the gallery section of a website. When the page loads, an image and background start expanding from zero scale in the center to 100 VIEWPORT HEIGHT (VH) a ...

Encountering a 500 internal server error when utilizing jQuery and Ajax with Laravel 5.2

I have been working on a post editing system using jQuery and Ajax in Laravel 5.2. But when I try to save the changes by clicking on the button inside my Bootstrap modal, an error pops up: Error: POST http://localhost:8000/edit 500 (Internal Server Error) ...

The download functionality in HTML5 is not functioning properly, so users are forced to rename files when downloading

For weeks, I've been struggling to change the name of the downloaded file. Despite my efforts, instead of being named Chrysanthemum.jpg, it ends up as a hash of the file like 241693260.jpg In my backend setup, I utilize Node.js and Express.js for man ...

Problem Alert: Click Event Not Functioning on Generated Links

Take a look at these two code snippets. Despite other jQuery functions in the same JS file working fine on the UL element, nothing seems to be happening with these. Is there something obvious that I am missing? <ul id="activityPaganation" class="paga ...

Adjust the appearance of a div according to the input value

When a user inputs the correct value (a number) into an input of type "number," I want a button to appear. I attempted var check=document.getElementById("buttonID").value == "1" followed by an if statement, but it seems I made a mistake somewhere. Here&ap ...

jquery script that retrieves the href attribute of the anchor tag located near the button that is currently being clicked

Hello there! I am trying to extract the href of a link when the button next to it is clicked by the user. However, the challenge is that there are multiple buttons and links on the page. For example, if the first button is clicked, I want to display "www. ...

A guide on using Selenium to interact with a doughnut pie chart element

I am having difficulty performing a click event on the colored ring part of this doughnut pie chart. Currently, I can locate the element for each section of the chart, but the click event is being triggered in the center of the chart (empty inner circle) w ...

Looking for insights on reading and presenting XML files from a URL? Learn how to achieve this effortlessly with the power

Currently, I'm in the process of developing an innovative Android application using PhoneGap. My main objective is to dynamically present the data stored within a customized XML file hosted on my website that follows the .php format. Do you happen to ...